Skip to content

Latest commit

 

History

History
155 lines (131 loc) · 4.46 KB

README.md

File metadata and controls

155 lines (131 loc) · 4.46 KB

While language

Codacy Badge

A small programming language made with Scala 3.4 and ANTLR 4.13.

This is a simple programming language that has only one loop instruction (while) and a single type (integer).

The language is implemented in two ways:

Interpreter Transpiler (Compiler)
Grammar Grammar (29 lines)
Abstract Syntax Abstract Syntax (23 lines)
Semantics Semantics (35 lines) Semantics (34 lines)
Parser Rules Listener (56 lines)
Main Main (4 lines) Main (4 lines)
Utility Classes Walker (20 lines)
Runner (14 lines)
ContextValue (13 lines)
Total 194 lines 193 lines

Examples

Here are some 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: ";
print sum

Fibonacci Sequence

print "Fibonacci Sequence";
a := 0;
b := 1;
while b <= 1000000 do {
  print b;
  b := a + b;
  a := b - a
}

Grammar

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
         | 'print' 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;

Compiling & Running

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