MJ MJCompiler
Programski prevodioci 1 · ETF Beograd

A compiler for
MicroJava, end‑to‑end.

From source text to running bytecode — lexing, LALR parsing, a 157-node AST, full semantic analysis, and code generation for a stack machine. Built for a university compiler-construction course, with namespaces as a language extension.

5
Compiler phases
157
AST node classes
44
Language tokens
2.2k
Lines of code
5
Bundled libraries
Verified end-to-end

Watch it compile — and run

A real program (test301.mj) with namespaces and arrays, taken from source all the way to output on the MicroJava VM. Every line below is actual compiler output.

test301.mj — source
program test301

namespace Konstante {
    const int jedan = 1, pet = 5;
    {}
}
namespace Nizovi {
    int niz[];
    {}
}
{
    void main()
        int bodovi;
    {
        bodovi = 0;  bodovi++;
        bodovi = bodovi + Konstante::jedan;
        bodovi = bodovi * Konstante::pet;
        Nizovi::niz = new int[3];
        Nizovi::niz[1] = 2;
        print(bodovi);
        return;
    }
}
semantic analysis
INFO Deklarisana konstanta:
     const Konstante::jedan = 1
INFO Deklarisana konstanta:
     const Konstante::pet = 5
INFO Deklarisana promenljiva:
     Nizovi::niz
INFO Obradjuje se funkcija main
✓ Parsiranje uspesno zavrseno!
bytecode → MicroJava VM
codeSize=171  dataSize=3  mainPC=0
 0: const_0    1: store_0
 2: load_0     3: const_1
 4: add        5: store_0
10: load_0    11: const_5
12: mul       20: print
21: const_3   22: newarray 1
...
$ run test301.obj
    9    6    6bc   -4
Completion took 1 ms
Language support

What the compiler handles

Reflecting what is implemented and verified in the source — not merely what the grammar accepts.

✓Primitive types int, char, boolwith type resolution & compatibility checks
✓Constants & variablesglobal and local, with duplicate-declaration checks
✓One-dimensional arraysnew int[n], indexed load/store, int-index check
✓Methods & formal parametersnested scopes, void main() requirement
✓Expressions & operators+ − * / %, unary minus, relational & logical
✓print / read, ++ / --type-checked, lowered to VM instructions
★Namespaces — Namespace::memberqualified constants, variables, methods, types
✓Parser error recoverypanic-mode sync to ; / , with dedicated error nodes
◐Control flow — if / for / breakgrammar & AST present; branch codegen in progress
◐Classes with inheritanceclass … extends parsed & partially checked

The headline feature: namespaces

Beyond the base language, MJCompiler adds namespaces. Declarations inside namespace X { … } are managed as qualified symbols and accessed with X::member — for constants, variables, methods, and types alike. The semantic pass validates that every referenced namespace exists and resolves each qualified name against the symbol table.

Built with

Toolchain

Java JFlex · lexer generator CUP · LALR parser generator Apache Ant · build log4j · logging symbol-table lib MicroJava VM · runtime