As of now, we have generated the sequence of token in lexical analysis phase, then fed these tokens to the parser which generated the sequence of statements which are grammatically right.
Next part comes to be setting up the interpreter object (initializing its members).
#1 Creating Interpreter Object
Open the FarmScript.cpp
file and just after the statement of parser.parse()
, we initialize the interpreter.
Interpreter interpreter(repl); // repl is false when giving file as input.
Interpreter::Interpreter(bool repl)
{
this->repl = repl;
if (!environment)
{
globals = new Environment();
environment = globals;
locals = new std::unordered_map<Expr *, int>();
Object clock(new ClockFunction());
environment->define("clock", clock);
}
}
#1.1 Initialization:
This constructor takes a boolean parameter repl
which presumably indicates whether the interpreter is being used in a Read-Eval-Print Loop (REPL)
mode or not.
#1.2 Setting REPL Flag:
The constructor sets the repl
member variable of the Interpreter
object to the value of the repl
parameter. This flag is used to control the behavior of the interpreter, such as whether to display prompts and handle input interactively.
#1.3 Environment Setup:
If the environment is not already initialized, the constructor creates a new Environment object called globals
and assigns it to the environment
member variable. This environment serves as the global scope for variable and function definitions.
#1.4 Locals Initialization:
The constructor initializes a locals
variable as a new unordered map (std::unordered_map<Expr *, int>()
). This map is used to track local variable bindings within function scopes.
#1.5 Clock Function:
The constructor creates a ClockFunction
object and wraps it in an Object. This function provides access to a clock utility for measuring time within the interpreted code.
#1.6 Global Definition:
The clock
object is defined in the global environment using the define()
method of the environment. This makes the clock function accessible to all code executed by the interpreter.