Skip to content

Latest commit

 

History

History
74 lines (65 loc) · 1.8 KB

README.md

File metadata and controls

74 lines (65 loc) · 1.8 KB

MoLang

This is an fully home made interpreter for a C like language. No generators were used: it’s entirely hand crafted in Java. I build this solely for educational purpose, so maybe you should not use this in production 🐴

Example code

// Basic operators and precedences
a = 10 * 30 + 1;
b = a / 3;
c = (10 + 3) * a;
d = a == b;
e = a < 10;

// Functions and local variables
fun = (x, y){
    local a = 3; //Overshadowing a
    return x * y * a;
}

// Functions as parameters
apply = (y,fun){
    return fun(y);
}
mul = (x){ return x * 5; }
result = apply(3, mul);

// Recursion
fibonacci = (x){
    if(x > 2){
        return fibonacci(x - 1) + fibonacci(x - 2);
    }
    return 1;
}
return fibonacci(10);

Features

  • Simple operators (+-*/%)
  • Assignment (=)
  • Operator precedence
  • Variables
  • Number literals
  • Multi statement programs (separated by ';')
  • Brackets for changing precedence
  • Bool type
  • Comparisons
  • Jumps (if)
  • Loops (while)
  • Functions
  • Functions as parameters
  • Functions as return type
  • Scopes
  • Local and global variables
  • Unary operators
  • Prefix operators
  • Infix operators
  • Local variables
  • I/O
  • Comments (single / multiline)
  • String type
  • Arrays

Usage in Java

String code = Resources.toString(Resources.getResource("complexExample.molang"), StandardCharsets.UTF_8);

MoLang lang = new MoLang(code);
assertEquals("55", lang.getScope().getReturnValue().toString());

Tests

The entire project is unit tested with around 30 JUnit5 tests and the current line coverage is 94%.

Assembly like interpreter

If you like interpreters you might check out my Assembly like interpreter written in Node.js