AST Compiler
Alright ladies and gentlemen, we are finally at the meat of the actual language. Everything else is really supplementary to the AST Compiler. It really is the main sort of chef for the whole dish of our programming language. It is the largest part of the entire language, taking up about 1700 of the 7000-ish lines of the entire vm.
Now, this means that this entire page is going to be lengthy, and in all honesty I will try my best but the context is something that gets built on with each new part of the language added. It isn’t too terrible but it is one of the harder portions of the language.
Now, the AST compiler builds the AST(s), what those are will be mentioned later on when we get to expressions and what not, but it’s place in the pipeline is that it calls on the scanner to get a token at a time, and from these tokens it builds context based on set out rules in order to build expressions representative of the intention behind incoming tokens. These expressions are then handed over to the type checker which runs through them to make sure they are good, and then pushes these expressions into the bytecode compiler, freeing them before moving on to the next expression, one expression at a time.
I understand that is very verbose, and it requires a lot of context that I cannot outright give immediately, but here is that whole pattern in its smallest form from one of the first passes of the compiler:
static void expressionStatement(ASTparser* parser, TypeChecker* checker, AstCompiler* compiler, Vm* vm)
{
//compile and check expression, then compile again to bytecode
Expr* expr = astExpression(parser, compiler, vm);
ValueType type = checkExpression(checker, expr, parser);
if (type != VALUE_ERROR)
{
compileBytecode(expr, parser, &compiler->function->chunk, compiler, vm);
emitByte(OP_POP, &compiler->function->chunk, parser, vm);
}
//consume the ; and free memory
consume(T_SEMICOLON, "Please end all of your expressions with a ';'!", "SYNTAX ERROR", parser);
freeExpr(expr, vm);
}Found in /src/ASTcompiler.c
This is actually a beautiful representation of this process in action. Now this is still a little bit beyond the scope of what the entire AST does, as that astExpression() function basically recursively walks down a tree of functions in order to determine the order of actual expression creation, but know that it basically goes through the tokens of an expression (something like 2+3 for example) and turns it into a tree [+, 2, 3] pretty much.
However, after this expression is created, you can see that we immediately check the type of the expression. So we pass the tree structure we made into the type checker, and it goes through it to evaluate how the types of the class interact to make sure that everything is all good.
We then check to see if the type of the expression was correct, this is actually the advantage of a statically typed language, we know what the type of the expression should be based on the inner types. Thus, we can outright check to see if the expression does not mesh well here, and return an error before wasting time running any bugged code.
After making sure that the user’s expression is well written, we then compile it to bytecode and this goes directly onto the vm to be run whenever the compilation is done. In all honesty it is a bit simple here but of course there is nuance to it as well. This is a cherry picked example of an expressionStatement, notice that, there are expressions and statements in the compiler, we treat them differently
A given expression is made up of singular tokens and evaluates out to something. Hence it is technically compiled before a statement, which is made up of expressions internally. An expression would be something like a math calculation 1+2 == 3 but a statement would be something like 1+2; or if(1+2 == 3) and would then get treated differently and parsed differently as well.
We also call the consume function here, which is called throughout the entire compiler. Basically we just call the next token in the scanner with what we expect. If we get the correct token, then we proceed as normal, but if we do not, we error. It is why many languages have you put ; after each statement. It is so they know they are at the end of a statement and can being parsing the next statement.
The Parser and Compiler Structs
Now of course, the previous section had basically the real outline of how the parser fits within of the VM, it touches all of those parts and decides what happens when, and that is a very large part of what it does, but that is really not the main purpose, the main purpose is to actually create Abstract Syntax Trees:
typedef struct ASTparser
{
Scanner scanner;
Token current;
Token previous;
bool hadError;
bool panicMode;
} ASTparser;Found in /src/ASTcompiler.h
There are a lot of structs that tend to go into this, so we should start with the most basic. This is basically the internal struct that is representative of the AST Parser. This parser is a bit different from the compiler because it really feels like more so book keeping rather than action. We keep track of the current token that we are looking at, as well as what the previous one was, allowing us to use this for context.
In tandem we also use this as a point to check if there was a syntax error during compilation, and if there was, we need to try and handle it using the panicMode boolean, which is described more down below in the error handling of this page. Notice also that this owns the scanner object, it needs direct access to it because it is what calls the scanner each time we need a new token.
typedef struct AstCompiler
{
Local locals[MAX_LOCALS];
UpValueInfo upvalues[MAX_UPVALUES];
int localCount;
int scopeDepth;
bool isTopLevel;
bool isClassMethod;
ObjFunction* function; //that you write to
struct AstCompiler* enclosing;
} AstCompiler;Found in /src/ASTcompiler.h
Now if the AST Parser was really in line with the scanner, this is more so in line with the actual compilation of what is being scanned into our bytecode. A compiler is an interesting object, it is very flat whenever we have a single bytecode array, but this changes whenever we end up with functions.
As soon as functions are introduced, each function needs to own it’s own bytecode array, meaning that we need a separate compiler to understand what context we are in during compilation. This is because we are limited by memory and need to be able to resolve things like allocating and freeing local variables on our program’s stack
Not only that but we need to know how many function calls we are in, each new function call creates a new compiler inside of the current compiler, which eventually translates to a new function object on our VM’s stack, a limited stack mind you, hence this struct is here for making sure that we really know where we are in our program.
If it feels like it’s a bit much it’s because it certainly is a difficult portion of the language making to understand. Functions and then upclosures are hard concepts to grasp because we go from a single bytecode array to now multiple, but we still want to have the convenience of all of our local variables being accessed on the stack. Just imagine it as a little bookkeeping box thats a compass for what bytecode we are writing to.
typedef struct {
const char* name;
int length;
int depth;
bool isCaptured;
} Local;Found in /src/ASTcompiler.h
A local is basically a local variable, in our program we have different blocks which signify different levels of scope within of our program right. An outer variable should not be able to reference a variable in a deeper scope than it is, or be able to access that variable after the scope ends. However the inner variable should be able to access the outer variable right.
This is basically what this local value achieves. We end up with a value that is basically just a name (of the variable), the length of it, how deep we are in the scope, and whether a function closure has captured it and should be able to access it. With this information we then have an index in the array as it’s stack slot at runtime, so we can access it easily.
The Abstract Syntax Tree
typedef enum {
EXPR_LITERAL,
EXPR_BINARY,
EXPR_UNARY,
EXPR_GROUPING,
EXPR_ASSIGN,
EXPR_VARIABLE,
EXPR_CALL,
EXPR_STATIC_ARRAY,
EXPR_GET_ARRAY_INDEX,
EXPR_SET_ARRAY_INDEX,
EXPR_OR,
EXPR_AND,
EXPR_SET_FIELD,
EXPR_GET_FIELD,
EXPR_THIS,
EXPR_PULLF
} ExprType;Found in /src/Expr.h
You know, in all honest copy and pasting this enum, I did not remember there being this many expressions haha. Well, either way, these are basically all of the different expressions that the AST-Compiler can actually compile into. The reason why we need an enum with the “type” of the AST is not only for decoration or extra information, but this is actually key for the type checker to understand what is coming next and how the types held within these expressions should be held.
typedef struct Expr {
ExprType type;
int line;
union {
Literal literal;
Binary binary;
Unary unary;
Variable variable;
Grouping grouping;
VarAssignment var_assignment;
Call objectCall;
staticArray staticArray;
GetArray getArray;
SetArray setArray;
AndExpr andExpr;
OrExpr orExpr;
SetField setField;
GetField getField;
Exprthis _this;
ExprPullf pullf;
};
} Expr;Found in /src/Expr.h
add explanation here, the tagged union pattern again (same idea as Value on the chunks page, link back to it), every node stores its line for errors, and there is a createX() function for every node type plus freeExpr()
This is the expr struct, and this is basically the main tree of the Abstract Syntax Tree. All of those inner values in the union work in the same way that values work inside of chunks, where things all share the same memory.
This is just a fun little C trick with memory that lets us be a bit more loose with how we define each expression. Of course a single expression struct holds the specific expression type, this is so we can directly access this for type checking. We also then have a book keeping line for error reports.
In real essence though each of those structs inside of the union is just a slightly modified expression that is used to represent some type of operation that we can perform in the language. In the below example we see a binary expression for example, which just holds two different values and a mathematical operation:
typedef struct
{
struct Expr* left;
struct Expr* right;
const char* operator;
} Binary;Found in /src/Expr.h
This is one of those tree nodes right, you can see how this looks more and more like a tree data structure as well. We have a pointer to another node to the right and to the left, this basically being the things that the operator is working on. So in a very basic example we can have something like 1 + 2 where left = 1 right = 2 and operator = +. With this of course we have a LOT of different possibilities.
Of course the reason why we need to have expressions as our left and right is because of the ability to nest these values, so (1+2) / (5-9) will be a binary expression with both the left and right also being binary expressions, but each of those binary expressions will have a left and right of a literal value!
Of course having this struct is all fine and dandy, but the AST Compiler once again has a LOT of responsibility, not only to we need to know what to do with this expression, we need to know how and when to build it, and building it looks like this:
Expr* createBinary(Expr* left, Expr* right, const char* operator, int line, struct Vm* vm)
{
//allocate the expr in memory and set it's type
Expr* expr = (Expr*)reallocate(NULL, 0, sizeof(Expr), vm);
expr->type = EXPR_BINARY;
expr->line = line;
expr->binary.operator = operator;
expr->binary.right = right;
expr->binary.left = left;
return expr;
}Found in /src/Expr.c
Using pratt parsing we know that we have an expression to the left, an expression to the right, and then an operator, and hence we must have a binary expression. The lucky part is, no matter what these expressions might be, literals or other compound or unary expressions, we know that they have to have been created first because of Pratt Parsing rules (see below), and hence we can rely on them directly to make our binary expression.
Now the actual code is pretty simple. We allocate a new expression struct, and then we set it’s type to be of EXPR_BINARY. With this we have a zero-d out struct with data that is oh so ripe to fill. We update the inner values and then return the expression so that way we might pass it into another createX() expression function, or even pass it over to a type checker, or a bytecode compiler, shoot maybe even all three!
Pratt Parsing
This is one of the really fundamental concepts for the entire compiler. Pratt parsing is basically just a method of being able to apply an order of operations to the way things are parsed. Inside of a given expression, certain things go before others, so multiplication before addition, negation before multiplication, all of that.
This is allows for us to basically look for the operation that we actually are in terms of precedence:
Precedence
typedef enum
{
PREC_NONE,
PREC_ASSIGNMENT, // =
PREC_OR, // || / or
PREC_AND, // && / and
PREC_EQUALITY, // ==
PREC_COMPARISION, // >, <, >=, <=
PREC_TERM, // +, -
PREC_FACTOR, // *, /
PREC_UNARY, // -, !
PREC_CALL, // . ()
PREC_PRIMARY //literal values like strings or bools or doubles
} Precedence;Found in /src/ASTcompiler.c
This are the rules that explain precedence for Oli-Nat’s compiler. In essence each one of these corresponds to an action as you can see in the comments on the right. Based on what the given symbol or token that we are looking at, we can understand the level of precedence that it has.
So a token of 5 we know would have the PREC_PRIMARY, and we would then look at this large set of rules, which is defined below, and then based on the type of precedence and the type of token we have we would end up choosing a function that parses the string of this token into one of the above mentioned expressions. These rules are defined as follows:
The Rules Table
typedef Expr* (*PrefixFn)(bool canAssign, ASTparser* parser, AstCompiler* compiler, Vm* vm);
typedef Expr* (*InfixFn)(bool canAssign, ASTparser* parser, AstCompiler* compiler, Expr* left, Vm* vm);
typedef struct
{
PrefixFn prefix;
InfixFn infix;
Precedence precedence;
} ParseRule;Found in /src/ASTcompiler.c
Sorry, before we get to the actual rule table I realize it would be best if you understood what each of the actual pieces of data in the rules table meant. Basically, we have these things called function pointers in C, which as you guessed it, allow us to basically point to a function in memory. This is actually really nice because in a way we can treat the function dynamically, and assign different function pointers to whatever expression compilation function we want:
ParseRule rules[] = {
[T_LEFT_PAREN] = {grouping,functionCall,PREC_CALL},
[T_LEFT_BRACKET] = {Array,acesssArray,PREC_CALL},
[T_DOT] = {NULL, dot, PREC_CALL},
[T_MINUS] = {unary, binary,PREC_TERM},
[T_PLUS] = {NULL, binary, PREC_TERM},
[T_SEMICOLON] = {NULL, NULL, PREC_NONE},
[T_STAR] = {NULL, binary, PREC_FACTOR},
[T_EQUAL_EQUAL] = {NULL, binary, PREC_EQUALITY},
[T_IDENTIFIER] = {variable, NULL, PREC_NONE},
[T_INTEGER_VAL] = {number, NULL, PREC_NONE},
[T_AND] = {NULL, _and, PREC_AND},
[T_OR] = {NULL, _or, PREC_OR},
//... one row for every token type
};Found in /src/ASTcompiler.c (trimmed)
add explanation here, prefix vs infix with real rows: T_MINUS has both unary and binary which is how -x and a - b share a token, T_LEFT_PAREN is both grouping and a function call, T_LEFT_BRACKET is both an array literal and indexing. NULL means that token can’t start or continue an expression
This is the actual rules, and it helps to also explain the difference between that infix and prefix function difference. The reason why those hold two different spots is because the context of where a given symbol is at is very important. Something like -x and a - b would both end up using the T_Minus token, so we need to have the context of being either with unary or binary precedence. This is then explained later on in the next bit of code.
However before that, I want to talk more about this list of rules. It is a very long and comprehensive array of the struct that defines the actual action that we do for this given token, and is what we refer back to when actually making a token into an expression. It is the real brains of the operation. You will notice some values are NULL, and this is because something like ; is still a needed token we need to know how to parse, but does not create an expression. It still needs an entry though because the following function takes the data from this rules array and applies it:
parserPrecedence()
static Expr* parserPrecedence(Precedence precedence, ASTparser* parser, AstCompiler* compiler, Vm* vm)
{
//advance to next token, get the rule for the literal value and then some
//error catching for bad snytax
advance(parser);
PrefixFn prefixRule = getRule(parser->previous.type)->prefix;
if (prefixRule == NULL)
{
error("Expected expression", "SYNTAX ERROR", parser);
return NULL;
}
bool canAssign = precedence <= PREC_ASSIGNMENT; //for when i add variables
Expr* left = prefixRule(precedence <= PREC_ASSIGNMENT, parser, compiler, vm);
//consume the actual expression operator and what not, lead the recursive portion of
//this setup
while (precedence <= getRule(parser->current.type)->precedence)
{
advance(parser);
InfixFn infixRule = getRule(parser->previous.type)->infix;
left = infixRule(canAssign, parser, compiler, left, vm);
}
return left;
}Found in /src/ASTcompiler.c
This is the MOST IMPORTANT function in the entire codebase, at least on the compilation side of things. Every single expression starts here, and most of them come back here several times before they’re done. So I’m going to go through it line by line.
First, we call advance(), which consumes the next token and stores it as parser->previous. Then we use that token’s type to index straight into the rules[] array, which gives us its ParseRule, and from that we grab its prefix function.
Why prefix first? Because every expression has to start with something: a number, a variable name, a -, a (, and so on. If the token we just read doesn’t have one, like a ) or a ;, then it can’t possibly start an expression, so we report Expected expression and bail out.
Next is canAssign. It’s a bit of shoddy craftsmanship on my part, but it does an important job: it decides whether an = is allowed at this point. Assignment has the lowest precedence of everything, so canAssign is only true when we’re parsing at PREC_ASSIGNMENT level. That way a = 5 works, but in something like a + b = 5, the b gets parsed at a higher precedence (as the right side of the +), so it isn’t allowed to be assigned to.
Then we call the prefix function, which turns that first token into an expression, like a literal 2, and stores it in left.
Now for the loop, which is where the recursion and precedence magic really happens. The loop looks at the next token, and as long as it’s an operator whose precedence is at least as high as the precedence we were called with, we keep going. We advance() past the operator, get its infix function, and call it with everything we’ve built so far as left. The infix function parses the right-hand side and hands back a new, bigger expression, which becomes our new left.
Let’s trace 2 + 3 * 4:
- We start at the lowest precedence. The prefix function for
2gives usleft = 2. - The next token is
+(PREC_TERM), which is high enough, so we callbinary()for it. binary()parses its right side by callingparserPrecedence()again, but at one level abovePREC_TERM.- Inside that call, the prefix function for
3gives usleft = 3. The next token is*(PREC_FACTOR), which is higher thanPREC_TERM, so the loop keeps going and builds3 * 4. - Then we run out of tokens, so that inner call returns
3 * 4back tobinary(), which builds2 + (3 * 4).
The end result is a tree with the + at the top and the * underneath it, on the right: [*, 3, 4, +, 2]
Since the tree gets evaluated from the bottom up, 3 * 4 is calculated before the +, which is exactly what the rules of math say should happen.
If the expression had been 2 * 3 + 4 instead, the inner call for the * would hit the +, see that PREC_TERM is lower than what it was asked for, and stop. It would return just 2 * 3, and the outer loop would pick up the + 4 afterwards. So the precedence check in that while condition decides which operator grabs which numbers.
static Expr* binary(bool canAssign, ASTparser* parser, AstCompiler* compiler, Expr* left, Vm* vm)
{
//compile the second literal and also check out the type of operation you got
TokenType operatorType = parser->previous.type;
ParseRule* rule = getRule(operatorType);
Expr* right = parserPrecedence((Precedence)(rule->precedence+1), parser, compiler, vm);
switch (operatorType)
{
case T_PLUS: return createBinary(left, right, "+", parser->previous.line, vm);
case T_MINUS: return createBinary(left, right, "-", parser->previous.line, vm);
case T_STAR: return createBinary(left, right, "*", parser->previous.line, vm);
case T_SLASH: return createBinary(left, right, "/", parser->previous.line, vm);
case T_BANG_EQUAL: return createBinary(left, right, "!=", parser->previous.line, vm);
case T_EQUAL_EQUAL: return createBinary(left, right, "==", parser->previous.line, vm);
case T_GREATER: return createBinary(left, right, ">", parser->previous.line, vm);
case T_GREATER_EQUAL: return createBinary(left, right, ">=", parser->previous.line, vm);
case T_LESS: return createBinary(left, right, "<", parser->previous.line, vm);
case T_LESS_EQUAL: return createBinary(left, right, "<=", parser->previous.line, vm);
}
}Found in /src/ASTcompiler.c
add explanation here, the precedence + 1 for the right side, why that makes operators left associative and lets * grab the 3 before + does, and that operators are stored as strings which the bytecode compiler later strcmp’s
This is an example of one of the more fun functions that maintains the logic for creation of expressions. The binary function parses all two given literals interacting with each other through an operator right.
The issue here is we need to be able to handle (1/3*5) + (-2+36-5) as clean as we do (1 + 2) Of course a lot of this is handled for us by the parser precedence function as described above, but we still need to make the call for it with all of the right information. That is exactly what those few first lines do, they get the expression for whatever is to the right of the binary expression, allowing us to go through with this process, making expressions out of literals and then expressions with those expressions made of literals. We need to be careful for things on the right that have higher precedence, like 3 + 2 * 4, the multiplication should go first, it is why we have the +1 there.
Enough rambling of course, we need the actual logic, and it is far less elegant than figuring out how to apply the logic is. We basically have one giant switch statement that handles what all of the possible string versions of the token for the operator in the binary expression might be. It might seem verbose to store them as strings now, but later on this lets us use strcmp on them for the bytecode compiler, which makes the inconvience very worth it. We really just look at the operator and then create the expression though.
Parsing Expressions
For the sake of being thorough, and in doubt of my own explaining capability, I want to showcase what the parsing of a literal value might look like, and showcase how things like && / || are a bit special in Oli-Nat for the purpose of slightly better performance.
static Expr* number(bool canAssign, ASTparser* parser, AstCompiler* compiler, Vm* vm)
{
//handle all three possible numbers you can have
switch (parser->previous.type)
{
case T_DOUBLE_VAL:
{
double value = strtod(parser->previous.lexemeStart, NULL);
return createLiteralDouble(value, parser->previous.line, vm);
}
case T_FLOAT_VAL:
{
float value = strtof(parser->previous.lexemeStart, NULL);
return createLiteralFloat(value, parser->previous.line, vm);
}
case T_INTEGER_VAL:
{
long value = strtol(parser->previous.lexemeStart, NULL, 10);
return createLiteralInt((int)value, parser->previous.line, vm);
}
default:
return NULL; //unreachable (hopefully)
}
}Found in /src/ASTcompiler.c
Even though Oli-Nat has multiple different literals, and we are a typed language, we can really abstract all of that out into a single number expression creation. The reason for this is because we know we have a number, so we can just use the built in strtod/strtof/strtol function in C to go from our source code into a real raw C value, which we then store and send on down the line to be type checked, turned into an internal Oli-Nat value, and then made into bytecode.
static Expr* _and(bool canAssign, ASTparser* parser, AstCompiler* compiler, Expr* left, Vm* vm)
{
Expr* right = parserPrecedence(PREC_AND, parser, compiler, vm);
return createAnd(left, right, parser->previous.line, vm);
}
static Expr* _or(bool canAssign, ASTparser* parser, AstCompiler* compiler, Expr* left, Vm* vm)
{
Expr* right = parserPrecedence(PREC_AND, parser, compiler, vm);
return createOr(left, right, parser->previous.line, vm);
}Found in /src/ASTcompiler.c
A little bit of an extra tid bit as well that I thought fits best here. Inside of Oli-Nat these docs have show how a binary operation works between two given literals. Of course we need to follow the rules of precedence, but we can sort of for-go that a bit with the boolean binaries.
This is because these end up short-circuiting. We know that if we have an && expression, and the left hand side we already parsed is false, we know the whole expression is false, so we do not even need to parse the right, and the inverse is of course true for the || operation via De Morgan’s Laws.
Syntactic Sugar
static Expr* variable(bool canAssign, ASTparser* parser, AstCompiler* compiler, Vm* vm)
{
//save the name of the var
const char* name = parser->previous.lexemeStart;
int length = parser->previous.length;
int line = parser->previous.line;
if (match(T_EQUAL, parser) && canAssign)
{
Expr* value = astExpression(parser, compiler, vm);
return createVarAssignment(name, length, value, line, vm);
}
Expr* self = createVariable(name, length, line, vm); //helper for doing the fancy += syntax
if (match(T_PLUS_EQUAL, parser) && canAssign)
{
Expr* value = astExpression(parser, compiler, vm);
Expr* binary = createBinary(self, value, "+", line, vm);
return createVarAssignment(name, length, binary, line, vm);
}
//... the same pattern for -=, *=, /=, ++ and --
return self;
}Found in /src/ASTcompiler.c (trimmed)
Here’s something I think is really cool. You might expect that shortcuts like += and ++ would need their very own expression node, or maybe even their own opcode. They don’t! Instead, the parser quietly rewrites them into code that already exists.
When variable() sees x += 5, it builds the exact same tree it would have built if you’d typed out x = x + 5 by hand. It makes a Variable node for x (that’s the self in the code), puts it in a Binary node with your value and a +, and then wraps the whole thing in a regular VarAssignment. x++ works the same way, just with a literal 1 as the right side, so it becomes x = x + 1.
This trick is called desugaring, because shortcuts like these are known as syntactic sugar. They make the language nicer to write, but they don’t add anything the language couldn’t already do. Real compilers use this technique all the time, and the payoff is huge: the type checker and bytecode compiler never even find out that += exists. They only ever see a normal assignment and a normal addition, which they already know how to handle, so I didn’t have to touch either of them to add these shortcuts.
It also means the shortcuts follow the exact same rules as the long version. If x is an int, then x += 2.5 is a type error, because x = x + 2.5 would be too.
Cool Note: There is one side effect you might not expect if you’re coming from C. In C, x++ gives back the old value of x, before the increment. Since Oli-Nat turns x++ into x = x + 1, it gives back the new value. So if x is 5, println(x++); prints 6, not 5.
if (match(T_PLUS_PLUS, parser))
{
Expr* get = createGetField(left, fieldName, nameLength, line, vm);
Expr* one = createLiteralInt(1, line, vm);
Expr* binary = createBinary(get, one, "+", line, vm);
//create a copy of left since it would get shared between binary and this and get freed twice
Expr* leftCopy = ALLOCATE(Expr, 1, vm);
*leftCopy = *left;
return createSetField(leftCopy, binary, fieldName, nameLength, line, vm);
}Found in /src/ASTcompiler.c (trimmed, inside dot())
The same process applies here as well of course. Fields do the same thing in dot(), this means that under the hood if we do instance.field++, this basically then ends up becoming instance.field = instance.field + 1 and is compiled that way, we love to add some sugar.
We also have to create this leftCopy which basically means that the same node does not get freed twice and the compiler does not segfault, we create two expressions out of one pretty much.
Declarations and Statements
So far, most of the things that I have talked about have been expressions and not statements. Expressions use Pratt Parsing and compile into the given expression structs, but statements follow plain recursive descent. There was a small bit of a side tangent about the difference between the two and a quick overview for context, but this section will go into more detail.
static void declaration(ASTparser* parser, TypeChecker* checker, AstCompiler* compiler, Vm* vm)
{
if (match(T_MAKE, parser))
{
//get / consume the declaraed type, and then name
ValueType type = getVarDeclarationType(parser, checker);
//check for [] for arrays
if (match(T_LEFT_BRACKET, parser))
{
consume(T_RIGHT_BRACKET, "Please match all '[' with a ']',", "SYNTAX ERROR", parser);
type = toArrayType(type);
}
//get var name
consume(T_IDENTIFIER, "You must name your variables and functions, they get sad if you dont.", "SYNTAX ERROR", parser);
if (check(T_LEFT_PAREN, parser))
{
functionDeclaration(parser, checker, compiler, vm, type, false);
}
else
{
varDeclaration(parser, checker, compiler, vm, type);
}
}
else if (match(T_HASH_PULLF, parser))
{
nativeFunction(parser, checker, compiler, vm);
}
else if (match(T_CLASS, parser))
{
classDeclaration(parser, checker, compiler, vm);
}
else
{
statement(parser, checker, compiler, vm);
}
if (parser->panicMode) synchronize(parser);
}Found in /src/ASTcompiler.c
add explanation here, the dispatcher, make could be a variable or a function and you tell by whether a ’(’ comes after the name, then pullf, class, and everything else is a statement. Mention the synchronize call at the bottom and point to error handling
Now this we generally call whenever something is declared. Shocking, I know. However this lets us handle everything in the language, we use specifc tokens as keywords in order to know what kind of statement to call from a declaration. make is either a variable or a function/ declaration.
If we are not declaring some form of man made allocation, then we know we have either a native function call, which is handled a bit difference, they are all already loaded in and are just pointers to C function, you can check the natives tab for more info. We can also have a class declaration which does through it’s own statement parsing. Like consuming the name and then just letting us understand a different context of course.
Now, the else statement is for all of the different possible things, these will be gone over next. Skipping over though though, the synchronize() function basically consumes tokens until we get to what we can assume to be the next statement. This is so when we encounter one error we can kind of try and go back to what the context is, so we do not cascade into a large number of false errors.
static void statement(ASTparser* parser, TypeChecker* checker, AstCompiler* compiler, Vm* vm)
{
if (match(T_LEFT_BRACE, parser))
{
beginScope(compiler);
block(parser, checker, compiler, vm);
endScope(compiler, checker, vm, parser);
}
else if (match(T_IF, parser))
{
ifStatement(parser, checker, compiler, vm);
}
else if (match(T_WHILE, parser))
{
whileStatement(parser, checker, compiler, vm);
}
else if (match(T_FOR, parser))
{
forStatement(parser, checker, compiler, vm);
}
else if (match(T_RETURN, parser))
{
returnStatement(parser, checker, compiler, vm);
}
else
{
expressionStatement(parser, checker, compiler, vm);
}
}Found in /src/ASTcompiler.c
This is then the statement which is what I talked about in the previous section. We understand that if we are not declaring something like a variable or a function, then we are probably doing some kind of scope or control flow. So we either check out for a { to then parse this new scope, new compiler need be, local variables, we basically call declaration() again, hence the recursive descent portion of course <br/ >
Either way, we keep going down the line, scope comes before control flow, comes before returns in a given scope / function, and then all of that comes before the expressionStatement which in essence just parses the basic expression. This is probably the part hit the most often because it’s what every single expression hits to start going through the process that was described earlier in the docs.
Variables
static void varDeclaration(ASTparser* parser, TypeChecker* checker, AstCompiler* compiler, Vm* vm, ValueType type)
{
const char* name = parser->previous.lexemeStart;
int nameLength = parser->previous.length;
//get the equal and parse the expression
consume(T_EQUAL, "Expected a '=' after you declare a new variable.", "SYNTAX ERROR", parser);
Expr* varInitializer = astExpression(parser, compiler, vm);
consume(T_SEMICOLON, "Expected ';' after you declare a new variable", "SYNTAX ERROR", parser);
//check the type of the expression vs the declared type
ValueType realType = checkExpression(checker, varInitializer, parser);
if (realType != type)
{
error("A variable expression's type must be the same as it's declared type.", "TYPE MISMATCH ERROR", parser);
freeExpr(varInitializer, vm); //fix possible leak on error
return;
}
if (compiler->scopeDepth == 0)
{
//set the global to get defined here
addSymbol(checker, name, nameLength, compiler->scopeDepth, type, NULL, parser);
//check to see if the type is a class declaration somewhere, and update the metadata in the typechecker to know what class it is
if (type == VALUE_INSTANCE)
{
Symbol* symbol = lookUpSymbol(checker, name, nameLength);
symbol->className = checker->lastClassName;
symbol->classNameLength = checker->lastClassNameLength;
}
compileBytecode(varInitializer, parser, &compiler->function->chunk, compiler, vm);
emitDefineGlobal(name, nameLength, &compiler->function->chunk, parser, vm);
freeExpr(varInitializer, vm);
}
else
{
//declare a new local and then actually parse the value
Local* local = &compiler->locals[compiler->localCount++];
local->name = name;
local->length = nameLength;
local->depth = compiler->scopeDepth;
//the compiled value ends up on the stack and IS the local
addSymbol(checker, name, nameLength, compiler->scopeDepth, type, NULL, parser);
//check to see if the type is a class declaration somewhere, and update the metadata in the typechecker to know what class it is
if (type == VALUE_INSTANCE)
{
Symbol* symbol = lookUpSymbol(checker, name, nameLength);
symbol->className = checker->lastClassName;
symbol->classNameLength = checker->lastClassNameLength;
}
compileBytecode(varInitializer, parser, &compiler->function->chunk, compiler, vm);
freeExpr(varInitializer, vm);
}
}Found in /src/ASTcompiler.c
Okay, basic theory apart, I think we should get into what an actual declaration might look like. I think the most basic and fundamental declaration would be one of the variable declarations. Now variables are handled differently based on the scope that they are in, global variables are stored in a hashmap that can be accessed from anywhere, where as local variables live on the program’s stack until we exit the scope of that variable, more on that below.
Right here however, we already know we have a make keyword, and so the next item is the identifier name, in this case the name of the given variable. We then consume the = token as the assignment operator. Oli-Nat does not allow for empty definitions, so each value needs to have some kind of value assigned to it on creation. After this though, things are really simple because we know almost every statement has some expressions internally!
So we have make x = 5 + 3; We already parsed make as the thing telling us we are declaring a variable, then x is our identifier, and we consume =, so all we have left is 5+3 which is just compiled as a basic expression using the above steps! Of course we then have a ; consumption to see when the declarative expression ends.
Now, that’s the easy part, we’ve parsed the statement into an expression and we know the context is a variable declaration, but we need to now check the current scope of the encompassing compilers, good thing it is already stored internally! So, we just access this variable, and if we are in the global scope we simply add it as a interned value based on the identifier string in the global variables hashmap.
The fun thing actually happens when we do not exist locally though. Instead we create a new local struct that we zero out and then add information into based on the variable. This includes things like the local name and adding the local to the list of all locals in the compiler struct. The fun part is we basically store the local in our compiler in the exact same way that it appears on the stack! Thus we do not really need to do any extra work because the local only needs to exist on the stack for the scope that it is in! Speaking of scope:
Scopes
static void endScope(AstCompiler* compiler, TypeChecker* checker, Vm* vm, ASTparser* parser)
{
compiler->scopeDepth--;
//pop locals
while (compiler->localCount > 0 && compiler->locals[compiler->localCount-1].depth > compiler->scopeDepth)
{
if (compiler->locals[compiler->localCount-1].isCaptured)
{
emitByte(OP_CLOSE_UPVALUE, &compiler->function->chunk, parser, vm);
}
else
{
emitByte(OP_POP, &compiler->function->chunk, parser, vm);
}
compiler->localCount--;
}
//pop in tandem with symbol table
while (checker->varCount > 0 &&
checker->symbols[checker->varCount - 1].depth > compiler->scopeDepth)
{
checker->varCount--;
}
}Found in /src/ASTcompiler.c
Scope of course, for anyone who might not know, is basically the current access level that you have. It allows you to separate out your code into hierarchies so you can declare a variable outside of a scope, and then access it inside. You can also do something like declare a variable inside of a scope and then have it no longer be accessible once that scope is exited, it is very useful for local variable usage.
With this said, we need to know how to handle scope within of the language, and this is what the above function does. We know when we exit a scope we are changing back to the outward encompassing compiler (if applicable of course), but doing so means we need to pop locals as they leave the scope. This is representative of the lifetime of a scoped variable of course.
Equally, a lot of nuance is added for closures, which are basically function calls that capture a value from an outer scope. We set if a variable is captured already before hand, so we differentiate between a regular local and an enclosed upvalue. After which of course we proceed to translate this exact level of popping to the bytecode so the stack representation I have been mentioning is actually established here.
Control Flow
Going in, control flow to me was kind of not something I really had much of an idea of how it would work. I understood that we needed to basically choose one of two options when choosing the code to execute, but it was beyond me how things like loops work. The funny thing is that in practice the solution to this is so obvious when you hear it, but truly genius.
Instead of doing something like creating a whole new branch of bytecode or something, we simply jump around our bytecode. The bytecode is really just an array of instruction, so whenever we encounter something like an if statement, we just check to see if we need to jump over the code or actually run it. The same thing for loops, we check a boolean expression and then if it is true, we run the code and then at the end of it we simply jump back.
Now this is all fine and dandy, but as we compile an if statement, we have no idea how long the bytecode after the code would be, so how do we do it?:
void patchJump(int offset, Chunk* currentChunk, ASTparser* parser)
{
short jump = currentChunk->count - offset - 2;
if (jump > UINT16_MAX)
{
error("Too much code to jump over twin.", "MEMORY ERROR", parser);
}
currentChunk->byteCode[offset] = (jump >> 8) & 0xff;
currentChunk->byteCode[offset+1] = jump & 0xff;
}Found in /src/ASTcompiler.c
We use this patchjump() function. Now this looks a bit weird at first right. A lot of bit math going on. Here is the thing though, we understand that we need to have the OP_JUMP and then a numeric distance of bytecode instructions to jump over if we determine we should jump. So, what we do is just put in a place holder value (of size 2 bytes, so a short), and then we compile the body as we see fit, and once we are done we know the size of the jump, so we go back and amend the jump size.
Of course the caveat of this is then that we are limited to a 2 byte jump, we could allocate more, but very rarely will a single if statement block be over sixteen thousand instructions, it is more often much less, so we trade off space for convenience. Here is the actual implementation for how we count this though:
static void ifStatement(ASTparser* parser, TypeChecker* checker, AstCompiler* compiler, Vm* vm)
{
consume(T_LEFT_PAREN, "Please supplement your if statement with a '(' after 'if'.", "SYNTAX ERROR", parser);
Expr* condition = astExpression(parser, compiler, vm);
consume(T_RIGHT_PAREN, "Please close your if statement's condition with ')'.","SYNTAX ERROR", parser);
ValueType conditionType = checkExpression(checker, condition, parser);
if (conditionType != VALUE_BOOL)
{
error("If condition must be a boolean.", "TYPE MISMATCH ERROR", parser);
}
compileBytecode(condition, parser, &compiler->function->chunk, compiler, vm);
freeExpr(condition, vm); //forgot to free condition expr haha
//emit a jump instruction with then two supplementary bytes to store how large the jump is
short jumpIndex = emitJump(OP_JUMP_IF_FALSE, &compiler->function->chunk, parser, vm);
emitByte(OP_POP, &compiler->function->chunk, parser, vm); //get condition value off stack TODO: see if this causes issues
statement(parser, checker, compiler, vm); //parse block
short elseJump = emitJump(OP_JUMP, &compiler->function->chunk, parser, vm); //always jump if found
patchJump(jumpIndex, &compiler->function->chunk, parser);
emitByte(OP_POP, &compiler->function->chunk, parser, vm);
if (match(T_ELSE, parser))
{
statement(parser, checker, compiler, vm); //parse else block
}
patchJump(elseJump, &compiler->function->chunk, parser);
}Found in /src/ASTcompiler.c
add explanation here, emit OP_JUMP_IF_FALSE with a 2 byte placeholder, compile the body, then patchJump goes BACK and fills in the real distance once we know it. Back-patching. A little drawing of the chunk with the hole getting filled in would be great here
Of course, the previous context we have described of statements and expressions lets us parse this syntax very easily. We look for the if keyword and then we known an expression is up next. Now technically you often do not need the () token(s), but I like them, and it is my language, so they stay.
Of course the expression in the parenthesis gets evaluated to a boolean, and then we get to the fun part. We parse the actual expression first, of course also checking for else syntax. The else statement is the same as the if statement because if we choose to skip the if code we just end up at the else statement (this is why else if works), but if we choose to go through if we then need to know how to skip else.
Either way, we compile the two statements and then just pass them over to the bytecode compiler, which very nicely counts the amount of instruction made and returns it to us as a short value which we then use patchjump to update the temporary hold jump value that we made earlier. That is really about it! The beauty of seeing if we skip over specific code or run it, but what if we want to repeat code?:
static void emitLoop(int loopStart, ASTparser* parser, AstCompiler* compiler, Vm* vm)
{
emitByte(OP_LOOP, &compiler->function->chunk, parser, vm);
int offset = compiler->function->chunk.count - loopStart + 2;
if (offset > UINT16_MAX) error("Loop body is too large.", "MEMORY ERROR", parser);
emitByte(((offset >> 8) & 0xff), &compiler->function->chunk, parser, vm);
emitByte((offset & 0xff), &compiler->function->chunk, parser, vm);
}Found in /src/ASTcompiler.c
Generally it is really not that different, we just emit the OP_LOOP bytecode to let us know a loop is about to start, and then we make another temporary placement block that we use to indicate the number of skips in the bytecode array to perform if the loop condition is not true.
The only difference is really what we do at the end of the loop, instead of only knowing how far to go forward if the loop is not true, when at the end of the loop, we need to recalculate the condition for the loop, and if it is true then we need to actually go back the exact same offset but in reverse to run the code all over again.
static void forStatement(ASTparser* parser, TypeChecker* checker, AstCompiler* compiler, Vm* vm)
{
beginScope(compiler);
consume(T_LEFT_PAREN, "Please use a '(' character after the for keyword.", "SYNTAX ERROR", parser);
if (match(T_SEMICOLON, parser))
{
//no
//initializer, infinite loop
}
else if (match(T_MAKE, parser))
{
ValueType type = getVarDeclarationType(parser, checker);
consume(T_IDENTIFIER, "You must name your variables and functions, they get sad if you dont.", "SYNTAX ERROR", parser);
varDeclaration(parser, checker, compiler, vm, type);
}
else
{
expressionStatement(parser, checker, compiler, vm);
}
int loopStart = compiler->function->chunk.count;
int exitJump = -1;
if (!match(T_SEMICOLON, parser))
{
//calculate the actual condition
Expr* expr = astExpression(parser, compiler, vm);
ValueType type = checkExpression(checker, expr, parser);
if (type != VALUE_BOOL) { error("A for loops condition must evaluate to a boolean expression.", "SYNTAX ERROR", parser); }
compileBytecode(expr, parser, &compiler->function->chunk, compiler, vm);
consume(T_SEMICOLON, "The code expects ';' after a for loop conditional.", "SYNTAX ERROR", parser);
freeExpr(expr, vm); //forgot to free condition expr haha
exitJump = emitJump(OP_JUMP_IF_FALSE, &compiler->function->chunk, parser, vm);
emitByte(OP_POP, &compiler->function->chunk, parser, vm);
}
int bodyJump = -1;
int incrementStart = -1;
if (!match(T_RIGHT_PAREN, parser))
{
//evaluate the expression changing the loop
bodyJump = emitJump(OP_JUMP, &compiler->function->chunk, parser, vm);
incrementStart = compiler->function->chunk.count;
Expr* expr = astExpression(parser, compiler, vm);
compileBytecode(expr,parser, &compiler->function->chunk, compiler, vm);
freeExpr(expr, vm); //forgot to free condition expr haha
emitByte(OP_POP, &compiler->function->chunk, parser, vm);
consume(T_RIGHT_PAREN, "Expect ')' after for loop clauses", "SYNTAX ERROR", parser);
emitLoop(loopStart, parser, compiler, vm);
loopStart = incrementStart;
patchJump(bodyJump, &compiler->function->chunk, parser);
}
else
{
consume(T_RIGHT_PAREN, "Expect ')' after for clauses", "SYNTAX ERROR", parser);
}
statement(parser, checker, compiler, vm);
emitLoop(loopStart, parser, compiler, vm);
if (exitJump != -1)
{
patchJump(exitJump, &compiler->function->chunk, parser);
emitByte(OP_POP, &compiler->function->chunk, parser, vm);
}
endScope(compiler, checker, vm, parser);
}Found in /src/ASTcompiler.c
Now, this is the probably the hardest example of the two that I could have chosen between a while loop and a for loop. The reason for this does make sense in a way, as technically all for loops are basically while loops anywho
Now, the for loop has a lot going on, we have three possible, and sometimes optional, things to parse for(var declaration; condition; operation). We have the variable declaration, which needs to check to see if there is a variable declaration with make and then we just go through the already described process of creating a variable. The variable is scoped in the same scope as the for loop itself. This is because someone can just declare an outer variable and only define the expression and condition
However, afterwards, we have the expression, this is basically just a expressionStatement and is parsed by going through the pratt parsing and everything that has already been described. This is run at the end of every single loop on the variable that was just declared. This is all so then the condition can be run next, and this is also just an expressionStatement but instead of an operation, it evaluates to a boolean expression based on how many times you want the loop to run.
Of course we need to make all of this optional because for(;;) is a valid infinite loop, int x = 1; for(;x>1;x++){} is also valid. And so much much more. This, except for the declaration is basically something we need to have after out OP_LOOP bytecode that says a loop is coming, and we need to execute all of it, and then if it is true we run the loop, and at the end of the loop we go back and run it all again. If we are not true then we just jump over it.
In all honesty it is a very verbose way of saying we keep track of a variable’s state, and based on some condition of this variable, we either jump forward in the bytecode array, or we run the code until we finish the current scope and then we jump back to where we started. All of course repeating while the condition is true.
Functions and Closures
static void initFunctionCompiler(AstCompiler* newCompiler, AstCompiler* enclosing, const char* name, int nameLength, ValueType returnType, bool isTopLevel, bool isMethod, Vm* vm, TypeChecker* checker, ASTparser* parser)
{
memset(newCompiler, 0, sizeof(AstCompiler)); //zero out the compiler so it doesnt read garbage memory for an inner function and just die
//zero out the compilers inner crap for locals
newCompiler->isClassMethod = isMethod;
newCompiler->localCount = 1;
newCompiler->scopeDepth = (enclosing == NULL) ? 0 : 1;
newCompiler->enclosing = enclosing;
newCompiler->isTopLevel = isTopLevel;
if (newCompiler->isClassMethod)
{
//tke up slot 0 for the 'this' keyword in the locals array instead of having it be the closure as normal
//at least for methods
Local* local = &newCompiler->locals[0];
local->name = "this";
local->length = 4;
local->depth = 1;
}
//create the function compiler will fill and add to symbol table for recursive calls
newCompiler->function = newFunction(name, nameLength, returnType, vm);
push(vm, CREATE_OBJECT_VAL((Obj*)newCompiler->function)); //push onto stack to protect from gc
if (!isTopLevel && !isMethod) { addSymbol(checker, name, nameLength, newCompiler->scopeDepth, returnType, newCompiler->function, parser); }
}Found in /src/ASTcompiler.c
add explanation here, new AstCompiler per function linked to enclosing, memset so it doesn’t read garbage, slot 0 is reserved (‘this’ for methods), and the push for gc sake (anchor pattern, link to garbage collector)
static ObjFunction* endFunctionCompiler(AstCompiler* compiler, ASTparser* parser, Vm* vm)
{
ObjFunction* function = compiler->function;
if (function->returnType != VALUE_EMPTY)
{
emitByte(OP_MISSING_RETURN, &function->chunk, parser, vm);
}
emitReturn(&function->chunk, parser, vm);
return function;
}Found in /src/ASTcompiler.c
add explanation here, OP_MISSING_RETURN for non-empty functions, this is how ‘every function must return’ gets enforced
int resolveUpvalue(AstCompiler* compiler, const char* name, int length)
{
if (compiler->enclosing == NULL) return -1;
//look for that local in the enclosing scope, searching from top down
for (int i = compiler->enclosing->localCount - 1; i >= 0; i--)
{
//get the local in said scope, and compare it to see if it matches
Local* local = &compiler->enclosing->locals[i];
if (local->length == length && memcmp(local->name, name, length) == 0)
{
local->isCaptured = true;
return addUpValue(compiler, i, true);
}
}
int upvalue = resolveUpvalue(compiler->enclosing, name, length);
if (upvalue != -1) return addUpValue(compiler, upvalue, false);
return -1;
}
int addUpValue(AstCompiler* compiler, int index, bool isLocal)
{
int count = compiler->function->upValueCount;
for (int i = 0; i < count; i++)
{
//check to see if it is already captured, and then just return that
if (compiler->upvalues[i].index == index && compiler->upvalues[i].isLocal == isLocal)
{
return i;
}
}
//set up the new upval at that count
compiler->upvalues[count].index = index;
compiler->upvalues[count].isLocal = isLocal;
return compiler->function->upValueCount++;
}Found in /src/ASTcompiler.c
add explanation here, keep this light: search outward through enclosing compilers, mark the local as captured, reuse an upvalue if it was already captured. Then functionDeclaration() emits OP_CLOSURE followed by an (isLocal, index) pair for each one. Link to Functions & Natives for the full story
Classes
consume(T_LEFT_BRACE, "A class body was expected after a new class declaration, please use '{'.", "SYNTAX ERROR", parser);
while (!check(T_RIGHT_BRACE, parser) && !check(T_EOF, parser))
{
if (match(T_MAKE, parser))
{
//consume the identifer
ValueType type = getVarDeclarationType(parser, checker);
consume(T_IDENTIFIER, "Even inner class methods or fields have feelings, have some heart and give them a name.", "SYNTAX ERROR", parser);
const char* name = parser->previous.lexemeStart;
int nameLength = parser->previous.length;
if (check(T_LEFT_PAREN, parser))
{
//method dispatch the call to append a new method to the class
functionDeclaration(parser, checker, compiler, vm, type, true);
//after function gets declared and is on top of stack in bytecode, you add in the class method opcode to
//make sure that that closure gets attached over to the class
ObjString* methodName = copyString(name, nameLength, vm);
uint8_t nameIndex = addConstant(&compiler->function->chunk, CREATE_OBJECT_VAL((Obj*)methodName), vm);
//check for constructor
if (strncmp(name, checker->currentClassName, checker->currentClassNameLength) == 0)
{
//constructor has been found
emitByte(OP_CONSTRUCTOR, &compiler->function->chunk, parser, vm);
}
else
{
//regular class method
emitByte(OP_CLASS_METHOD, &compiler->function->chunk, parser, vm);
emitByte(nameIndex, &compiler->function->chunk, parser, vm);
}
}
else
{
//... it's a field: compile its initializer (or OP_FIELD_DEFAULT), then OP_CLASS_FIELD
}
}
//...
}Found in /src/ASTcompiler.c (trimmed, inside classDeclaration())
add explanation here, emit order: OP_CLASS, optional superclass + OP_INHERIT, then every member, then OP_DEFINE_GLOBAL. Methods reuse functionDeclaration with isMethod = true then OP_CLASS_METHOD or OP_CONSTRUCTOR, fields compile their initializer or OP_FIELD_DEFAULT then OP_CLASS_FIELD. Mention checker->currentClassName being set so ‘this’ can be type checked, and link to the class guide pages
# pullf and Natives
static void nativeFunction(ASTparser* parser, TypeChecker* checker, AstCompiler* compiler, Vm* vm)
{
//check the type of native
consume(T_IDENTIFIER, "You have to list the name of the library you wish to include.", "SYNTAX ERROR", parser);
const char* library = parser->previous.lexemeStart;
int length = parser->previous.length;
if (strncmp(library, "stdlib", length) == 0)
{
registerIONatives(vm);
registerMathNatives(vm);
registerRandomNatives(vm);
registerTimeNatives(vm);
registerFileIONatives(vm);
registerTypeNatives(vm);
registerUtilsNatives(vm);
registerStringNatives(vm);
registerIOSymbols(checker, parser, vm);
registerMathSymbols(checker, parser, vm);
registerRandomSymbols(checker, parser, vm);
registerTimeSymbols(checker, parser, vm);
registerFileIOSymbols(checker, parser, vm);
registerTypeSymbols(checker, parser, vm);
registerUtilsSymbols(checker, parser, vm);
registerStringSymbols(checker, parser, vm);
}
else if (strncmp(library, "io", length) == 0) //print & output functions
{
registerIONatives(vm);
registerIOSymbols(checker, parser, vm);
}
//... one branch for every library
else
{
error("Unknown library name.", "IMPORT ERROR", parser);
}
}Found in /src/ASTcompiler.c (trimmed)
add explanation here, every library registers twice, the natives for the VM and the symbols for the type checker. Keep it short and link to the stdlib overview and Functions & Natives
The Two Pass Compile
ObjFunction* compile(const char* source, Vm* vm)
{
//set up the parser and essentially the scanner
ASTparser parser;
initParser(&parser, source);
//second parser for the first pass through looking for declarations of classes and functions
ASTparser parser2;
initParser(&parser2, source);
TypeChecker checker;
initTypeChecker(&checker);
//----------------------------First pass--------------------//
while (!check(T_EOF, &parser2))
{
declareFunction(&parser2, &checker, vm );
}
if (parser2.hadError) return NULL;
#ifdef DEBUG_TRACE_EXECUTION
printf("RAN PAST FIRST COMPILATION\n");
#endif
//----------------------------Second pass--------------------//
AstCompiler compiler;
initFunctionCompiler(&compiler, NULL, "<script>", 8, VALUE_EMPTY, true, false, vm, &checker, &parser);
while (!check(T_EOF, &parser))
{
declaration(&parser, &checker, &compiler, vm );
}
ObjFunction* topScript = endFunctionCompiler(&compiler, &parser, vm);
pop(vm); //pop the top level script off the stack since gc no longer needs it
//free all of the temp functions make in type checker
freeTypeChecker(&checker);
//emitReturn(&vm->chunk, &parser);
return (parser.hadError || checker.hadError) ? NULL : topScript;
}Found in /src/ASTcompiler.c
add explanation here, two parsers over the SAME source string, parser2 does the first pass with declareFunction() writing down function signatures, class fields and method signatures, and pullf symbols, then the real second pass. The payoff: calling a function that is defined further down, and classes knowing their fields before their methods compile
//skip over the body
if (check(T_LEFT_BRACE, parser))
{
int braceCount = 1;
consume(T_LEFT_BRACE, "", "", parser);
while (braceCount > 0 && !check(T_EOF, parser))
{
if (match(T_LEFT_BRACE, parser)) braceCount++;
else if (match(T_RIGHT_BRACE, parser)) braceCount--;
else advance(parser);
}
}Found in /src/ASTcompiler.c (trimmed, inside declareFunction())
add explanation here, the brace counting trick for skipping function bodies in the first pass, since we only care about the signature
Error Handling
void errorAt(Token* token, const char* message, const char* messageType, ASTparser* parser)
{
if (parser->panicMode) return; //skip if error already detected
fprintf(stderr, ":>> %s -- [line %d", messageType, token->line);
if (token->type == T_EOF)
{
fprintf(stderr, " at end");
}
else if (token->type == T_ERROR)
{
//nothing
}
else
{
//print out erroring code
fprintf(stderr, " at '%.*s'", token->length, token->lexemeStart);
}
fprintf(stderr, ": %s]\n", message);
parser->hadError = true;
parser->panicMode = true;
}Found in /src/ASTcompiler.c
add explanation here, where the :>> error format comes from, and that panicMode makes it skip every error after the first one
void consume(TokenType type, const char* message, const char* messageType, ASTparser* parser)
{
if (parser->current.type == type)
{
advance(parser);
return;
}
errorAtCurrent(message, messageType, parser);
}Found in /src/ASTcompiler.c
add explanation here, ‘my personal favorite function’, lean into it. Expect a token or error, this is behind almost every SYNTAX ERROR message
static void synchronize(ASTparser* parser)
{
parser->panicMode = false;
while (!parser->current.type != T_EOF)
{
//check if there is a semi colon
if (parser->previous.type == T_SEMICOLON) return;
//start a new declaration, find a new place to start parsing
switch (parser->current.type)
{
case T_CLASS:
case T_MAKE:
case T_FOR:
case T_IF:
case T_WHILE:
case T_RETURN:
case T_HASH_PULLF:
return;
default:
break;
}
advance(parser);
}
}Found in /src/ASTcompiler.c
add explanation here, panic mode recovery, skip ahead to a likely statement boundary (a ; or a keyword like make or if) so one typo doesn’t cause 40 errors. NOTE: fix the while condition first, it should be parser->current.type != T_EOF (the extra ! is the hang bug)
Where to Go Next
wrap up here, link to the Type Checker page next, then the ByteCode Compiler