Mantra is implemented as a source-to-source translator with Java as a target. The Java compiler converts the resulting Java to bytecodes as usual. This means Java integrates trivially with Java and runs on any machine with a Java VM (1.5). Mantra has the potential to run much faster than Ruby or Python due to their purely interpreted nature. Current experiments support this expectation.
The current implementation is a devious but relatively small 3000 lines of Java. My current implementation took about six weeks. I was originally going to hold my implementation private until spring 2008 because I wanted my students to implement Mantra. Mantra has evolved way past a student project at this point, though, and so I am releasing it so people can try it out and learn from it.
My implementation's basic strategy is to create an intermediate form tree (an AST) from the source code and pass it between multiple components (passes or phases). The semantic analysis phase populates a symbol table (hash table mapping identifiers to information about them) and annotates the tree with information necessary for code generation.
Mantra is a four pass translator as follows:
- Parse Mantra source and build AST (mantra/tool/Mantra.g)
- Semantic analysis I: Walk class definition ASTs, declaring methods in symbol table (method scanClassAndDeclareMethods in mantra/tool/SemanticPhase.g)
- Semantic analysis II: define all symbols and walk method bodies computing expression types (mantra/tool/SemanticPhase.g)
- Code generation (mantra/tool/CodeGen.g)
The semantic analysis is done in two phases so that forward method references work. The first semantic phase finds all method definitions so that the second semantic phase can accurately answer if "foo" is a method or a variable.
The project is organized as follows: