Skip to content

JanBaig/Tree-Walk-Interpreter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

56 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Tree-Walk Interpreter

Goals

  • Scanner
  • Print Abstract Syntax Tree (AST)
  • Parser
  • Variable Resolution Pass

Evaluates:

  • Expressions & Arithmetic
  • Branching & Looping
  • Variables, Functions & Function calls
  • Parameter binding & Function return statements
  • Classes, Inheritance, Instance variables, & Methods

Future Features

  • Ability to evaluate string interpolation
  • Add support for the C-style conditional or “ternary” operator ?:.

Example Program

class Cake {
  taste() {
    var adjective = "delicious";
    print "The " + this.flavor + " cake is " + adjective + "!";
  }
}

var cake = Cake();
cake.flavor = "German chocolate";
cake.taste(); // Prints "The German chocolate cake is delicious!".

BNF Grammer

programdeclaration* EOF ;

declarationclassDecl
               | funDecl
               | varDecl
               | statement ;

classDecl"class" IDENTIFIER ( "<" IDENTIFIER )? "{" function* "}" ;

funDecl"fun" function ;
functionIDENTIFIER "(" parameters? ")" block ;
parametersIDENTIFIER ( "," IDENTIFIER )* ;

varDecl"var" IDENTIFIER ( "=" expression )? ";" ;

statementexprStmt
               | forStmt
               | ifStmt
               | printStmt
               | returnStmt
               | whileStmt
               | block ;

block"{" declaration* "}" ;

ifStmt"if" "(" expression ")" statement
               ( "else" statement )? ;

whileStmt"while" "(" expression ")" statement ;

forStmt"for" "(" ( varDecl | exprStmt | ";" )
                 expression? ";"
                 expression? ")" statement ;

exprStmtexpression ";" ;
printStmt"print" expression ";" ;
returnStmt"return" expression? ";" ;

expressionassignment ;
assignment     → ( call ".")? IDENTIFIER "=" assignment
               | logic_or ;

logic_orlogic_and ( "or" logic_and )* ;
logic_andequality ( "and" equality )* ;
equalitycomparison ( ( "!=" | "==" ) comparison )* ;
comparisonterm ( ( ">" | ">=" | "<" | "<=" ) term )* ;
termfactor ( ( "-" | "+" ) factor )* ;
factorunary ( ( "/" | "*" ) unary )* ;
unary          → ( "!" | "-" ) unary | call ;
callprimary ( "(" arguments? ") | "." IDENTIFIER )* ;
argumentsexpression ( "," expression )* ;

primary"true" | "false" | "nil"
               | NUMBER | STRING | IDENTIFIER
               | "(" expression ")"
               | "super" "." IDENTIFIER ;

Great Learning Resources

About

Implementing a Tree-Walk Interpreter

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages