Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

TLang Interpreter

A dynamic, mixed-paradigm programming language written entirely in C. TLang was built completely from scratch as a fun passion project to learn about compilers, interpreters, and language design. During the process of building this project, I did not consult ANY resources relating to compiler, programming language or software design. Everything from the lexer, parser, bytecode compiler, semantic analyzer, runtime, GC, etc, was reinvented in its entirety. This was VERY enjoyable, but also lead to a lot of suboptimal solutions as I was just trying to get everything working, and trying to add features that I thought were cool and fun to tinker around with, at the expense of design quality.

I may eventually write a paper on this that will act as documentation for this project and the language itself. However I have a lot to say which means it's gonna be a monumental task.

Table of Contents

  1. Motivation
  2. Features
  3. Architecture
  4. Getting Started
  5. Sample Code
  6. License
  7. Contact

Motivation

The primary motivation behind TLang was to learn and experiment with:

  • Hand-crafting a lexer and parser from scratch.
  • Implementing a bytecode compiler and runtime environment.
  • Designing and managing a custom garbage collector.
  • Exploring different programming paradigms (functional, imperative, object-oriented) in a single language.

Features

  • Dynamic Typing: No need to specify variable types; the runtime handles it.
  • Mixed Paradigms: Write in a functional style (lambdas, higher-order functions) or go object-oriented (classes), or mix both with imperative constructs.
  • Exceptions & Error Handling: try { ... } catch (e) { ... } style exception mechanism, you can also define your exceptions.
  • Custom Runtime & Garbage Collector: A hand-rolled memory management system for automatic cleanup.
  • Classes & Objects: Native class support with the class keyword and the -> arrow operator for member access, with access modifiers (private and public).
  • Lambda Functions: Define inline, nameless functions that can be passed around.
  • Built-In Standard Library Functions: A variety of helper methods like print(), println(), min(), max(), abs(), sleep(), etc.

Architecture

  1. Lexer: Hand-crafted tokenizer that reads source code and produces a stream of tokens.
  2. Parser: Top-down recursive descent parser that transforms tokens into an Abstract Syntax Tree (AST).
  3. Bytecode Compiler: Traverses the AST to generate a custom bytecode representation (the enum defining this is in compiler/compiler.h).
  4. Runtime/VM:
    • Stack-based virtual machine executes the generated bytecode.
    • Custom reference count garbage collector manages memory automatically.
    • Offers a standard library of built-in functions and classes.
  5. Data Structures: I implemetend my own maps and sets, mosly using standard hash functions, and chaining to handle collisions (and some linear probing).

Getting Started

Prerequisites

  • A C compiler (e.g., GCC or Clang).
  • Make.

Building From Source

  1. Clone the repository:
    git clone https://github.com/YourUserName/TLang.git
    cd TLang
  2. Build the project:
    make
    This should generate an executable (e.g., tlang).

Running a TLang Program

  1. Create a .tl file containing your TLang code (e.g. example.tl). The extension does not really matter, but its nice to add it :).
  2. Run it:
    ./tlang example.tl
  3. Enjoy experimenting with TLang’s dynamic features.
  4. You can run program with --help to get all options different flags.
   ./tlang --help

Sample Code

Below are a few examples illustrating various aspects of TLang’s syntax and features.

Functional Examples

Example 1: Higher-Order Function (Power)

func power(n) {
    if(n == 0) {
        return func (x) { return 1; };
    } else {
        let r = power(n - 1);
        return func (x) {
            return x * r(x);
        };
    }
}

let pow2 = power(4);
print(pow2(10));
  • power(n) returns a function that, when applied to a value x, computes (x^n).
  • Demonstrates recursion and higher-order functions.

Example 2: Approximating Sine

let PI = 3.1415926;

func sin(x, ite) {
    let res = x;
    let term = x;
    let sign = -1;
    let i = 2;
    while(i <= ite) {
        term = term * ((x * x) / ((i + 1) * i));
        res = res + sign * term;
        sign = sign * -1.0;
        i = i + 2;
    }
    return res;
}

print(sin(0.5 * PI, 40));
  • Computes an approximation of (\sin(x)) using a Taylor series expansion.
  • Showcases loops, conditionals, and arithmetic operations.

Example 3: Church Numerals (Functional Programming)

func church(n) {
    if(n == 0) {
        return func(f, x) {
            return x;
        };
    } else {
        return func(f, x) {
            return church(n-1)(f, f(x));
        };
    }
}

func getVal(church_numeral) {
    return church_numeral(
        func(n) { return n + 1; },
        0
    );
}

func addChurch(f, g) {
    return func(f_, x) {
        return f(f_, g(f_, x));
    };
}

println(getVal(addChurch(church(30), church(4))));
  • Demonstrates the expressiveness of TLang’s lambda functions and higher-order capabilities.

Example 4: Exceptions

exception Exception__;
exception Ex;
println(Exception__);

func test1(x) {
    try {
        raise Ex("hello");
    } catch (Exception__()) {
        print("Exception__");
    }
}

func a() {
    func b() {
        func c() {
            test1(2, 2);
        }
        c();
    }
    b();
}
a();

Object-Oriented Examples

Example 1: Binary Search Tree

class BSTNode(value) {
    let val = value;
    let left = null;
    let right = null;
}

class BST() {
    let root = null;

    private func _insert(r, val) {
        if(r == null) {
            return BSTNode(val);
        } else if(r->val < val) {
            r->left = _insert(r->left, val);
        } else {
            r->right = _insert(r->right, val);
        }
        return r;
    }

    func insert(val) {
        root = _insert(root,val);
    }
}

let t = BST();
let i = 0;
let sign = -1;
while(i < 10) {
    t->insert(i * sign);
    i = i + 1;
    sign = sign * -1;
}

func Preorder(root) {
    if(root == null) {
        return;
    }
    Preorder(root->left);
    println(root->val);
    Preorder(root->right);
}

Preorder(t->root);
  • Defines a BSTNode class and a BST class.
  • Illustrates how to define methods, use private helper functions, and traverse a tree.

Example 2: LinkedList

class LinkedList() {
    let head = null;
    let tail = null;
    let size = 0;

    private class Node(val) {
        let val = val;
        let next = null;
    }

    func add(val) {
        let node = Node(val);
        if(head == null) {
            head = node;
            tail = node;
        } else {
            tail->next = node;
            tail = node;
        }
        size = size + 1;
    }
}

let l = LinkedList();
for(let i = 0; i < 5; i = i + 1;) {
    l->add(i);
}

let tmp = l->head;
while(!(tmp == null)) {
    println(tmp->val);
    tmp = tmp->next;
}
  • Shows a simple singly linked list implementation.
  • Demonstrates using classes, nested classes, and iterating through nodes.

Note

This is just purely a passion project, and therefore was not tested rigourly, memory bugs and edge cases 100% exists somewhere.

Contact

  • Author: Theodor Semerdzhiev

Feel free to open an issue or pull request if you’d like to contribute or report a bug (there is probably a lot lol). Thank you for checking out TLang!


Happy coding with TLang!

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages