A small programming language created with ANTLR and Scala.
This is a programming language with only one loop instruction (while) and a single type (integer). The goal is to show that it is possible to implement a programming language with a only few lines of code.
The language is implemented in two ways:
- as an interpreter
- as a transpiler (compiler) for the Scala language.
Interpreter | Compiler (Transpiler) | |
---|---|---|
Grammar | Grammar (29 lines) | |
Parser Rules |
Listener (59 lines) Abstract Syntax (23 lines) |
|
Semantics | Semantics (31 lines) | Semantics (31 lines) |
Main | Main (3 lines) | Main (3 lines) |
Utility Classes |
Antr2Scala (10 lines) Walker (23 lines) Runner (12 lines) |
|
Total | 190 lines | 190 lines |
Here are some code examples:
Hello World
print "Hello World"
Sum of two numbers
print "Enter the first number:";
a := read;
print "Enter the second number:";
b := read;
sum := a + b;
print "The sum is:";
write sum
Fibonacci Sequence
print "Fibonacci Sequence";
a := 0;
b := 1;
while b <= 1000000 do {
write b;
b := a + b;
a := b - a
}
The formal syntax is as follows (ANTLR syntax):
grammar Whilelang;
program : seqStatement;
seqStatement: statement (';' statement)* ;
statement: ID ':=' expression # attrib
| 'skip' # skip
| 'if' bool 'then' statement 'else' statement # if
| 'while' bool 'do' statement # while
| 'print' Text # print
| 'write' expression # write
| '{' seqStatement '}' # block
;
expression: INT # int
| 'read' # read
| ID # id
| expression '*' expression # binOp
| expression ('+'|'-') expression # binOp
| '(' expression ')' # expParen
;
bool: ('true'|'false') # boolean
| expression '=' expression # relOp
| expression '<=' expression # relOp
| 'not' bool # not
| bool 'and' bool # and
| '(' bool ')' # boolParen
;
INT: ('0'..'9')+ ;
ID: ('a'..'z')+;
Text: '"' .*? '"';
Space: [ \t\n\r] -> skip;
To compile you need to install sbt. The easiest way is to use Sdkman (Linux) or Scoop (Windows).
$ sbt
sbt> clean
sbt> compile
# To run the interpreter
sbt> runMain whilelang.interpreter.main sum.while
# To run the transpiler
sbt> runMain whilelang.compiler.main sum.while