pocketlang/src/pk_compiler.c

2539 lines
80 KiB
C
Raw Normal View History

2021-02-07 15:40:00 +08:00
/*
2021-06-09 18:42:26 +08:00
* Copyright (c) 2020-2021 Thakee Nathees
* Distributed Under The MIT License
2021-02-07 15:40:00 +08:00
*/
2021-06-09 18:42:26 +08:00
#include "pk_compiler.h"
2021-02-07 15:40:00 +08:00
2021-06-09 18:42:26 +08:00
#include "pk_core.h"
#include "pk_buffers.h"
#include "pk_utils.h"
#include "pk_vm.h"
#include "pk_debug.h"
2021-02-12 01:35:43 +08:00
// The maximum number of variables (or global if compiling top level script)
// to lookup from the compiling context. Also it's limited by it's opcode
2021-02-07 15:40:00 +08:00
// which is using a single byte value to identify the local.
#define MAX_VARIABLES 256
2021-06-04 22:55:06 +08:00
// The maximum number of functions a script could contain. Also it's limited by
// it's opcode which is using a single byte value to identify the local.
#define MAX_FUNCTIONS 256
2021-05-20 22:05:57 +08:00
// The maximum number of names that were used before defined. Its just the size
// of the Forward buffer of the compiler. Feel free to increase it if it
// require more.
#define MAX_FORWARD_NAMES 256
2021-02-09 16:21:10 +08:00
// The maximum number of constant literal a script can contain. Also it's
// limited by it's opcode which is using a short value to identify.
#define MAX_CONSTANTS (1 << 16)
// The maximum address possible to jump. Similar limitation as above.
#define MAX_JUMP (1 << 16)
// Max number of break statement in a loop statement to patch.
#define MAX_BREAK_PATCH 256
2021-02-12 01:35:43 +08:00
// The size of the compiler time error message buffer excluding the file path,
// line number, and function name. Used for `vsprintf` and `vsnprintf` is not
// available in C++98.
#define ERROR_MESSAGE_SIZE 256
2021-06-07 13:54:06 +08:00
// The name of a literal function.
#define LITERAL_FN_NAME "$(LiteralFn)"
2021-06-01 19:50:41 +08:00
/*****************************************************************************
* TOKENS *
*****************************************************************************/
2021-02-07 15:40:00 +08:00
typedef enum {
2021-02-12 01:35:43 +08:00
TK_ERROR = 0,
TK_EOF,
TK_LINE,
// symbols
TK_DOT, // .
TK_DOTDOT, // ..
TK_COMMA, // ,
TK_COLLON, // :
TK_SEMICOLLON, // ;
TK_HASH, // #
TK_LPARAN, // (
TK_RPARAN, // )
TK_LBRACKET, // [
TK_RBRACKET, // ]
TK_LBRACE, // {
TK_RBRACE, // }
TK_PERCENT, // %
TK_TILD, // ~
TK_AMP, // &
TK_PIPE, // |
TK_CARET, // ^
2021-05-16 15:05:54 +08:00
TK_ARROW, // ->
2021-02-12 01:35:43 +08:00
TK_PLUS, // +
TK_MINUS, // -
TK_STAR, // *
TK_FSLASH, // /
TK_BSLASH, // \.
TK_EQ, // =
TK_GT, // >
TK_LT, // <
TK_EQEQ, // ==
TK_NOTEQ, // !=
TK_GTEQ, // >=
TK_LTEQ, // <=
TK_PLUSEQ, // +=
TK_MINUSEQ, // -=
TK_STAREQ, // *=
TK_DIVEQ, // /=
TK_SRIGHT, // >>
TK_SLEFT, // <<
//TODO:
2021-02-17 02:28:03 +08:00
//TK_SRIGHTEQ // >>=
//TK_SLEFTEQ // <<=
//TK_MODEQ, // %=
//TK_XOREQ, // ^=
2021-02-12 01:35:43 +08:00
// Keywords.
2021-05-19 02:59:09 +08:00
TK_MODULE, // module
TK_FROM, // from
2021-05-06 22:19:30 +08:00
TK_IMPORT, // import
2021-05-09 20:31:36 +08:00
TK_AS, // as
2021-02-12 01:35:43 +08:00
TK_DEF, // def
TK_NATIVE, // native (C function declaration)
TK_FUNC, // func (literal function)
2021-02-12 01:35:43 +08:00
TK_END, // end
TK_NULL, // null
TK_IN, // in
TK_AND, // and
TK_OR, // or
2021-02-17 02:28:03 +08:00
TK_NOT, // not / !
2021-02-12 01:35:43 +08:00
TK_TRUE, // true
TK_FALSE, // false
TK_DO, // do
TK_THEN, // then
2021-02-12 01:35:43 +08:00
TK_WHILE, // while
TK_FOR, // for
TK_IF, // if
TK_ELIF, // elif
TK_ELSE, // else
TK_BREAK, // break
TK_CONTINUE, // continue
TK_RETURN, // return
TK_NAME, // identifier
TK_NUMBER, // number literal
TK_STRING, // string literal
/* String interpolation (reference wren-lang)
* but it doesn't support recursive ex: "a \(b + "\(c)")"
* "a \(b) c \(d) e"
* tokenized as:
* TK_STR_INTERP "a "
* TK_NAME b
* TK_STR_INTERP " c "
* TK_NAME d
* TK_STRING " e" */
// TK_STR_INTERP, //< not yet.
2021-02-07 15:40:00 +08:00
} TokenType;
typedef struct {
2021-02-12 01:35:43 +08:00
TokenType type;
2021-02-07 15:40:00 +08:00
2021-02-12 01:35:43 +08:00
const char* start; //< Begining of the token in the source.
int length; //< Number of chars of the token.
int line; //< Line number of the token (1 based).
Var value; //< Literal value of the token.
2021-02-07 15:40:00 +08:00
} Token;
typedef struct {
2021-02-12 01:35:43 +08:00
const char* identifier;
int length;
TokenType tk_type;
2021-02-07 15:40:00 +08:00
} _Keyword;
// List of keywords mapped into their identifiers.
static _Keyword _keywords[] = {
2021-06-01 19:50:41 +08:00
{ "module", 6, TK_MODULE },
{ "from", 4, TK_FROM },
{ "import", 6, TK_IMPORT },
{ "as", 2, TK_AS },
{ "def", 3, TK_DEF },
{ "native", 6, TK_NATIVE },
{ "func", 4, TK_FUNC },
{ "end", 3, TK_END },
{ "null", 4, TK_NULL },
{ "in", 2, TK_IN },
{ "and", 3, TK_AND },
{ "or", 2, TK_OR },
{ "not", 3, TK_NOT },
{ "true", 4, TK_TRUE },
{ "false", 5, TK_FALSE },
{ "do", 2, TK_DO },
{ "then", 4, TK_THEN },
{ "while", 5, TK_WHILE },
{ "for", 3, TK_FOR },
{ "if", 2, TK_IF },
{ "elif", 4, TK_ELIF },
{ "else", 4, TK_ELSE },
{ "break", 5, TK_BREAK },
2021-02-12 01:35:43 +08:00
{ "continue", 8, TK_CONTINUE },
2021-06-01 19:50:41 +08:00
{ "return", 6, TK_RETURN },
2021-02-12 01:35:43 +08:00
2021-04-26 17:34:30 +08:00
{ NULL, 0, (TokenType)(0) }, // Sentinal to mark the end of the array
2021-02-07 15:40:00 +08:00
};
2021-06-01 19:50:41 +08:00
/*****************************************************************************
* COMPILIER INTERNAL TYPES *
*****************************************************************************/
2021-02-07 15:40:00 +08:00
// Precedence parsing references:
// https://en.wikipedia.org/wiki/Shunting-yard_algorithm
2021-06-01 19:50:41 +08:00
// http://mathcenter.oxford.emory.edu/site/cs171/shuntingYardAlgorithm/
// http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/
2021-02-07 15:40:00 +08:00
typedef enum {
2021-02-12 01:35:43 +08:00
PREC_NONE,
PREC_LOWEST,
PREC_LOGICAL_OR, // or
PREC_LOGICAL_AND, // and
PREC_LOGICAL_NOT, // not
PREC_EQUALITY, // == !=
PREC_IN, // in
PREC_IS, // is
PREC_COMPARISION, // < > <= >=
PREC_BITWISE_OR, // |
PREC_BITWISE_XOR, // ^
PREC_BITWISE_AND, // &
PREC_BITWISE_SHIFT, // << >>
PREC_RANGE, // ..
PREC_TERM, // + -
PREC_FACTOR, // * / %
PREC_UNARY, // - ! ~
2021-05-16 15:05:54 +08:00
PREC_CHAIN_CALL, // ->
2021-02-12 01:35:43 +08:00
PREC_CALL, // ()
PREC_SUBSCRIPT, // []
PREC_ATTRIB, // .index
PREC_PRIMARY,
2021-02-07 15:40:00 +08:00
} Precedence;
2021-06-04 22:55:06 +08:00
typedef void (*GrammarFn)(Compiler* compiler);
2021-02-07 15:40:00 +08:00
typedef struct {
2021-02-12 01:35:43 +08:00
GrammarFn prefix;
GrammarFn infix;
Precedence precedence;
2021-02-07 15:40:00 +08:00
} GrammarRule;
2021-02-13 21:57:59 +08:00
typedef enum {
DEPTH_SCRIPT = -2, //< Only used for script body function's depth.
DEPTH_GLOBAL = -1, //< Global variables.
DEPTH_LOCAL, //< Local scope. Increase with inner scope.
} Depth;
typedef enum {
FN_NATIVE, //< Native C function.
FN_SCRIPT, //< Script level functions defined with 'def'.
FN_LITERAL, //< Literal functions defined with 'function(){...}'
} FuncType;
2021-02-07 15:40:00 +08:00
typedef struct {
2021-02-12 01:35:43 +08:00
const char* name; //< Directly points into the source string.
2021-06-08 00:56:56 +08:00
uint32_t length; //< Length of the name.
2021-02-13 21:57:59 +08:00
int depth; //< The depth the local is defined in.
2021-02-12 01:35:43 +08:00
int line; //< The line variable declared for debugging.
2021-06-04 22:55:06 +08:00
} Local;
2021-02-07 15:40:00 +08:00
typedef struct sLoop {
2021-02-12 01:35:43 +08:00
// Index of the loop's start instruction where the execution will jump
// back to once it reach the loop end or continue used.
int start;
2021-02-07 15:40:00 +08:00
2021-02-12 01:35:43 +08:00
// Index of the jump out address instruction to patch it's value once done
// compiling the loop.
int exit_jump;
2021-02-07 15:40:00 +08:00
2021-02-12 01:35:43 +08:00
// Array of address indexes to patch break address.
int patches[MAX_BREAK_PATCH];
int patch_count;
2021-02-07 15:40:00 +08:00
2021-02-12 01:35:43 +08:00
// The outer loop of the current loop used to set and reset the compiler's
// current loop context.
struct sLoop* outer_loop;
2021-02-07 15:40:00 +08:00
// Depth of the loop, required to pop all the locals in that loop when it
// met a break/continue statement inside.
int depth;
2021-02-07 15:40:00 +08:00
} Loop;
2021-05-20 22:05:57 +08:00
// To keep track of names used but not defined yet. This is only used for
// functions, because variables can't be accessed before it ever defined.
typedef struct sForwardName {
// Index of the short instruction that has the value of the name (in the
// names buffer of the script).
int instruction;
// The function where the name is used, and the instruction is belongs to.
Fn* func;
// The name string's pointer in the source.
const char* name;
int length;
// Line number of the name used (required for error message).
int line;
} ForwardName;
2021-02-13 21:57:59 +08:00
typedef struct sFunc {
// Scope of the function. -2 for script body, -1 for top level function and
2021-02-13 21:57:59 +08:00
// literal functions will have the scope where it declared.
int depth;
// The actual function pointer which is being compiled.
Function* ptr;
// If outer function of a literal or the script body function of a script
// function. Null for script body function.
struct sFunc* outer_func;
} Func;
// A convinent macro to get the current function.
#define _FN (compiler->func->ptr->fn)
2021-02-07 15:40:00 +08:00
struct Compiler {
2021-05-09 18:28:00 +08:00
PKVM* vm;
2021-05-19 02:59:09 +08:00
Compiler* next_compiler;
// Variables related to parsing.
const char* source; //< Currently compiled source (Weak pointer).
const char* token_start; //< Start of the currently parsed token.
const char* current_char; //< Current char position in the source.
int current_line; //< Line number of the current char.
Token previous, current, next; //< Currently parsed tokens.
2021-06-09 18:42:26 +08:00
bool has_errors; //< True if any syntex error occured at.
2021-06-09 18:42:26 +08:00
bool need_more_lines; //< True if we need more lines in REPL mode.
2021-02-07 15:40:00 +08:00
2021-06-07 13:54:06 +08:00
const PkCompileOptions* options; //< To configure the compilation.
2021-02-12 01:35:43 +08:00
// Current depth the compiler in (-1 means top level) 0 means function
// level and > 0 is inner scope.
int scope_depth;
2021-02-07 15:40:00 +08:00
2021-06-04 22:55:06 +08:00
Local locals[MAX_VARIABLES]; //< Variables in the current context.
int local_count; //< Number of locals in [locals].
2021-02-07 15:40:00 +08:00
2021-06-04 22:55:06 +08:00
int stack_size; //< Current size including locals ind temps.
2021-02-07 15:40:00 +08:00
2021-05-07 15:21:34 +08:00
Script* script; //< Current script (a weak pointer).
2021-02-13 21:57:59 +08:00
Loop* loop; //< Current loop.
Func* func; //< Current function.
2021-05-20 22:05:57 +08:00
// An array of implicitly forward declared names, which will be resolved once
// the script is completely compiled.
ForwardName forwards[MAX_FORWARD_NAMES];
int forwards_count;
// True if the last statement is a new local variable assignment. Because
// the assignment is different than reqular assignment and use this boolean
// to tell the compiler that dont pop it's assigned value because the value
// itself is the local.
bool new_local;
2021-06-04 22:55:06 +08:00
// Will be true when parsing an "l-value" which can be assigned to a value
// using the assignment operator ('='). ie. 'a = 42' here a is an "l-value"
// and the 42 is a "r-value" so the assignment is consumed and compiled.
// Consider '42 = a' where 42 is a "r-value" which cannot be assigned.
// Similerly 'a = 1 + b = 2' the expression '(1 + b)' is a "r value" and
// the assignment here is invalid, however 'a = 1 + (b = 2)' is valid because
// the 'b' is an "l-value" and can be assigned but the '(b = 2)' is a
// "r-value".
bool l_value;
2021-02-09 16:21:10 +08:00
};
typedef struct {
2021-02-12 01:35:43 +08:00
int params;
int stack;
2021-02-09 16:21:10 +08:00
} OpInfo;
static OpInfo opcode_info[] = {
2021-02-12 01:35:43 +08:00
#define OPCODE(name, params, stack) { params, stack },
2021-06-09 18:42:26 +08:00
#include "pk_opcodes.h"
2021-02-12 01:35:43 +08:00
#undef OPCODE
2021-02-07 15:40:00 +08:00
};
2021-02-08 02:30:29 +08:00
/*****************************************************************************
* ERROR HANDLERS *
*****************************************************************************/
// Internal error report function of the parseError() function.
static void reportError(Compiler* compiler, const char* file, int line,
2021-02-08 02:30:29 +08:00
const char* fmt, va_list args) {
2021-06-09 18:42:26 +08:00
// On REPL mode only the first error is reported.
if (compiler->options && compiler->options->repl_mode &&
compiler->has_errors) {
return;
}
compiler->has_errors = true;
// If the source is incompilete we're not printing an error message,
// instead return PK_RESULT_UNEXPECTED_EOF to the host.
if (compiler->need_more_lines) {
ASSERT(compiler->options && compiler->options->repl_mode, OOPS);
return;
}
PKVM* vm = compiler->vm;
2021-06-04 22:55:06 +08:00
if (vm->config.error_fn == NULL) return;
2021-02-12 01:35:43 +08:00
char message[ERROR_MESSAGE_SIZE];
int length = vsprintf(message, fmt, args);
__ASSERT(length < ERROR_MESSAGE_SIZE, "Error message buffer should not "
"exceed the buffer");
2021-05-09 18:28:00 +08:00
vm->config.error_fn(vm, PK_ERROR_COMPILE, file, line, message);
2021-02-08 02:30:29 +08:00
}
// Error caused at the middle of lexing (and TK_ERROR will be lexed insted).
static void lexError(Compiler* compiler, const char* fmt, ...) {
2021-02-12 01:35:43 +08:00
va_list args;
va_start(args, fmt);
const char* path = compiler->script->path->data;
reportError(compiler, path, compiler->current_line, fmt, args);
2021-02-12 01:35:43 +08:00
va_end(args);
2021-02-08 02:30:29 +08:00
}
// Error caused when parsing. The associated token assumed to be last consumed
// which is [compiler->previous].
static void parseError(Compiler* compiler, const char* fmt, ...) {
2021-02-08 02:30:29 +08:00
Token* token = &compiler->previous;
2021-02-08 02:30:29 +08:00
2021-02-12 01:35:43 +08:00
// Lex errors would repored earlier by lexError and lexed a TK_ERROR token.
if (token->type == TK_ERROR) return;
2021-02-08 02:30:29 +08:00
2021-02-12 01:35:43 +08:00
va_list args;
va_start(args, fmt);
const char* path = compiler->script->path->data;
reportError(compiler, path, token->line, fmt, args);
2021-02-12 01:35:43 +08:00
va_end(args);
2021-02-08 02:30:29 +08:00
}
2021-05-20 22:05:57 +08:00
// Error caused when trying to resolve forward names (maybe more in the
// furure), Which will be called once after compiling the script and thus we
// need to pass the line number the error origined from.
static void resolveError(Compiler* compiler, int line, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
const char* path = compiler->script->path->data;
reportError(compiler, path, line, fmt, args);
va_end(args);
}
2021-02-07 15:40:00 +08:00
/*****************************************************************************
* LEXING *
*****************************************************************************/
// Forward declaration of lexer methods.
static char eatChar(Compiler* compiler);
static void setNextValueToken(Compiler* compiler, TokenType type, Var value);
static void setNextToken(Compiler* compiler, TokenType type);
static bool matchChar(Compiler* compiler, char c);
static bool matchLine(Compiler* compiler);
2021-02-07 15:40:00 +08:00
static void eatString(Compiler* compiler, bool single_quote) {
2021-06-09 18:42:26 +08:00
pkByteBuffer buff;
pkByteBufferInit(&buff);
2021-02-12 01:35:43 +08:00
2021-02-13 21:57:59 +08:00
char quote = (single_quote) ? '\'' : '"';
2021-02-12 01:35:43 +08:00
while (true) {
char c = eatChar(compiler);
2021-02-12 01:35:43 +08:00
2021-02-13 01:40:19 +08:00
if (c == quote) break;
2021-02-12 01:35:43 +08:00
if (c == '\0') {
lexError(compiler, "Non terminated string.");
2021-02-12 01:35:43 +08:00
// Null byte is required by TK_EOF.
compiler->current_char--;
2021-02-12 01:35:43 +08:00
break;
}
if (c == '\\') {
switch (eatChar(compiler)) {
2021-06-09 18:42:26 +08:00
case '"': pkByteBufferWrite(&buff, compiler->vm, '"'); break;
case '\'': pkByteBufferWrite(&buff, compiler->vm, '\''); break;
case '\\': pkByteBufferWrite(&buff, compiler->vm, '\\'); break;
case 'n': pkByteBufferWrite(&buff, compiler->vm, '\n'); break;
case 'r': pkByteBufferWrite(&buff, compiler->vm, '\r'); break;
case 't': pkByteBufferWrite(&buff, compiler->vm, '\t'); break;
2021-02-12 01:35:43 +08:00
default:
lexError(compiler, "Error: invalid escape character");
2021-02-12 01:35:43 +08:00
break;
}
} else {
2021-06-09 18:42:26 +08:00
pkByteBufferWrite(&buff, compiler->vm, c);
2021-02-12 01:35:43 +08:00
}
}
// '\0' will be added by varNewSring();
Var string = VAR_OBJ(newStringLength(compiler->vm, (const char*)buff.data,
2021-06-07 13:54:06 +08:00
(uint32_t)buff.count));
2021-02-12 01:35:43 +08:00
2021-06-09 18:42:26 +08:00
pkByteBufferClear(&buff, compiler->vm);
2021-02-12 01:35:43 +08:00
setNextValueToken(compiler, TK_STRING, string);
2021-02-07 15:40:00 +08:00
}
// Returns the current char of the compiler on.
static char peekChar(Compiler* compiler) {
return *compiler->current_char;
2021-02-07 15:40:00 +08:00
}
// Returns the next char of the compiler on.
static char peekNextChar(Compiler* compiler) {
if (peekChar(compiler) == '\0') return '\0';
return *(compiler->current_char + 1);
2021-02-07 15:40:00 +08:00
}
// Advance the compiler by 1 char.
static char eatChar(Compiler* compiler) {
char c = peekChar(compiler);
compiler->current_char++;
if (c == '\n') compiler->current_line++;
2021-02-12 01:35:43 +08:00
return c;
2021-02-07 15:40:00 +08:00
}
// Complete lexing an identifier name.
static void eatName(Compiler* compiler) {
2021-02-07 15:40:00 +08:00
char c = peekChar(compiler);
2021-02-12 01:35:43 +08:00
while (utilIsName(c) || utilIsDigit(c)) {
eatChar(compiler);
c = peekChar(compiler);
2021-02-12 01:35:43 +08:00
}
2021-02-07 15:40:00 +08:00
const char* name_start = compiler->token_start;
2021-02-07 15:40:00 +08:00
2021-02-12 01:35:43 +08:00
TokenType type = TK_NAME;
2021-02-07 15:40:00 +08:00
int length = (int)(compiler->current_char - name_start);
2021-02-12 01:35:43 +08:00
for (int i = 0; _keywords[i].identifier != NULL; i++) {
if (_keywords[i].length == length &&
strncmp(name_start, _keywords[i].identifier, length) == 0) {
type = _keywords[i].tk_type;
break;
}
}
2021-02-07 15:40:00 +08:00
setNextToken(compiler, type);
2021-02-07 15:40:00 +08:00
}
// Complete lexing a number literal.
static void eatNumber(Compiler* compiler) {
2021-02-07 15:40:00 +08:00
2021-02-12 01:35:43 +08:00
// TODO: hex, binary and scientific literals.
while (utilIsDigit(peekChar(compiler)))
eatChar(compiler);
2021-02-12 01:35:43 +08:00
if (peekChar(compiler) == '.' && utilIsDigit(peekNextChar(compiler))) {
matchChar(compiler, '.');
while (utilIsDigit(peekChar(compiler)))
eatChar(compiler);
2021-02-12 01:35:43 +08:00
}
errno = 0;
Var value = VAR_NUM(strtod(compiler->token_start, NULL));
2021-02-12 01:35:43 +08:00
if (errno == ERANGE) {
const char* start = compiler->token_start;
int len = (int)(compiler->current_char - start);
lexError(compiler, "Literal is too large (%.*s)", len, start);
2021-02-12 01:35:43 +08:00
value = VAR_NUM(0);
}
setNextValueToken(compiler, TK_NUMBER, value);
2021-02-07 15:40:00 +08:00
}
// Read and ignore chars till it reach new line or EOF.
static void skipLineComment(Compiler* compiler) {
2021-02-15 20:49:19 +08:00
char c;
while ((c = peekChar(compiler)) != '\0') {
// Don't eat new line it's not part of the comment.
2021-02-15 20:49:19 +08:00
if (c == '\n') return;
eatChar(compiler);
2021-02-12 01:35:43 +08:00
}
2021-02-07 15:40:00 +08:00
}
// If the current char is [c] consume it and advance char by 1 and returns
// true otherwise returns false.
static bool matchChar(Compiler* compiler, char c) {
if (peekChar(compiler) != c) return false;
eatChar(compiler);
2021-02-12 01:35:43 +08:00
return true;
2021-02-07 15:40:00 +08:00
}
// If the current char is [c] eat the char and add token two otherwise eat
// append token one.
static void setNextTwoCharToken(Compiler* compiler, char c, TokenType one,
2021-02-12 01:35:43 +08:00
TokenType two) {
if (matchChar(compiler, c)) {
setNextToken(compiler, two);
2021-02-12 01:35:43 +08:00
} else {
setNextToken(compiler, one);
2021-02-12 01:35:43 +08:00
}
2021-02-07 15:40:00 +08:00
}
// Initialize the next token as the type.
static void setNextToken(Compiler* compiler, TokenType type) {
Token* next = &compiler->next;
next->type = type;
next->start = compiler->token_start;
next->length = (int)(compiler->current_char - compiler->token_start);
next->line = compiler->current_line - ((type == TK_LINE) ? 1 : 0);
2021-02-07 15:40:00 +08:00
}
// Initialize the next token as the type and assign the value.
static void setNextValueToken(Compiler* compiler, TokenType type, Var value) {
setNextToken(compiler, type);
compiler->next.value = value;
2021-02-07 15:40:00 +08:00
}
// Lex the next token and set it as the next token.
static void lexToken(Compiler* compiler) {
compiler->previous = compiler->current;
compiler->current = compiler->next;
2021-02-12 01:35:43 +08:00
if (compiler->current.type == TK_EOF) return;
2021-02-12 01:35:43 +08:00
while (peekChar(compiler) != '\0') {
compiler->token_start = compiler->current_char;
char c = eatChar(compiler);
2021-02-12 01:35:43 +08:00
switch (c) {
case ',': setNextToken(compiler, TK_COMMA); return;
case ':': setNextToken(compiler, TK_COLLON); return;
case ';': setNextToken(compiler, TK_SEMICOLLON); return;
case '#': skipLineComment(compiler); break;
case '(': setNextToken(compiler, TK_LPARAN); return;
case ')': setNextToken(compiler, TK_RPARAN); return;
case '[': setNextToken(compiler, TK_LBRACKET); return;
case ']': setNextToken(compiler, TK_RBRACKET); return;
case '{': setNextToken(compiler, TK_LBRACE); return;
case '}': setNextToken(compiler, TK_RBRACE); return;
case '%': setNextToken(compiler, TK_PERCENT); return;
case '~': setNextToken(compiler, TK_TILD); return;
case '&': setNextToken(compiler, TK_AMP); return;
case '|': setNextToken(compiler, TK_PIPE); return;
case '^': setNextToken(compiler, TK_CARET); return;
case '\n': setNextToken(compiler, TK_LINE); return;
2021-02-12 01:35:43 +08:00
case ' ':
case '\t':
case '\r': {
2021-06-08 00:56:56 +08:00
c = peekChar(compiler);
2021-02-12 01:35:43 +08:00
while (c == ' ' || c == '\t' || c == '\r') {
eatChar(compiler);
c = peekChar(compiler);
2021-02-12 01:35:43 +08:00
}
break;
}
case '.': // TODO: ".5" should be a valid number.
setNextTwoCharToken(compiler, '.', TK_DOT, TK_DOTDOT);
2021-02-12 01:35:43 +08:00
return;
case '=':
setNextTwoCharToken(compiler, '=', TK_EQ, TK_EQEQ);
2021-02-12 01:35:43 +08:00
return;
case '!':
setNextTwoCharToken(compiler, '=', TK_NOT, TK_NOTEQ);
2021-02-12 01:35:43 +08:00
return;
case '>':
if (matchChar(compiler, '>'))
setNextToken(compiler, TK_SRIGHT);
2021-02-12 01:35:43 +08:00
else
setNextTwoCharToken(compiler, '=', TK_GT, TK_GTEQ);
2021-02-12 01:35:43 +08:00
return;
case '<':
if (matchChar(compiler, '<'))
setNextToken(compiler, TK_SLEFT);
2021-02-12 01:35:43 +08:00
else
setNextTwoCharToken(compiler, '=', TK_LT, TK_LTEQ);
2021-02-12 01:35:43 +08:00
return;
case '+':
setNextTwoCharToken(compiler, '=', TK_PLUS, TK_PLUSEQ);
2021-02-12 01:35:43 +08:00
return;
case '-':
if (matchChar(compiler, '=')) {
setNextToken(compiler, TK_MINUSEQ); // '-='
} else if (matchChar(compiler, '>')) {
setNextToken(compiler, TK_ARROW); // '->'
2021-05-16 15:05:54 +08:00
} else {
setNextToken(compiler, TK_MINUS); // '-'
2021-05-16 15:05:54 +08:00
}
2021-02-12 01:35:43 +08:00
return;
case '*':
setNextTwoCharToken(compiler, '=', TK_STAR, TK_STAREQ);
2021-02-12 01:35:43 +08:00
return;
case '/':
setNextTwoCharToken(compiler, '=', TK_FSLASH, TK_DIVEQ);
2021-02-12 01:35:43 +08:00
return;
case '"': eatString(compiler, false); return;
2021-02-13 01:40:19 +08:00
case '\'': eatString(compiler, true); return;
2021-02-12 01:35:43 +08:00
default: {
if (utilIsDigit(c)) {
eatNumber(compiler);
2021-02-12 01:35:43 +08:00
} else if (utilIsName(c)) {
eatName(compiler);
2021-02-12 01:35:43 +08:00
} else {
if (c >= 32 && c <= 126) {
2021-05-22 21:27:40 +08:00
lexError(compiler, "Invalid character '%c'", c);
2021-02-12 01:35:43 +08:00
} else {
lexError(compiler, "Invalid byte 0x%x", (uint8_t)c);
2021-02-12 01:35:43 +08:00
}
setNextToken(compiler, TK_ERROR);
2021-02-12 01:35:43 +08:00
}
return;
}
}
}
setNextToken(compiler, TK_EOF);
compiler->next.start = compiler->current_char;
2021-02-07 15:40:00 +08:00
}
/*****************************************************************************
* PARSING *
*****************************************************************************/
// Returns current token type without lexing a new token.
static TokenType peek(Compiler* self) {
2021-02-12 01:35:43 +08:00
return self->current.type;
2021-02-07 15:40:00 +08:00
}
// Consume the current token if it's expected and lex for the next token
2021-02-12 01:35:43 +08:00
// and return true otherwise reutrn false.
static bool match(Compiler* self, TokenType expected) {
2021-02-12 01:35:43 +08:00
if (peek(self) != expected) return false;
lexToken(self);
return true;
2021-02-07 15:40:00 +08:00
}
2021-02-15 20:49:19 +08:00
// Consume the the current token and if it's not [expected] emits error log
// and continue parsing for more error logs.
static void consume(Compiler* self, TokenType expected, const char* err_msg) {
2021-02-15 20:49:19 +08:00
lexToken(self);
if (self->previous.type != expected) {
parseError(self, "%s", err_msg);
// If the next token is expected discard the current to minimize
// cascaded errors and continue parsing.
if (peek(self) == expected) {
lexToken(self);
}
}
}
2021-02-07 15:40:00 +08:00
// Match one or more lines and return true if there any.
static bool matchLine(Compiler* compiler) {
2021-06-09 18:42:26 +08:00
bool consumed = false;
if (peek(compiler) == TK_LINE) {
while (peek(compiler) == TK_LINE)
lexToken(compiler);
consumed = true;
}
// If we're running on REPL mode, at the EOF and compile time error occured,
// signal the host to get more lines and try re-compiling it.
if (compiler->options && compiler->options->repl_mode &&
!compiler->has_errors) {
if (peek(compiler) == TK_EOF) {
compiler->need_more_lines = true;
}
}
return consumed;
}
// Will skip multiple new lines.
static void skipNewLines(Compiler* compiler) {
matchLine(compiler);
2021-02-07 15:40:00 +08:00
}
2021-05-22 21:27:40 +08:00
// Match semi collon, multiple new lines or peek 'end', 'else', 'elif'
// keywords.
static bool matchEndStatement(Compiler* compiler) {
if (match(compiler, TK_SEMICOLLON)) {
skipNewLines(compiler);
2021-02-15 20:49:19 +08:00
return true;
2021-02-12 01:35:43 +08:00
}
2021-05-22 21:27:40 +08:00
if (matchLine(compiler) || peek(compiler) == TK_EOF)
return true;
2021-02-15 20:49:19 +08:00
2021-05-22 21:27:40 +08:00
// In the below statement we don't require any new lines or semicollons.
// 'if cond then stmnt1 elif cond2 then stmnt2 else stmnt3 end'
if (peek(compiler) == TK_END || peek(compiler) == TK_ELSE ||
peek(compiler) == TK_ELIF)
2021-02-15 20:49:19 +08:00
return true;
2021-05-22 21:27:40 +08:00
2021-02-16 02:51:00 +08:00
return false;
2021-02-15 20:49:19 +08:00
}
// Consume semi collon, multiple new lines or peek 'end' keyword.
static void consumeEndStatement(Compiler* compiler) {
if (!matchEndStatement(compiler)) {
2021-06-08 00:56:56 +08:00
parseError(compiler, "Expected statement end with '\\n' or ';'.");
2021-02-12 01:35:43 +08:00
}
2021-02-07 15:40:00 +08:00
}
// Match optional "do" or "then" keyword and new lines.
static void consumeStartBlock(Compiler* compiler, TokenType delimiter) {
2021-02-12 01:35:43 +08:00
bool consumed = false;
// Match optional "do" or "then".
if (delimiter == TK_DO || delimiter == TK_THEN) {
if (match(compiler, delimiter))
consumed = true;
}
2021-02-12 01:35:43 +08:00
if (matchLine(compiler))
2021-02-12 01:35:43 +08:00
consumed = true;
if (!consumed) {
2021-05-16 01:57:34 +08:00
const char* msg;
if (delimiter == TK_DO) msg = "Expected enter block with newline or 'do'.";
else msg = "Expected enter block with newline or 'then'.";
parseError(compiler, msg);
2021-02-12 01:35:43 +08:00
}
2021-02-07 15:40:00 +08:00
}
2021-02-15 20:49:19 +08:00
// Returns a optional compound assignment.
static bool matchAssignment(Compiler* compiler) {
if (match(compiler, TK_EQ)) return true;
if (match(compiler, TK_PLUSEQ)) return true;
if (match(compiler, TK_MINUSEQ)) return true;
if (match(compiler, TK_STAREQ)) return true;
if (match(compiler, TK_DIVEQ)) return true;
2021-02-15 20:49:19 +08:00
return false;
2021-02-07 15:40:00 +08:00
}
2021-02-11 01:23:48 +08:00
/*****************************************************************************
* NAME SEARCH *
*****************************************************************************/
// Result type for an identifier definition.
typedef enum {
2021-02-12 01:35:43 +08:00
NAME_NOT_DEFINED,
NAME_LOCAL_VAR, //< Including parameter.
NAME_GLOBAL_VAR,
NAME_FUNCTION,
NAME_BUILTIN, //< Native builtin function.
2021-02-11 01:23:48 +08:00
} NameDefnType;
// Identifier search result.
typedef struct {
2021-02-12 01:35:43 +08:00
NameDefnType type;
2021-02-11 01:23:48 +08:00
2021-02-12 01:35:43 +08:00
// Index in the variable/function buffer/array.
int index;
2021-02-11 01:23:48 +08:00
2021-02-12 01:35:43 +08:00
// The line it declared.
int line;
2021-02-11 01:23:48 +08:00
} NameSearchResult;
// Will check if the name already defined.
static NameSearchResult compilerSearchName(Compiler* compiler,
const char* name, uint32_t length) {
2021-02-12 01:35:43 +08:00
NameSearchResult result;
result.type = NAME_NOT_DEFINED;
2021-02-13 21:57:59 +08:00
2021-06-04 22:55:06 +08:00
for (int i = compiler->local_count - 1; i >= 0; i--) {
Local* local = &compiler->locals[i];
ASSERT(local->depth != DEPTH_GLOBAL, OOPS);
2021-02-12 01:35:43 +08:00
2021-02-13 21:57:59 +08:00
// Literal functions are not closures and ignore it's outer function's
// local variables.
2021-06-04 22:55:06 +08:00
if (compiler->func->depth >= local->depth) {
2021-02-13 21:57:59 +08:00
continue;
}
2021-06-04 22:55:06 +08:00
if (length == local->length) {
if (strncmp(local->name, name, length) == 0) {
result.type = NAME_LOCAL_VAR;
result.index = i;
2021-02-12 01:35:43 +08:00
return result;
}
}
}
2021-06-04 22:55:06 +08:00
int index; // For storing the search result below.
// Search through globals.
2021-06-07 13:54:06 +08:00
index = scriptGetGlobals(compiler->script, name, length);
2021-06-04 22:55:06 +08:00
if (index != -1) {
result.type = NAME_GLOBAL_VAR;
result.index = index;
return result;
}
2021-02-12 01:35:43 +08:00
// Search through functions.
2021-06-07 13:54:06 +08:00
index = scriptGetFunc(compiler->script, name, length);
2021-02-12 01:35:43 +08:00
if (index != -1) {
result.type = NAME_FUNCTION;
result.index = index;
return result;
}
2021-02-13 01:40:19 +08:00
// Search through builtin functions.
index = findBuiltinFunction(compiler->vm, name, length);
2021-02-13 01:40:19 +08:00
if (index != -1) {
result.type = NAME_BUILTIN;
result.index = index;
return result;
}
2021-02-12 01:35:43 +08:00
return result;
2021-02-11 01:23:48 +08:00
}
2021-02-07 15:40:00 +08:00
/*****************************************************************************
* PARSING GRAMMAR *
*****************************************************************************/
2021-02-09 16:21:10 +08:00
// Forward declaration of codegen functions.
static void emitOpcode(Compiler* compiler, Opcode opcode);
static int emitByte(Compiler* compiler, int byte);
static int emitShort(Compiler* compiler, int arg);
2021-05-20 22:05:57 +08:00
2021-05-16 01:57:34 +08:00
static void patchJump(Compiler* compiler, int addr_index);
static void patchForward(Compiler* compiler, Fn* fn, int index, int name);
2021-02-09 16:21:10 +08:00
2021-05-20 22:05:57 +08:00
static int compilerAddConstant(Compiler* compiler, Var value);
2021-05-19 02:59:09 +08:00
static int compilerGetVariable(Compiler* compiler, const char* name,
2021-06-08 00:56:56 +08:00
uint32_t length);
2021-02-11 01:23:48 +08:00
static int compilerAddVariable(Compiler* compiler, const char* name,
2021-06-08 00:56:56 +08:00
uint32_t length, int line);
2021-05-20 22:05:57 +08:00
static void compilerAddForward(Compiler* compiler, int instruction, Fn* fn,
const char* name, int length, int line);
2021-02-11 01:23:48 +08:00
2021-02-07 15:40:00 +08:00
// Forward declaration of grammar functions.
2021-02-09 16:21:10 +08:00
static void parsePrecedence(Compiler* compiler, Precedence precedence);
2021-05-20 22:05:57 +08:00
static int compileFunction(Compiler* compiler, FuncType fn_type);
2021-02-09 16:21:10 +08:00
static void compileExpression(Compiler* compiler);
2021-02-07 15:40:00 +08:00
2021-06-04 22:55:06 +08:00
static void exprLiteral(Compiler* compiler);
static void exprFunc(Compiler* compiler);
static void exprName(Compiler* compiler);
2021-02-07 15:40:00 +08:00
2021-06-04 22:55:06 +08:00
static void exprOr(Compiler* compiler);
static void exprAnd(Compiler* compiler);
2021-05-16 01:57:34 +08:00
2021-06-04 22:55:06 +08:00
static void exprChainCall(Compiler* compiler);
static void exprBinaryOp(Compiler* compiler);
static void exprUnaryOp(Compiler* compiler);
2021-02-07 15:40:00 +08:00
2021-06-04 22:55:06 +08:00
static void exprGrouping(Compiler* compiler);
static void exprList(Compiler* compiler);
static void exprMap(Compiler* compiler);
2021-02-07 15:40:00 +08:00
2021-06-04 22:55:06 +08:00
static void exprCall(Compiler* compiler);
static void exprAttrib(Compiler* compiler);
static void exprSubscript(Compiler* compiler);
2021-02-07 15:40:00 +08:00
2021-02-11 01:23:48 +08:00
// true, false, null, self.
2021-06-04 22:55:06 +08:00
static void exprValue(Compiler* compiler);
2021-02-11 01:23:48 +08:00
2021-02-07 15:40:00 +08:00
#define NO_RULE { NULL, NULL, PREC_NONE }
#define NO_INFIX PREC_NONE
GrammarRule rules[] = { // Prefix Infix Infix Precedence
2021-02-12 01:35:43 +08:00
/* TK_ERROR */ NO_RULE,
/* TK_EOF */ NO_RULE,
/* TK_LINE */ NO_RULE,
2021-02-16 02:51:00 +08:00
/* TK_DOT */ { NULL, exprAttrib, PREC_ATTRIB },
2021-02-12 01:35:43 +08:00
/* TK_DOTDOT */ { NULL, exprBinaryOp, PREC_RANGE },
/* TK_COMMA */ NO_RULE,
/* TK_COLLON */ NO_RULE,
/* TK_SEMICOLLON */ NO_RULE,
/* TK_HASH */ NO_RULE,
/* TK_LPARAN */ { exprGrouping, exprCall, PREC_CALL },
/* TK_RPARAN */ NO_RULE,
2021-02-13 01:40:19 +08:00
/* TK_LBRACKET */ { exprList, exprSubscript, PREC_SUBSCRIPT },
2021-02-12 01:35:43 +08:00
/* TK_RBRACKET */ NO_RULE,
/* TK_LBRACE */ { exprMap, NULL, NO_INFIX },
/* TK_RBRACE */ NO_RULE,
/* TK_PERCENT */ { NULL, exprBinaryOp, PREC_FACTOR },
/* TK_TILD */ { exprUnaryOp, NULL, NO_INFIX },
/* TK_AMP */ { NULL, exprBinaryOp, PREC_BITWISE_AND },
/* TK_PIPE */ { NULL, exprBinaryOp, PREC_BITWISE_OR },
/* TK_CARET */ { NULL, exprBinaryOp, PREC_BITWISE_XOR },
2021-05-16 15:05:54 +08:00
/* TK_ARROW */ { NULL, exprChainCall, PREC_CHAIN_CALL },
2021-02-12 01:35:43 +08:00
/* TK_PLUS */ { NULL, exprBinaryOp, PREC_TERM },
/* TK_MINUS */ { exprUnaryOp, exprBinaryOp, PREC_TERM },
/* TK_STAR */ { NULL, exprBinaryOp, PREC_FACTOR },
/* TK_FSLASH */ { NULL, exprBinaryOp, PREC_FACTOR },
/* TK_BSLASH */ NO_RULE,
2021-06-02 17:33:29 +08:00
/* TK_EQ */ NO_RULE,
2021-02-12 01:35:43 +08:00
/* TK_GT */ { NULL, exprBinaryOp, PREC_COMPARISION },
/* TK_LT */ { NULL, exprBinaryOp, PREC_COMPARISION },
/* TK_EQEQ */ { NULL, exprBinaryOp, PREC_EQUALITY },
/* TK_NOTEQ */ { NULL, exprBinaryOp, PREC_EQUALITY },
/* TK_GTEQ */ { NULL, exprBinaryOp, PREC_COMPARISION },
/* TK_LTEQ */ { NULL, exprBinaryOp, PREC_COMPARISION },
2021-06-02 17:33:29 +08:00
/* TK_PLUSEQ */ NO_RULE,
/* TK_MINUSEQ */ NO_RULE,
/* TK_STAREQ */ NO_RULE,
/* TK_DIVEQ */ NO_RULE,
2021-02-12 01:35:43 +08:00
/* TK_SRIGHT */ { NULL, exprBinaryOp, PREC_BITWISE_SHIFT },
/* TK_SLEFT */ { NULL, exprBinaryOp, PREC_BITWISE_SHIFT },
2021-05-19 02:59:09 +08:00
/* TK_MODULE */ NO_RULE,
/* TK_FROM */ NO_RULE,
2021-05-09 20:31:36 +08:00
/* TK_IMPORT */ NO_RULE,
/* TK_AS */ NO_RULE,
2021-02-12 01:35:43 +08:00
/* TK_DEF */ NO_RULE,
/* TK_EXTERN */ NO_RULE,
/* TK_FUNC */ { exprFunc, NULL, NO_INFIX },
2021-02-12 01:35:43 +08:00
/* TK_END */ NO_RULE,
/* TK_NULL */ { exprValue, NULL, NO_INFIX },
/* TK_IN */ { NULL, exprBinaryOp, PREC_IN },
2021-05-16 01:57:34 +08:00
/* TK_AND */ { NULL, exprAnd, PREC_LOGICAL_AND },
/* TK_OR */ { NULL, exprOr, PREC_LOGICAL_OR },
2021-02-12 01:35:43 +08:00
/* TK_NOT */ { exprUnaryOp, NULL, PREC_LOGICAL_NOT },
/* TK_TRUE */ { exprValue, NULL, NO_INFIX },
/* TK_FALSE */ { exprValue, NULL, NO_INFIX },
/* TK_DO */ NO_RULE,
/* TK_THEN */ NO_RULE,
2021-02-12 01:35:43 +08:00
/* TK_WHILE */ NO_RULE,
/* TK_FOR */ NO_RULE,
/* TK_IF */ NO_RULE,
/* TK_ELIF */ NO_RULE,
/* TK_ELSE */ NO_RULE,
/* TK_BREAK */ NO_RULE,
/* TK_CONTINUE */ NO_RULE,
/* TK_RETURN */ NO_RULE,
/* TK_NAME */ { exprName, NULL, NO_INFIX },
/* TK_NUMBER */ { exprLiteral, NULL, NO_INFIX },
/* TK_STRING */ { exprLiteral, NULL, NO_INFIX },
2021-02-07 15:40:00 +08:00
};
static GrammarRule* getRule(TokenType type) {
2021-02-12 01:35:43 +08:00
return &(rules[(int)type]);
2021-02-07 15:40:00 +08:00
}
2021-02-11 01:23:48 +08:00
// Emit variable store.
2021-02-15 20:49:19 +08:00
static void emitStoreVariable(Compiler* compiler, int index, bool global) {
2021-02-12 01:35:43 +08:00
if (global) {
emitOpcode(compiler, OP_STORE_GLOBAL);
2021-06-04 22:55:06 +08:00
emitByte(compiler, index);
2021-02-12 01:35:43 +08:00
} else {
if (index < 9) { //< 0..8 locals have single opcode.
emitOpcode(compiler, (Opcode)(OP_STORE_LOCAL_0 + index));
} else {
emitOpcode(compiler, OP_STORE_LOCAL_N);
2021-06-04 22:55:06 +08:00
emitByte(compiler, index);
2021-02-12 01:35:43 +08:00
}
}
2021-02-11 01:23:48 +08:00
}
2021-02-15 20:49:19 +08:00
static void emitPushVariable(Compiler* compiler, int index, bool global) {
2021-02-12 01:35:43 +08:00
if (global) {
emitOpcode(compiler, OP_PUSH_GLOBAL);
2021-06-04 22:55:06 +08:00
emitByte(compiler, index);
2021-02-12 01:35:43 +08:00
} else {
if (index < 9) { //< 0..8 locals have single opcode.
emitOpcode(compiler, (Opcode)(OP_PUSH_LOCAL_0 + index));
} else {
emitOpcode(compiler, OP_PUSH_LOCAL_N);
2021-06-04 22:55:06 +08:00
emitByte(compiler, index);
2021-02-12 01:35:43 +08:00
}
}
2021-02-11 01:23:48 +08:00
}
2021-02-09 16:21:10 +08:00
2021-06-04 22:55:06 +08:00
static void exprLiteral(Compiler* compiler) {
Token* value = &compiler->previous;
2021-02-12 01:35:43 +08:00
int index = compilerAddConstant(compiler, value->value);
2021-05-16 15:05:54 +08:00
emitOpcode(compiler, OP_PUSH_CONSTANT);
2021-02-12 01:35:43 +08:00
emitShort(compiler, index);
2021-02-09 16:21:10 +08:00
}
2021-06-04 22:55:06 +08:00
static void exprFunc(Compiler* compiler) {
2021-02-13 21:57:59 +08:00
int fn_index = compileFunction(compiler, FN_LITERAL);
emitOpcode(compiler, OP_PUSH_FN);
2021-06-04 22:55:06 +08:00
emitByte(compiler, fn_index);
2021-02-13 21:57:59 +08:00
}
2021-02-11 01:23:48 +08:00
// Local/global variables, script/native/builtin functions name.
2021-06-04 22:55:06 +08:00
static void exprName(Compiler* compiler) {
2021-02-15 20:49:19 +08:00
const char* start = compiler->previous.start;
int length = compiler->previous.length;
int line = compiler->previous.line;
NameSearchResult result = compilerSearchName(compiler, start, length);
2021-02-12 01:35:43 +08:00
if (result.type == NAME_NOT_DEFINED) {
2021-06-04 22:55:06 +08:00
if (compiler->l_value && match(compiler, TK_EQ)) {
int index = compilerAddVariable(compiler, start, length, line);
// Compile the assigned value.
2021-02-12 01:35:43 +08:00
compileExpression(compiler);
2021-06-04 22:55:06 +08:00
// Store the value to the variable.
if (compiler->scope_depth == DEPTH_GLOBAL) {
emitStoreVariable(compiler, index, true);
} else {
// This will prevent the assignment from poped out from the stack
// since the assigned value itself is the local and not a temp.
2021-05-09 20:31:36 +08:00
compiler->new_local = true;
2021-06-04 22:55:06 +08:00
emitStoreVariable(compiler, index, false);
}
2021-02-12 01:35:43 +08:00
} else {
2021-05-20 22:05:57 +08:00
// The name could be a function which hasn't been defined at this point.
if (peek(compiler) == TK_LPARAN) {
emitOpcode(compiler, OP_PUSH_FN);
2021-06-04 22:55:06 +08:00
int index = emitByte(compiler, 0xff);
compilerAddForward(compiler, index, _FN, start, length, line);
2021-05-20 22:05:57 +08:00
} else {
parseError(compiler, "Name '%.*s' is not defined.", length, start);
2021-05-20 22:05:57 +08:00
}
2021-02-12 01:35:43 +08:00
}
return;
2021-02-12 01:35:43 +08:00
}
switch (result.type) {
case NAME_LOCAL_VAR:
2021-05-16 01:57:34 +08:00
case NAME_GLOBAL_VAR: {
const bool is_global = result.type == NAME_GLOBAL_VAR;
2021-02-15 20:49:19 +08:00
2021-06-04 22:55:06 +08:00
if (compiler->l_value && matchAssignment(compiler)) {
TokenType assignment = compiler->previous.type;
2021-02-15 20:49:19 +08:00
if (assignment != TK_EQ) {
emitPushVariable(compiler, result.index, is_global);
2021-02-15 20:49:19 +08:00
compileExpression(compiler);
switch (assignment) {
case TK_PLUSEQ: emitOpcode(compiler, OP_ADD); break;
case TK_MINUSEQ: emitOpcode(compiler, OP_SUBTRACT); break;
case TK_STAREQ: emitOpcode(compiler, OP_MULTIPLY); break;
case TK_DIVEQ: emitOpcode(compiler, OP_DIVIDE); break;
default:
UNREACHABLE();
break;
}
2021-05-05 12:55:27 +08:00
2021-02-15 20:49:19 +08:00
} else {
compileExpression(compiler);
}
emitStoreVariable(compiler, result.index, is_global);
2021-02-15 20:49:19 +08:00
2021-02-12 01:35:43 +08:00
} else {
emitPushVariable(compiler, result.index, is_global);
2021-02-12 01:35:43 +08:00
}
return;
2021-05-16 01:57:34 +08:00
}
2021-02-12 01:35:43 +08:00
case NAME_FUNCTION:
emitOpcode(compiler, OP_PUSH_FN);
2021-06-04 22:55:06 +08:00
emitByte(compiler, result.index);
2021-02-12 01:35:43 +08:00
return;
case NAME_BUILTIN:
emitOpcode(compiler, OP_PUSH_BUILTIN_FN);
2021-06-04 22:55:06 +08:00
emitByte(compiler, result.index);
2021-02-12 01:35:43 +08:00
return;
2021-02-17 02:28:03 +08:00
case NAME_NOT_DEFINED:
UNREACHABLE(); // Case already handled.
2021-02-12 01:35:43 +08:00
}
2021-02-11 01:23:48 +08:00
}
2021-02-09 16:21:10 +08:00
2021-05-16 01:57:34 +08:00
/* a or b: | a and b:
|
2021-05-16 01:57:34 +08:00
(...) | (...)
.-- jump_if [offset] | .-- jump_if_not [offset]
| (...) | | (...)
2021-05-16 01:57:34 +08:00
|-- jump_if [offset] | |-- jump_if_not [offset]
| push false | | push true
2021-05-16 01:57:34 +08:00
.--+-- jump [offset] | .--+-- jump [offset]
| '-> push true | | '-> push false
'----> (...) | '----> (...)
*/
2021-05-16 01:57:34 +08:00
2021-06-04 22:55:06 +08:00
void exprOr(Compiler* compiler) {
2021-05-16 01:57:34 +08:00
emitOpcode(compiler, OP_JUMP_IF);
int true_offset_a = emitShort(compiler, 0xffff); //< Will be patched.
parsePrecedence(compiler, PREC_LOGICAL_OR);
emitOpcode(compiler, OP_JUMP_IF);
int true_offset_b = emitShort(compiler, 0xffff); //< Will be patched.
emitOpcode(compiler, OP_PUSH_FALSE);
emitOpcode(compiler, OP_JUMP);
2021-05-16 01:57:34 +08:00
int end_offset = emitShort(compiler, 0xffff); //< Will be patched.
patchJump(compiler, true_offset_a);
patchJump(compiler, true_offset_b);
emitOpcode(compiler, OP_PUSH_TRUE);
patchJump(compiler, end_offset);
}
2021-06-04 22:55:06 +08:00
void exprAnd(Compiler* compiler) {
2021-05-16 01:57:34 +08:00
emitOpcode(compiler, OP_JUMP_IF_NOT);
int false_offset_a = emitShort(compiler, 0xffff); //< Will be patched.
parsePrecedence(compiler, PREC_LOGICAL_AND);
emitOpcode(compiler, OP_JUMP_IF_NOT);
int false_offset_b = emitShort(compiler, 0xffff); //< Will be patched.
emitOpcode(compiler, OP_PUSH_TRUE);
emitOpcode(compiler, OP_JUMP);
int end_offset = emitShort(compiler, 0xffff); //< Will be patched.
patchJump(compiler, false_offset_a);
patchJump(compiler, false_offset_b);
emitOpcode(compiler, OP_PUSH_FALSE);
patchJump(compiler, end_offset);
}
2021-06-04 22:55:06 +08:00
static void exprChainCall(Compiler* compiler) {
skipNewLines(compiler);
2021-05-16 15:05:54 +08:00
parsePrecedence(compiler, (Precedence)(PREC_CHAIN_CALL + 1));
emitOpcode(compiler, OP_SWAP); // Swap the data with the function.
int argc = 1; // The initial data.
if (match(compiler, TK_LBRACE)) {
if (!match(compiler, TK_RBRACE)) {
2021-05-16 15:05:54 +08:00
do {
skipNewLines(compiler);
2021-05-16 15:05:54 +08:00
compileExpression(compiler);
skipNewLines(compiler);
2021-05-16 15:05:54 +08:00
argc++;
} while (match(compiler, TK_COMMA));
2021-05-22 21:27:40 +08:00
consume(compiler, TK_RBRACE, "Expected '}' after chain call "
2021-05-20 22:05:57 +08:00
"parameter list.");
2021-05-16 15:05:54 +08:00
}
}
2021-06-04 22:55:06 +08:00
// TOOD: ensure argc < 256 (MAX_ARGC) 1byte.
2021-05-16 15:05:54 +08:00
emitOpcode(compiler, OP_CALL);
2021-06-04 22:55:06 +08:00
emitByte(compiler, argc);
2021-05-16 15:05:54 +08:00
}
2021-06-04 22:55:06 +08:00
static void exprBinaryOp(Compiler* compiler) {
TokenType op = compiler->previous.type;
skipNewLines(compiler);
2021-02-12 01:35:43 +08:00
parsePrecedence(compiler, (Precedence)(getRule(op)->precedence + 1));
switch (op) {
case TK_DOTDOT: emitOpcode(compiler, OP_RANGE); break;
case TK_PERCENT: emitOpcode(compiler, OP_MOD); break;
case TK_AMP: emitOpcode(compiler, OP_BIT_AND); break;
case TK_PIPE: emitOpcode(compiler, OP_BIT_OR); break;
case TK_CARET: emitOpcode(compiler, OP_BIT_XOR); break;
case TK_PLUS: emitOpcode(compiler, OP_ADD); break;
case TK_MINUS: emitOpcode(compiler, OP_SUBTRACT); break;
case TK_STAR: emitOpcode(compiler, OP_MULTIPLY); break;
case TK_FSLASH: emitOpcode(compiler, OP_DIVIDE); break;
case TK_GT: emitOpcode(compiler, OP_GT); break;
case TK_LT: emitOpcode(compiler, OP_LT); break;
case TK_EQEQ: emitOpcode(compiler, OP_EQEQ); break;
case TK_NOTEQ: emitOpcode(compiler, OP_NOTEQ); break;
case TK_GTEQ: emitOpcode(compiler, OP_GTEQ); break;
case TK_LTEQ: emitOpcode(compiler, OP_LTEQ); break;
case TK_SRIGHT: emitOpcode(compiler, OP_BIT_RSHIFT); break;
case TK_SLEFT: emitOpcode(compiler, OP_BIT_LSHIFT); break;
case TK_IN: emitOpcode(compiler, OP_IN); break;
default:
UNREACHABLE();
}
2021-02-09 16:21:10 +08:00
}
2021-06-04 22:55:06 +08:00
static void exprUnaryOp(Compiler* compiler) {
TokenType op = compiler->previous.type;
skipNewLines(compiler);
2021-02-12 01:35:43 +08:00
parsePrecedence(compiler, (Precedence)(PREC_UNARY + 1));
switch (op) {
case TK_TILD: emitOpcode(compiler, OP_BIT_NOT); break;
case TK_MINUS: emitOpcode(compiler, OP_NEGATIVE); break;
case TK_NOT: emitOpcode(compiler, OP_NOT); break;
default:
UNREACHABLE();
}
2021-02-09 16:21:10 +08:00
}
2021-02-07 15:40:00 +08:00
2021-06-04 22:55:06 +08:00
static void exprGrouping(Compiler* compiler) {
skipNewLines(compiler);
2021-02-12 01:35:43 +08:00
compileExpression(compiler);
skipNewLines(compiler);
2021-05-22 21:27:40 +08:00
consume(compiler, TK_RPARAN, "Expected ')' after expression.");
2021-02-09 16:21:10 +08:00
}
2021-02-07 15:40:00 +08:00
2021-06-04 22:55:06 +08:00
static void exprList(Compiler* compiler) {
2021-02-13 01:40:19 +08:00
emitOpcode(compiler, OP_PUSH_LIST);
int size_index = emitShort(compiler, 0);
int size = 0;
do {
skipNewLines(compiler);
if (peek(compiler) == TK_RBRACKET) break;
2021-02-13 01:40:19 +08:00
compileExpression(compiler);
emitOpcode(compiler, OP_LIST_APPEND);
size++;
skipNewLines(compiler);
} while (match(compiler, TK_COMMA));
2021-02-13 01:40:19 +08:00
skipNewLines(compiler);
consume(compiler, TK_RBRACKET, "Expected ']' after list elements.");
2021-02-13 01:40:19 +08:00
2021-02-13 21:57:59 +08:00
_FN->opcodes.data[size_index] = (size >> 8) & 0xff;
_FN->opcodes.data[size_index + 1] = size & 0xff;
2021-02-13 01:40:19 +08:00
}
2021-06-04 22:55:06 +08:00
static void exprMap(Compiler* compiler) {
emitOpcode(compiler, OP_PUSH_MAP);
do {
skipNewLines(compiler);
if (peek(compiler) == TK_RBRACE) break;
compileExpression(compiler);
consume(compiler, TK_COLLON, "Expected ':' after map's key.");
compileExpression(compiler);
emitOpcode(compiler, OP_MAP_INSERT);
skipNewLines(compiler);
} while (match(compiler, TK_COMMA));
skipNewLines(compiler);
consume(compiler, TK_RBRACE, "Expected '}' after map elements.");
}
2021-02-12 01:35:43 +08:00
2021-06-04 22:55:06 +08:00
static void exprCall(Compiler* compiler) {
2021-02-12 01:35:43 +08:00
// Compile parameters.
int argc = 0;
if (!match(compiler, TK_RPARAN)) {
2021-02-12 01:35:43 +08:00
do {
skipNewLines(compiler);
2021-02-12 01:35:43 +08:00
compileExpression(compiler);
skipNewLines(compiler);
2021-02-12 01:35:43 +08:00
argc++;
} while (match(compiler, TK_COMMA));
consume(compiler, TK_RPARAN, "Expected ')' after parameter list.");
2021-02-12 01:35:43 +08:00
}
emitOpcode(compiler, OP_CALL);
2021-06-04 22:55:06 +08:00
emitByte(compiler, argc);
2021-02-12 01:35:43 +08:00
}
2021-02-11 01:23:48 +08:00
2021-06-04 22:55:06 +08:00
static void exprAttrib(Compiler* compiler) {
consume(compiler, TK_NAME, "Expected an attribute name after '.'.");
const char* name = compiler->previous.start;
int length = compiler->previous.length;
2021-02-12 01:35:43 +08:00
// Store the name in script's names.
2021-05-09 20:31:36 +08:00
int index = scriptAddName(compiler->script, compiler->vm, name, length);
2021-02-12 01:35:43 +08:00
2021-06-04 22:55:06 +08:00
if (compiler->l_value && matchAssignment(compiler)) {
2021-02-16 02:51:00 +08:00
TokenType assignment = compiler->previous.type;
2021-02-16 02:51:00 +08:00
if (assignment != TK_EQ) {
emitOpcode(compiler, OP_GET_ATTRIB_KEEP);
2021-02-16 02:51:00 +08:00
emitShort(compiler, index);
compileExpression(compiler);
switch (assignment) {
case TK_PLUSEQ: emitOpcode(compiler, OP_ADD); break;
case TK_MINUSEQ: emitOpcode(compiler, OP_SUBTRACT); break;
case TK_STAREQ: emitOpcode(compiler, OP_MULTIPLY); break;
case TK_DIVEQ: emitOpcode(compiler, OP_DIVIDE); break;
default:
UNREACHABLE();
break;
}
} else {
compileExpression(compiler);
}
2021-02-12 01:35:43 +08:00
emitOpcode(compiler, OP_SET_ATTRIB);
emitShort(compiler, index);
} else {
emitOpcode(compiler, OP_GET_ATTRIB);
emitShort(compiler, index);
}
2021-02-11 01:23:48 +08:00
}
2021-06-04 22:55:06 +08:00
static void exprSubscript(Compiler* compiler) {
2021-02-16 02:51:00 +08:00
compileExpression(compiler);
consume(compiler, TK_RBRACKET, "Expected ']' after subscription ends.");
2021-02-16 02:51:00 +08:00
2021-06-04 22:55:06 +08:00
if (compiler->l_value && matchAssignment(compiler)) {
2021-02-16 02:51:00 +08:00
TokenType assignment = compiler->previous.type;
2021-02-16 02:51:00 +08:00
if (assignment != TK_EQ) {
emitOpcode(compiler, OP_GET_SUBSCRIPT_KEEP);
2021-02-16 02:51:00 +08:00
compileExpression(compiler);
switch (assignment) {
case TK_PLUSEQ: emitOpcode(compiler, OP_ADD); break;
case TK_MINUSEQ: emitOpcode(compiler, OP_SUBTRACT); break;
case TK_STAREQ: emitOpcode(compiler, OP_MULTIPLY); break;
case TK_DIVEQ: emitOpcode(compiler, OP_DIVIDE); break;
default:
UNREACHABLE();
break;
}
} else {
compileExpression(compiler);
}
emitOpcode(compiler, OP_SET_SUBSCRIPT);
} else {
emitOpcode(compiler, OP_GET_SUBSCRIPT);
}
}
2021-02-07 15:40:00 +08:00
2021-06-04 22:55:06 +08:00
static void exprValue(Compiler* compiler) {
TokenType op = compiler->previous.type;
2021-02-12 01:35:43 +08:00
switch (op) {
case TK_NULL: emitOpcode(compiler, OP_PUSH_NULL); return;
case TK_TRUE: emitOpcode(compiler, OP_PUSH_TRUE); return;
case TK_FALSE: emitOpcode(compiler, OP_PUSH_FALSE); return;
default:
UNREACHABLE();
}
2021-02-11 01:23:48 +08:00
}
2021-02-09 16:21:10 +08:00
static void parsePrecedence(Compiler* compiler, Precedence precedence) {
lexToken(compiler);
GrammarFn prefix = getRule(compiler->previous.type)->prefix;
2021-02-12 01:35:43 +08:00
if (prefix == NULL) {
parseError(compiler, "Expected an expression.");
2021-02-12 01:35:43 +08:00
return;
}
2021-06-04 22:55:06 +08:00
compiler->l_value = precedence <= PREC_LOWEST;
prefix(compiler);
2021-02-12 01:35:43 +08:00
while (getRule(compiler->current.type)->precedence >= precedence) {
lexToken(compiler);
GrammarFn infix = getRule(compiler->previous.type)->infix;
2021-06-04 22:55:06 +08:00
infix(compiler);
2021-02-12 01:35:43 +08:00
}
2021-02-09 16:21:10 +08:00
}
2021-02-07 15:40:00 +08:00
/*****************************************************************************
* COMPILING *
*****************************************************************************/
2021-05-09 18:28:00 +08:00
static void compilerInit(Compiler* compiler, PKVM* vm, const char* source,
2021-06-07 13:54:06 +08:00
Script* script, const PkCompileOptions* options) {
2021-02-12 01:35:43 +08:00
compiler->vm = vm;
2021-05-19 02:59:09 +08:00
compiler->next_compiler = NULL;
compiler->source = source;
compiler->script = script;
compiler->token_start = source;
compiler->has_errors = false;
2021-06-09 18:42:26 +08:00
compiler->need_more_lines = false;
2021-06-07 13:54:06 +08:00
compiler->options = options;
compiler->current_char = source;
compiler->current_line = 1;
compiler->next.type = TK_ERROR;
compiler->next.start = NULL;
compiler->next.length = 0;
compiler->next.line = 1;
compiler->next.value = VAR_UNDEFINED;
2021-02-13 21:57:59 +08:00
compiler->scope_depth = DEPTH_GLOBAL;
2021-06-04 22:55:06 +08:00
compiler->local_count = 0;
2021-02-12 01:35:43 +08:00
compiler->stack_size = 0;
compiler->loop = NULL;
compiler->func = NULL;
2021-05-20 22:05:57 +08:00
compiler->forwards_count = 0;
compiler->new_local = false;
2021-02-07 15:40:00 +08:00
}
2021-05-19 02:59:09 +08:00
// Return the index of the variable if it's already defined in the current
// scope otherwise returns -1.
static int compilerGetVariable(Compiler* compiler, const char* name,
2021-06-08 00:56:56 +08:00
uint32_t length) {
2021-06-04 22:55:06 +08:00
for (int i = compiler->local_count - 1; i >= 0; i--) {
Local* local = &compiler->locals[i];
if (length == local->length && strncmp(name, local->name, length) == 0) {
2021-05-19 02:59:09 +08:00
return i;
}
}
return -1;
}
2021-02-07 15:40:00 +08:00
// Add a variable and return it's index to the context. Assumes that the
// variable name is unique and not defined before in the current scope.
static int compilerAddVariable(Compiler* compiler, const char* name,
2021-06-08 00:56:56 +08:00
uint32_t length, int line) {
2021-05-19 02:59:09 +08:00
// TODO: should I validate the name for pre-defined, etc?
2021-06-04 22:55:06 +08:00
// Check if maximum variable count is reached.
bool max_vars_reached = false;
2021-06-08 00:56:56 +08:00
const char* var_type = ""; // For max variables reached error message.
2021-06-04 22:55:06 +08:00
if (compiler->scope_depth == DEPTH_GLOBAL) {
if (compiler->local_count == MAX_VARIABLES) {
max_vars_reached = true;
var_type = "locals";
}
} else {
if (compiler->script->globals.count == MAX_VARIABLES) {
max_vars_reached = true;
var_type = "globals";
}
}
if (max_vars_reached) {
parseError(compiler, "A script should contain at most %d %s.",
MAX_VARIABLES, var_type);
2021-05-20 22:05:57 +08:00
return -1;
}
2021-06-04 22:55:06 +08:00
// Add the variable and return it's index.
if (compiler->scope_depth == DEPTH_GLOBAL) {
Script* script = compiler->script;
uint32_t name_index = scriptAddName(script, compiler->vm, name, length);
pkUintBufferWrite(&script->global_names, compiler->vm, name_index);
pkVarBufferWrite(&script->globals, compiler->vm, VAR_NULL);
2021-06-04 22:55:06 +08:00
return compiler->script->globals.count - 1;
} else {
Local* local = &compiler->locals [compiler->local_count];
local->name = name;
local->length = length;
local->depth = compiler->scope_depth;
local->line = line;
return compiler->local_count++;
2021-05-19 02:59:09 +08:00
}
2021-06-04 22:55:06 +08:00
UNREACHABLE();
2021-02-07 15:40:00 +08:00
}
2021-05-20 22:05:57 +08:00
static void compilerAddForward(Compiler* compiler, int instruction, Fn* fn,
const char* name, int length, int line) {
2021-05-24 06:17:52 +08:00
if (compiler->forwards_count == MAX_FORWARD_NAMES) {
2021-05-20 22:05:57 +08:00
parseError(compiler, "A script should contain at most %d implict forward "
2021-05-24 06:17:52 +08:00
"function declarations.", MAX_FORWARD_NAMES);
2021-05-20 22:05:57 +08:00
return;
}
ForwardName* forward = &compiler->forwards[compiler->forwards_count++];
forward->instruction = instruction;
forward->func = fn;
forward->name = name;
forward->length = length;
forward->line = line;
}
2021-02-09 16:21:10 +08:00
// Add a literal constant to scripts literals and return it's index.
static int compilerAddConstant(Compiler* compiler, Var value) {
2021-06-09 18:42:26 +08:00
pkVarBuffer* literals = &compiler->script->literals;
2021-02-12 01:35:43 +08:00
2021-05-04 18:24:26 +08:00
for (uint32_t i = 0; i < literals->count; i++) {
if (isValuesSame(literals->data[i], value)) {
2021-02-12 01:35:43 +08:00
return i;
}
}
// Add new constant to script.
if (literals->count < MAX_CONSTANTS) {
2021-06-09 18:42:26 +08:00
pkVarBufferWrite(literals, compiler->vm, value);
2021-02-12 01:35:43 +08:00
} else {
parseError(compiler, "A script should contain at most %d "
2021-05-24 06:17:52 +08:00
"unique constants.", MAX_CONSTANTS);
2021-02-12 01:35:43 +08:00
}
return (int)literals->count - 1;
2021-02-09 16:21:10 +08:00
}
// Enters inside a block.
static void compilerEnterBlock(Compiler* compiler) {
2021-02-12 01:35:43 +08:00
compiler->scope_depth++;
2021-02-09 16:21:10 +08:00
}
2021-06-02 17:33:29 +08:00
// Pop all the locals at the [depth] or highter. Returns the number of locals
// that were poppedl
static int compilerPopLocals(Compiler* compiler, int depth) {
ASSERT(depth > (int)DEPTH_GLOBAL, "Cannot pop global variables.");
2021-02-12 01:35:43 +08:00
2021-06-04 22:55:06 +08:00
int local = compiler->local_count - 1;
while (local >= 0 && compiler->locals[local].depth >= depth) {
emitOpcode(compiler, OP_POP);
local--;
2021-02-12 01:35:43 +08:00
}
2021-06-04 22:55:06 +08:00
return (compiler->local_count - 1) - local;
}
// Exits a block.
static void compilerExitBlock(Compiler* compiler) {
ASSERT(compiler->scope_depth > (int)DEPTH_GLOBAL, "Cannot exit toplevel.");
// Discard all the locals at the current scope.
2021-06-02 17:33:29 +08:00
int popped = compilerPopLocals(compiler, compiler->scope_depth);
2021-06-04 22:55:06 +08:00
compiler->local_count -= popped;
2021-06-02 17:33:29 +08:00
compiler->stack_size -= popped;
2021-02-12 01:35:43 +08:00
compiler->scope_depth--;
2021-02-09 16:21:10 +08:00
}
/*****************************************************************************
* COMPILING (EMIT BYTECODE) *
*****************************************************************************/
// Emit a single byte and return it's index.
static int emitByte(Compiler* compiler, int byte) {
2021-06-09 18:42:26 +08:00
pkByteBufferWrite(&_FN->opcodes, compiler->vm,
2021-02-09 16:21:10 +08:00
(uint8_t)byte);
2021-06-09 18:42:26 +08:00
pkUintBufferWrite(&_FN->oplines, compiler->vm,
compiler->previous.line);
2021-02-13 21:57:59 +08:00
return (int)_FN->opcodes.count - 1;
2021-02-09 16:21:10 +08:00
}
// Emit 2 bytes argument as big indian. return it's starting index.
static int emitShort(Compiler* compiler, int arg) {
2021-02-12 01:35:43 +08:00
emitByte(compiler, (arg >> 8) & 0xff);
return emitByte(compiler, arg & 0xff) - 1;
2021-02-09 16:21:10 +08:00
}
// Emits an instruction and update stack size (variable stack size opcodes
// should be handled).
static void emitOpcode(Compiler* compiler, Opcode opcode) {
2021-02-12 01:35:43 +08:00
emitByte(compiler, (int)opcode);
2021-02-09 16:21:10 +08:00
2021-02-12 01:35:43 +08:00
compiler->stack_size += opcode_info[opcode].stack;
2021-02-13 21:57:59 +08:00
if (compiler->stack_size > _FN->stack_size) {
_FN->stack_size = compiler->stack_size;
2021-02-12 01:35:43 +08:00
}
2021-02-09 16:21:10 +08:00
}
2021-02-13 01:40:19 +08:00
// Update the jump offset.
2021-02-09 16:21:10 +08:00
static void patchJump(Compiler* compiler, int addr_index) {
2021-06-02 17:33:29 +08:00
int offset = (int)_FN->opcodes.count - (addr_index + 2 /*bytes index*/);
2021-05-16 01:57:34 +08:00
ASSERT(offset < MAX_JUMP, "Too large address offset to jump to.");
2021-02-09 16:21:10 +08:00
2021-05-16 01:57:34 +08:00
_FN->opcodes.data[addr_index] = (offset >> 8) & 0xff;
_FN->opcodes.data[addr_index + 1] = offset & 0xff;
2021-02-09 16:21:10 +08:00
}
static void patchForward(Compiler* compiler, Fn* fn, int index, int name) {
2021-06-04 22:55:06 +08:00
fn->opcodes.data[index] = name & 0xff;
2021-05-20 22:05:57 +08:00
}
2021-02-13 01:40:19 +08:00
// Jump back to the start of the loop.
static void emitLoopJump(Compiler* compiler) {
emitOpcode(compiler, OP_LOOP);
2021-02-13 21:57:59 +08:00
int offset = (int)_FN->opcodes.count - compiler->loop->start + 2;
2021-02-13 01:40:19 +08:00
emitShort(compiler, offset);
}
2021-02-11 01:23:48 +08:00
/****************************************************************************
* COMPILING (PARSE TOPLEVEL) *
****************************************************************************/
2021-02-09 16:21:10 +08:00
2021-02-16 02:51:00 +08:00
typedef enum {
BLOCK_FUNC,
BLOCK_LOOP,
BLOCK_IF,
BLOCK_ELSE,
} BlockType;
2021-02-09 16:21:10 +08:00
static void compileStatement(Compiler* compiler);
2021-02-16 02:51:00 +08:00
static void compileBlockBody(Compiler* compiler, BlockType type);
2021-02-09 16:21:10 +08:00
2021-02-13 21:57:59 +08:00
// Compile a function and return it's index in the script's function buffer.
static int compileFunction(Compiler* compiler, FuncType fn_type) {
2021-02-07 15:40:00 +08:00
2021-02-13 21:57:59 +08:00
const char* name;
2021-02-16 02:51:00 +08:00
int name_length;
2021-02-07 15:40:00 +08:00
2021-02-13 21:57:59 +08:00
if (fn_type != FN_LITERAL) {
consume(compiler, TK_NAME, "Expected a function name.");
name = compiler->previous.start;
name_length = compiler->previous.length;
2021-05-20 22:05:57 +08:00
NameSearchResult result = compilerSearchName(compiler, name, name_length);
2021-02-13 21:57:59 +08:00
if (result.type != NAME_NOT_DEFINED) {
2021-05-20 22:05:57 +08:00
parseError(compiler, "Name '%.*s' already exists.", name_length, name);
2021-02-13 21:57:59 +08:00
}
} else {
2021-06-07 13:54:06 +08:00
name = LITERAL_FN_NAME;
2021-02-16 02:51:00 +08:00
name_length = (int)strlen(name);
2021-02-13 21:57:59 +08:00
}
2021-02-16 02:51:00 +08:00
Function* func = newFunction(compiler->vm, name, name_length,
2021-02-13 21:57:59 +08:00
compiler->script, fn_type == FN_NATIVE);
2021-02-15 20:49:19 +08:00
int fn_index = (int)compiler->script->functions.count - 1;
2021-06-04 22:55:06 +08:00
if (fn_index == MAX_FUNCTIONS) {
parseError(compiler, "A script should contain at most %d functions.",
MAX_FUNCTIONS);
}
2021-02-07 15:40:00 +08:00
2021-02-13 21:57:59 +08:00
Func curr_func;
curr_func.outer_func = compiler->func;
curr_func.ptr = func;
curr_func.depth = compiler->scope_depth;
compiler->func = &curr_func;
2021-02-07 15:40:00 +08:00
2021-02-12 01:35:43 +08:00
int argc = 0;
compilerEnterBlock(compiler); // Parameter depth.
2021-02-07 15:40:00 +08:00
2021-02-12 01:35:43 +08:00
// Parameter list is optional.
if (match(compiler, TK_LPARAN) && !match(compiler, TK_RPARAN)) {
2021-02-12 01:35:43 +08:00
do {
skipNewLines(compiler);
2021-02-07 15:40:00 +08:00
consume(compiler, TK_NAME, "Expected a parameter name.");
2021-02-12 01:35:43 +08:00
argc++;
2021-02-07 15:40:00 +08:00
const char* param_name = compiler->previous.start;
2021-06-08 00:56:56 +08:00
uint32_t param_len = compiler->previous.length;
2021-02-07 15:40:00 +08:00
2021-06-04 22:55:06 +08:00
// TODO: move this to a functions.
2021-02-12 01:35:43 +08:00
bool predefined = false;
2021-06-04 22:55:06 +08:00
for (int i = compiler->local_count - 1; i >= 0; i--) {
Local* local = &compiler->locals[i];
if (compiler->scope_depth != local->depth) break;
if (local->length == param_len &&
strncmp(local->name, param_name, param_len) == 0) {
2021-02-12 01:35:43 +08:00
predefined = true;
break;
}
}
2021-06-04 22:55:06 +08:00
if (predefined) {
2021-05-22 21:27:40 +08:00
parseError(compiler, "Multiple definition of a parameter.");
2021-06-04 22:55:06 +08:00
}
2021-02-11 01:23:48 +08:00
2021-02-12 01:35:43 +08:00
compilerAddVariable(compiler, param_name, param_len,
2021-05-19 02:59:09 +08:00
compiler->previous.line);
2021-02-11 01:23:48 +08:00
} while (match(compiler, TK_COMMA));
2021-02-07 15:40:00 +08:00
consume(compiler, TK_RPARAN, "Expected ')' after parameter list.");
2021-02-12 01:35:43 +08:00
}
2021-02-07 15:40:00 +08:00
2021-02-12 01:35:43 +08:00
func->arity = argc;
2021-02-07 15:40:00 +08:00
2021-02-13 21:57:59 +08:00
if (fn_type != FN_NATIVE) {
2021-02-16 02:51:00 +08:00
compileBlockBody(compiler, BLOCK_FUNC);
consume(compiler, TK_END, "Expected 'end' after function definition end.");
2021-06-08 00:56:56 +08:00
// TODO: This is the function end return, if we pop all the parameters the
// below push_null is redundent (because we always have a null at the rbp
// of the call frame. (for i in argc : emit(pop)) emit(return); but this
// might be faster (right?).
emitOpcode(compiler, OP_PUSH_NULL);
emitOpcode(compiler, OP_RETURN);
emitOpcode(compiler, OP_END);
}
2021-02-12 01:35:43 +08:00
compilerExitBlock(compiler); // Parameter depth.
#if DEBUG_DUMP_COMPILED_CODE
2021-05-16 15:05:54 +08:00
dumpFunctionCode(compiler->vm, compiler->func->ptr);
#endif
2021-02-13 21:57:59 +08:00
compiler->func = compiler->func->outer_func;
return fn_index;
2021-02-07 15:40:00 +08:00
}
2021-02-09 16:21:10 +08:00
// Finish a block body.
2021-02-16 02:51:00 +08:00
static void compileBlockBody(Compiler* compiler, BlockType type) {
2021-02-13 01:40:19 +08:00
2021-02-12 01:35:43 +08:00
compilerEnterBlock(compiler);
2021-02-16 02:51:00 +08:00
if (type == BLOCK_IF) {
consumeStartBlock(compiler, TK_THEN);
skipNewLines(compiler);
} else if (type == BLOCK_ELSE) {
skipNewLines(compiler);
} else if (type == BLOCK_FUNC) {
// Function body doesn't require a 'do' or 'then' delimiter to enter.
skipNewLines(compiler);
} else {
// For/While loop block body delimiter is 'do'.
consumeStartBlock(compiler, TK_DO);
skipNewLines(compiler);
2021-02-16 02:51:00 +08:00
}
TokenType next = peek(compiler);
2021-02-12 01:35:43 +08:00
while (!(next == TK_END || next == TK_EOF || (
2021-06-02 17:33:29 +08:00
(type == BLOCK_IF) && (next == TK_ELSE || next == TK_ELIF)))) {
2021-02-09 16:21:10 +08:00
2021-02-12 01:35:43 +08:00
compileStatement(compiler);
skipNewLines(compiler);
2021-02-09 16:21:10 +08:00
next = peek(compiler);
2021-02-12 01:35:43 +08:00
}
2021-02-09 16:21:10 +08:00
2021-02-12 01:35:43 +08:00
compilerExitBlock(compiler);
2021-02-09 16:21:10 +08:00
}
2021-05-19 02:59:09 +08:00
// Import a file at the given path (first it'll be resolved from the current
// path) and return it as a script pointer. And it'll emit opcodes to push
// that script to the stack.
static Script* importFile(Compiler* compiler, const char* path) {
PKVM* vm = compiler->vm;
2021-05-19 02:59:09 +08:00
// Resolve the path.
2021-06-04 22:55:06 +08:00
PkStringPtr resolved = { path, NULL, NULL };
2021-05-19 02:59:09 +08:00
if (vm->config.resolve_path_fn != NULL) {
resolved = vm->config.resolve_path_fn(vm, compiler->script->path->data,
path);
2021-05-19 02:59:09 +08:00
}
2021-05-09 20:31:36 +08:00
2021-05-22 21:27:40 +08:00
if (resolved.string == NULL) {
parseError(compiler, "Cannot resolve path '%s' from '%s'", path,
compiler->script->path->data);
}
2021-05-19 02:59:09 +08:00
// Create new string for the resolved path. And free the resolved path.
int index = (int)scriptAddName(compiler->script, compiler->vm,
resolved.string, (uint32_t)strlen(resolved.string));
String* path_name = compiler->script->names.data[index];
if (resolved.on_done != NULL) resolved.on_done(vm, resolved);
2021-05-09 20:31:36 +08:00
2021-05-19 02:59:09 +08:00
// Check if the script already exists.
Var entry = mapGet(vm->scripts, VAR_OBJ(path_name));
2021-05-19 02:59:09 +08:00
if (!IS_UNDEF(entry)) {
ASSERT(AS_OBJ(entry)->type == OBJ_SCRIPT, OOPS);
2021-05-09 20:31:36 +08:00
2021-05-19 02:59:09 +08:00
// Push the script on the stack.
emitOpcode(compiler, OP_IMPORT);
emitShort(compiler, index);
return (Script*)AS_OBJ(entry);
}
2021-05-19 02:59:09 +08:00
// The script not exists, make sure we have the script loading api function.
if (vm->config.load_script_fn == NULL) {
parseError(compiler, "Cannot import. The hosting application haven't "
"registered the script loading API");
return NULL;
}
2021-05-09 20:31:36 +08:00
2021-05-19 02:59:09 +08:00
// Load the script at the path.
2021-06-04 22:55:06 +08:00
PkStringPtr source = vm->config.load_script_fn(vm, path_name->data);
2021-05-19 02:59:09 +08:00
if (source.string == NULL) {
2021-06-04 22:55:06 +08:00
parseError(compiler, "Error loading script at \"%s\"", path_name->data);
2021-05-19 02:59:09 +08:00
return NULL;
}
2021-05-19 02:59:09 +08:00
// Make a new script and to compile it.
Script* scr = newScript(vm, path_name);
vmPushTempRef(vm, &scr->_super); // scr.
mapSet(vm, vm->scripts, VAR_OBJ(path_name), VAR_OBJ(scr));
2021-05-19 02:59:09 +08:00
vmPopTempRef(vm); // scr.
// Push the script on the stack.
emitOpcode(compiler, OP_IMPORT);
emitShort(compiler, index);
2021-06-07 13:54:06 +08:00
// Option for the compilation, even if we're running on repl mode the
// imported script cannot run on repl mode.
PkCompileOptions options = pkNewCompilerOptions();
if (compiler->options) options = *compiler->options;
options.repl_mode = false;
2021-05-19 02:59:09 +08:00
// Compile the source to the script and clean the source.
2021-06-09 18:42:26 +08:00
PkResult result = compile(vm, scr, source.string, &options);
2021-05-19 02:59:09 +08:00
if (source.on_done != NULL) source.on_done(vm, source);
2021-06-09 18:42:26 +08:00
if (result != PK_RESULT_SUCCESS) {
parseError(compiler, "Compilation of imported script '%s' failed",
path_name->data);
}
2021-05-19 02:59:09 +08:00
return scr;
}
// Import the core library from the vm's core_libs and it'll emit opcodes to
// push that script to the stack.
static Script* importCoreLib(Compiler* compiler, const char* name_start,
int name_length) {
// Add the name to the script's name buffer, we need it as a key to the
// vm's script cache.
int index = (int)scriptAddName(compiler->script, compiler->vm,
name_start, name_length);
String* module = compiler->script->names.data[index];
Var entry = mapGet(compiler->vm->core_libs, VAR_OBJ(module));
2021-05-19 02:59:09 +08:00
if (IS_UNDEF(entry)) {
parseError(compiler, "No module named '%s' exists.", module->data);
return NULL;
}
// Push the script on the stack.
emitOpcode(compiler, OP_IMPORT);
emitShort(compiler, index);
ASSERT(AS_OBJ(entry)->type == OBJ_SCRIPT, OOPS);
return (Script*)AS_OBJ(entry);
}
// Push the imported script on the stack and return the pointer. It could be
// either core library or a local import.
static inline Script* compilerImport(Compiler* compiler) {
// Get the script (from core libs or vm's cache or compile new one).
// And push it on the stack.
if (match(compiler, TK_NAME)) { //< Core library.
return importCoreLib(compiler, compiler->previous.start,
compiler->previous.length);
} else if (match(compiler, TK_STRING)) { //< Local library.
Var var_path = compiler->previous.value;
ASSERT(IS_OBJ_TYPE(var_path, OBJ_STRING), OOPS);
2021-05-19 02:59:09 +08:00
String* path = (String*)AS_OBJ(var_path);
return importFile(compiler, path->data);
}
// Invalid token after import/from keyword.
parseError(compiler, "Expected a module name or path to import.");
return NULL;
}
// Import all from the script, which is also would be at the top of the stack
// before executing the below instructions.
static void compilerImportAll(Compiler* compiler, Script* script) {
2021-06-08 00:56:56 +08:00
ASSERT(script != NULL, OOPS);
2021-05-19 02:59:09 +08:00
// Line number of the variables which will be bind to the imported sybmols.
int line = compiler->previous.line;
2021-06-04 22:55:06 +08:00
// TODO: Refactor this to a loop rather than jumping with goto.
2021-05-19 02:59:09 +08:00
// !!! WARNING !!!
//
// The below code uses 'goto' statement to run same loop twice with different
// string buffer, instead of making the loop a function or writeing it twice.
// So modify the below code with caution.
2021-06-09 18:42:26 +08:00
bool done = false; //< A flag to jump out of the loop.
pkUintBuffer* name_buff = NULL; //< The string buffer to iterate through.
goto L_first_buffer; //< Skip pass the below iteration.
2021-05-19 02:59:09 +08:00
// --------------------------------------------------------------------------
L_import_all_from_buffer:
// Iterate over the names and import them.
for (uint32_t i = 0; i < name_buff->count; i++) {
String* name = script->names.data[name_buff->data[i]];
// Special names are begins with '$' like function body (only for now).
// Skip them.
if (name->data[0] == '$') continue;
// Add the name to the **current** script's name buffer.
int name_index = (int)scriptAddName(compiler->script, compiler->vm,
name->data, name->length);
// Get the function from the script.
emitOpcode(compiler, OP_GET_ATTRIB_KEEP);
emitShort(compiler, name_index);
// Store the bind the function with the variable. If the variable already
// exists, override it, otherwise a add a new varaible.
int var_index = compilerGetVariable(compiler, name->data, name->length);
if (var_index == -1) {
var_index = compilerAddVariable(compiler, name->data,
name->length, line);
}
2021-05-19 02:59:09 +08:00
emitStoreVariable(compiler, var_index, true);
emitOpcode(compiler, OP_POP);
}
2021-05-09 20:31:36 +08:00
2021-05-19 02:59:09 +08:00
// If we have multiple buffer, we need to use an integer to keep track by
// incrementing it, But it's just 2 buffers so using a boolean 'done' here.
if (!done) {
done = true;
goto L_next_buffer;
2021-05-09 20:31:36 +08:00
} else {
2021-05-19 02:59:09 +08:00
goto L_import_done;
2021-05-09 20:31:36 +08:00
}
2021-05-19 02:59:09 +08:00
// --------------------------------------------------------------------------
2021-05-09 20:31:36 +08:00
2021-05-19 02:59:09 +08:00
// Set the buffer to function names and run the iteration.
L_first_buffer:
name_buff = &script->function_names;
goto L_import_all_from_buffer;
2021-05-09 20:31:36 +08:00
2021-05-19 02:59:09 +08:00
// Set the buffer to global names and run the iteration.
L_next_buffer:
name_buff = &script->global_names;
goto L_import_all_from_buffer;
L_import_done:
return;
2021-05-09 20:31:36 +08:00
}
2021-05-19 02:59:09 +08:00
// from module import symbol [as alias [, symbol2 [as alias]]]
static void compileFromImport(Compiler* compiler) {
2021-05-22 21:27:40 +08:00
// Import the library and push it on the stack. If the import failed
// lib_from would be NULL.
2021-05-19 02:59:09 +08:00
Script* lib_from = compilerImport(compiler);
2021-05-19 02:59:09 +08:00
// At this point the script would be on the stack before executing the next
// instruction.
consume(compiler, TK_IMPORT, "Expected keyword 'import'.");
if (match(compiler, TK_STAR)) {
// from math import *
2021-05-22 21:27:40 +08:00
if (lib_from) compilerImportAll(compiler, lib_from);
2021-05-09 20:31:36 +08:00
} else {
do {
2021-05-19 02:59:09 +08:00
// Consume the symbol name to import from the script.
consume(compiler, TK_NAME, "Expected symbol to import.");
const char* name = compiler->previous.start;
int length = compiler->previous.length;
int line = compiler->previous.line;
2021-05-19 02:59:09 +08:00
// Add the name of the symbol to the names buffer.
int name_index = (int)scriptAddName(compiler->script, compiler->vm,
name, length);
2021-05-19 02:59:09 +08:00
// Don't pop the lib since it'll be used for the next entry.
emitOpcode(compiler, OP_GET_ATTRIB_KEEP);
emitShort(compiler, name_index); //< Name of the attrib.
2021-05-19 02:59:09 +08:00
// Check if it has an alias.
if (match(compiler, TK_AS)) {
// Consuming it'll update the previous token which would be the name of
// the binding variable.
consume(compiler, TK_NAME, "Expected a name after 'as'.");
}
2021-05-19 02:59:09 +08:00
// Get the variable to bind the imported symbol, if we already have a
// variable with that name override it, otherwise use a new variable.
const char* name_start = compiler->previous.start;
length = compiler->previous.length, line = compiler->previous.line;
int var_index = compilerGetVariable(compiler, name_start, length);
if (var_index == -1) {
var_index = compilerAddVariable(compiler, name_start, length, line);
}
emitStoreVariable(compiler, var_index, true);
emitOpcode(compiler, OP_POP);
2021-06-08 00:56:56 +08:00
} while (match(compiler, TK_COMMA) && (skipNewLines(compiler), true));
2021-05-09 20:31:36 +08:00
}
2021-05-19 02:59:09 +08:00
// Done getting all the attributes, now pop the lib from the stack.
emitOpcode(compiler, OP_POP);
// Always end the import statement.
consumeEndStatement(compiler);
2021-05-09 20:31:36 +08:00
}
2021-05-19 02:59:09 +08:00
static void compileRegularImport(Compiler* compiler) {
do {
2021-05-22 21:27:40 +08:00
2021-05-29 02:53:46 +08:00
// Import the library and push it on the stack. If it cannot import,
2021-05-22 21:27:40 +08:00
// the lib would be null, but we're not terminating here, just continue
// parsing for cascaded errors.
2021-05-19 02:59:09 +08:00
Script* lib = compilerImport(compiler);
// variable to bind the imported script.
int var_index = -1;
// Check if it has an alias, if so bind the variable with that name.
if (match(compiler, TK_AS)) {
// Consuming it'll update the previous token which would be the name of
// the binding variable.
consume(compiler, TK_NAME, "Expected a name after 'as'.");
// Get the variable to bind the imported symbol, if we already have a
// variable with that name override it, otherwise use a new variable.
const char* name_start = compiler->previous.start;
int length = compiler->previous.length, line = compiler->previous.line;
var_index = compilerGetVariable(compiler, name_start, length);
if (var_index == -1) {
var_index = compilerAddVariable(compiler, name_start, length, line);
}
} else {
// If it has a module name use it as binding variable.
// Core libs names are it's module name but for local libs it's optional
// to define a module name for a script.
2021-05-22 21:27:40 +08:00
if (lib && lib->moudle != NULL) {
2021-05-19 02:59:09 +08:00
// Get the variable to bind the imported symbol, if we already have a
// variable with that name override it, otherwise use a new variable.
const char* name_start = lib->moudle->data;
int length = lib->moudle->length, line = compiler->previous.line;
var_index = compilerGetVariable(compiler, name_start, length);
if (var_index == -1) {
var_index = compilerAddVariable(compiler, name_start, length, line);
}
} else {
// -- Nothing to do here --
// Importing from path which doesn't have a module name. Import
// everything of it. and bind to a variables.
}
}
if (var_index != -1) {
emitStoreVariable(compiler, var_index, true);
emitOpcode(compiler, OP_POP);
} else {
2021-05-22 21:27:40 +08:00
if (lib) compilerImportAll(compiler, lib);
2021-05-19 02:59:09 +08:00
// Done importing everything from lib now pop the lib.
emitOpcode(compiler, OP_POP);
}
2021-06-08 00:56:56 +08:00
} while (match(compiler, TK_COMMA) && (skipNewLines(compiler), true));
2021-05-19 02:59:09 +08:00
consumeEndStatement(compiler);
}
2021-02-09 16:21:10 +08:00
// Compiles an expression. An expression will result a value on top of the
// stack.
static void compileExpression(Compiler* compiler) {
2021-02-12 01:35:43 +08:00
parsePrecedence(compiler, PREC_LOWEST);
2021-02-09 16:21:10 +08:00
}
2021-06-02 17:33:29 +08:00
static void compileIfStatement(Compiler* compiler, bool elif) {
2021-02-09 16:21:10 +08:00
skipNewLines(compiler);
2021-02-12 01:35:43 +08:00
compileExpression(compiler); //< Condition.
emitOpcode(compiler, OP_JUMP_IF_NOT);
int ifpatch = emitShort(compiler, 0xffff); //< Will be patched.
2021-02-09 16:21:10 +08:00
2021-02-16 02:51:00 +08:00
compileBlockBody(compiler, BLOCK_IF);
2021-06-02 17:33:29 +08:00
if (match(compiler, TK_ELIF)) {
2021-02-16 02:51:00 +08:00
// Jump pass else.
emitOpcode(compiler, OP_JUMP);
int exit_jump = emitShort(compiler, 0xffff); //< Will be patched.
2021-02-09 16:21:10 +08:00
2021-06-02 17:33:29 +08:00
// if (false) jump here.
2021-02-12 01:35:43 +08:00
patchJump(compiler, ifpatch);
2021-06-02 17:33:29 +08:00
compilerEnterBlock(compiler);
compileIfStatement(compiler, true);
compilerExitBlock(compiler);
2021-02-16 02:51:00 +08:00
patchJump(compiler, exit_jump);
2021-02-09 16:21:10 +08:00
} else if (match(compiler, TK_ELSE)) {
2021-02-16 02:51:00 +08:00
// Jump pass else.
emitOpcode(compiler, OP_JUMP);
int exit_jump = emitShort(compiler, 0xffff); //< Will be patched.
2021-02-12 01:35:43 +08:00
patchJump(compiler, ifpatch);
2021-02-16 02:51:00 +08:00
compileBlockBody(compiler, BLOCK_ELSE);
patchJump(compiler, exit_jump);
2021-02-09 16:21:10 +08:00
2021-02-12 01:35:43 +08:00
} else {
patchJump(compiler, ifpatch);
}
2021-02-11 01:23:48 +08:00
2021-06-02 17:33:29 +08:00
// elif will not consume the 'end' keyword as it'll be leaved to be consumed
// by it's 'if'.
2021-02-16 02:51:00 +08:00
if (!elif) {
skipNewLines(compiler);
consume(compiler, TK_END, "Expected 'end' after statement end.");
2021-02-16 02:51:00 +08:00
}
2021-02-09 16:21:10 +08:00
}
static void compileWhileStatement(Compiler* compiler) {
2021-02-12 01:35:43 +08:00
Loop loop;
2021-02-13 21:57:59 +08:00
loop.start = (int)_FN->opcodes.count;
2021-02-12 01:35:43 +08:00
loop.patch_count = 0;
loop.outer_loop = compiler->loop;
loop.depth = compiler->scope_depth;
2021-02-12 01:35:43 +08:00
compiler->loop = &loop;
2021-02-09 16:21:10 +08:00
2021-02-12 01:35:43 +08:00
compileExpression(compiler); //< Condition.
emitOpcode(compiler, OP_JUMP_IF_NOT);
int whilepatch = emitShort(compiler, 0xffff); //< Will be patched.
2021-02-09 16:21:10 +08:00
2021-02-16 02:51:00 +08:00
compileBlockBody(compiler, BLOCK_LOOP);
2021-02-09 16:21:10 +08:00
2021-02-13 01:40:19 +08:00
emitLoopJump(compiler);
2021-02-12 01:35:43 +08:00
patchJump(compiler, whilepatch);
2021-02-09 16:21:10 +08:00
2021-02-12 01:35:43 +08:00
// Patch break statement.
for (int i = 0; i < compiler->loop->patch_count; i++) {
patchJump(compiler, compiler->loop->patches[i]);
}
compiler->loop = loop.outer_loop;
2021-02-13 01:40:19 +08:00
skipNewLines(compiler);
consume(compiler, TK_END, "Expected 'end' after statement end.");
2021-02-09 16:21:10 +08:00
}
static void compileForStatement(Compiler* compiler) {
2021-02-13 01:40:19 +08:00
compilerEnterBlock(compiler);
consume(compiler, TK_NAME, "Expected an iterator name.");
2021-02-13 01:40:19 +08:00
// Unlike functions local variable could shadow a name.
const char* iter_name = compiler->previous.start;
int iter_len = compiler->previous.length;
int iter_line = compiler->previous.line;
2021-02-13 01:40:19 +08:00
consume(compiler, TK_IN, "Expected 'in' after iterator name.");
2021-02-13 01:40:19 +08:00
// Compile and store sequence.
compilerAddVariable(compiler, "@Sequence", 9, iter_line); // Sequence
2021-02-13 01:40:19 +08:00
compileExpression(compiler);
2021-05-24 06:17:52 +08:00
// Add iterator to locals. It's an increasing integer indicating that the
// current loop is nth starting from 0.
compilerAddVariable(compiler, "@iterator", 9, iter_line); // Iterator.
2021-05-24 06:17:52 +08:00
emitOpcode(compiler, OP_PUSH_0);
2021-02-13 01:40:19 +08:00
// Add the iteration value. It'll be updated to each element in an array of
// each character in a string etc.
compilerAddVariable(compiler, iter_name, iter_len, iter_line); // Iter value.
2021-02-13 01:40:19 +08:00
emitOpcode(compiler, OP_PUSH_NULL);
2021-05-24 06:17:52 +08:00
// Start the iteration, and check if the sequence is iterable.
emitOpcode(compiler, OP_ITER_TEST);
2021-02-13 01:40:19 +08:00
Loop loop;
2021-02-13 21:57:59 +08:00
loop.start = (int)_FN->opcodes.count;
2021-02-13 01:40:19 +08:00
loop.patch_count = 0;
loop.outer_loop = compiler->loop;
loop.depth = compiler->scope_depth;
2021-02-13 01:40:19 +08:00
compiler->loop = &loop;
// Compile next iteration.
emitOpcode(compiler, OP_ITER);
int forpatch = emitShort(compiler, 0xffff);
2021-02-16 02:51:00 +08:00
compileBlockBody(compiler, BLOCK_LOOP);
2021-02-13 01:40:19 +08:00
2021-05-24 06:17:52 +08:00
emitLoopJump(compiler); //< Loop back to iteration.
patchJump(compiler, forpatch); //< Patch exit iteration address.
2021-02-13 01:40:19 +08:00
// Patch break statement.
for (int i = 0; i < compiler->loop->patch_count; i++) {
patchJump(compiler, compiler->loop->patches[i]);
}
compiler->loop = loop.outer_loop;
skipNewLines(compiler);
consume(compiler, TK_END, "Expected 'end' after statement end.");
2021-02-13 01:40:19 +08:00
compilerExitBlock(compiler); //< Iterator scope.
2021-02-09 16:21:10 +08:00
}
2021-02-08 02:30:29 +08:00
// Compiles a statement. Assignment could be an assignment statement or a new
// variable declaration, which will be handled.
static void compileStatement(Compiler* compiler) {
2021-02-12 01:35:43 +08:00
2021-06-07 13:54:06 +08:00
// is_temproary will be set to true if the statement is an temporary
2021-06-08 00:56:56 +08:00
// expression, it'll used to be pop from the stack.
2021-06-07 13:54:06 +08:00
bool is_temproary = false;
2021-06-08 00:56:56 +08:00
// This will be set to true if the statement is an expression. It'll used to
// print it's value when running in REPL mode.
bool is_expression = false;
if (match(compiler, TK_BREAK)) {
2021-02-12 01:35:43 +08:00
if (compiler->loop == NULL) {
parseError(compiler, "Cannot use 'break' outside a loop.");
2021-02-12 01:35:43 +08:00
return;
}
ASSERT(compiler->loop->patch_count < MAX_BREAK_PATCH,
"Too many break statements (" STRINGIFY(MAX_BREAK_PATCH) ")." );
consumeEndStatement(compiler);
// Pop all the locals at the loop's body depth.
compilerPopLocals(compiler, compiler->loop->depth + 1);
2021-02-12 01:35:43 +08:00
emitOpcode(compiler, OP_JUMP);
2021-06-02 17:33:29 +08:00
int patch = emitShort(compiler, 0xffff); //< Will be patched.
2021-02-12 01:35:43 +08:00
compiler->loop->patches[compiler->loop->patch_count++] = patch;
} else if (match(compiler, TK_CONTINUE)) {
2021-02-12 01:35:43 +08:00
if (compiler->loop == NULL) {
parseError(compiler, "Cannot use 'continue' outside a loop.");
2021-02-12 01:35:43 +08:00
return;
}
consumeEndStatement(compiler);
// Pop all the locals at the loop's body depth.
compilerPopLocals(compiler, compiler->loop->depth + 1);
2021-02-13 01:40:19 +08:00
emitLoopJump(compiler);
2021-02-12 01:35:43 +08:00
} else if (match(compiler, TK_RETURN)) {
2021-02-12 01:35:43 +08:00
2021-02-13 21:57:59 +08:00
if (compiler->scope_depth == DEPTH_GLOBAL) {
parseError(compiler, "Invalid 'return' outside a function.");
2021-02-12 01:35:43 +08:00
return;
}
if (matchEndStatement(compiler)) {
2021-02-12 01:35:43 +08:00
emitOpcode(compiler, OP_PUSH_NULL);
emitOpcode(compiler, OP_RETURN);
} else {
compileExpression(compiler); //< Return value is at stack top.
consumeEndStatement(compiler);
2021-02-12 01:35:43 +08:00
emitOpcode(compiler, OP_RETURN);
}
} else if (match(compiler, TK_IF)) {
2021-06-02 17:33:29 +08:00
compileIfStatement(compiler, false);
2021-02-12 01:35:43 +08:00
} else if (match(compiler, TK_WHILE)) {
2021-02-12 01:35:43 +08:00
compileWhileStatement(compiler);
} else if (match(compiler, TK_FOR)) {
2021-02-12 01:35:43 +08:00
compileForStatement(compiler);
} else {
compiler->new_local = false;
2021-02-12 01:35:43 +08:00
compileExpression(compiler);
consumeEndStatement(compiler);
2021-06-08 00:56:56 +08:00
is_expression = true;
2021-06-07 13:54:06 +08:00
if (!compiler->new_local) is_temproary = true;
2021-06-08 00:56:56 +08:00
compiler->new_local = false;
2021-02-12 01:35:43 +08:00
}
2021-06-07 13:54:06 +08:00
2021-06-08 00:56:56 +08:00
// If running REPL mode, print the expression's evaluvated value. Only if
// we're at the top level. Python does print local depth expression too.
// (it's just a design decision).
2021-06-07 13:54:06 +08:00
if (compiler->options && compiler->options->repl_mode &&
2021-06-08 00:56:56 +08:00
compiler->func->ptr == compiler->script->body &&
is_expression /*&& compiler->scope_depth == DEPTH_GLOBAL*/) {
2021-06-07 13:54:06 +08:00
emitOpcode(compiler, OP_REPL_PRINT);
}
if (is_temproary) emitOpcode(compiler, OP_POP);
}
// Compile statements that are only valid at the top level of the script. Such
// as import statement, function define, and if we're running REPL mode top
// level expression's evaluvated value will be printed.
static void compileTopLevelStatement(Compiler* compiler) {
if (match(compiler, TK_NATIVE)) {
compileFunction(compiler, FN_NATIVE);
} else if (match(compiler, TK_DEF)) {
compileFunction(compiler, FN_SCRIPT);
} else if (match(compiler, TK_FROM)) {
compileFromImport(compiler);
} else if (match(compiler, TK_IMPORT)) {
compileRegularImport(compiler);
} else if (match(compiler, TK_MODULE)) {
parseError(compiler, "Module name must be the first statement "
"of the script.");
} else {
compileStatement(compiler);
}
2021-02-08 02:30:29 +08:00
}
2021-06-09 18:42:26 +08:00
PkResult compile(PKVM* vm, Script* script, const char* source,
2021-06-07 13:54:06 +08:00
const PkCompileOptions* options) {
2021-02-12 01:35:43 +08:00
// Skip utf8 BOM if there is any.
if (strncmp(source, "\xEF\xBB\xBF", 3) == 0) source += 3;
Compiler _compiler;
Compiler* compiler = &_compiler; //< Compiler pointer for quick access.
2021-06-07 13:54:06 +08:00
compilerInit(compiler, vm, source, script, options);
// If compiling for an imported script the vm->compiler would be the compiler
2021-05-19 02:59:09 +08:00
// of the script that imported this script. Add the all the compilers into a
// link list.
compiler->next_compiler = vm->compiler;
vm->compiler = compiler;
2021-02-13 21:57:59 +08:00
2021-06-08 00:56:56 +08:00
// If we're compiling for a script that was already compiled (when running
// REPL or evaluvating an expression) we don't need the old main anymore.
// just use the globals and functions of the script and use a new body func.
ASSERT(script->body != NULL, OOPS);
2021-06-09 18:42:26 +08:00
pkByteBufferClear(&script->body->fn->opcodes, vm);
2021-06-08 00:56:56 +08:00
// Remember the count of the globals and functions, If the compilation failed
// discard all the globals and functions added by the compilation.
uint32_t globals_count = script->globals.count;
uint32_t functions_count = script->functions.count;
2021-06-07 13:54:06 +08:00
2021-02-13 21:57:59 +08:00
Func curr_fn;
curr_fn.depth = DEPTH_SCRIPT;
curr_fn.ptr = script->body;
curr_fn.outer_func = NULL;
compiler->func = &curr_fn;
2021-02-07 15:40:00 +08:00
2021-02-12 01:35:43 +08:00
// Lex initial tokens. current <-- next.
lexToken(compiler);
lexToken(compiler);
skipNewLines(compiler);
2021-02-07 15:40:00 +08:00
2021-05-19 02:59:09 +08:00
if (match(compiler, TK_MODULE)) {
// If the script running a REPL or compiled multiple times by hosting
// application module attribute might already set. In that case make it
// Compile error.
if (script->moudle != NULL) {
parseError(compiler, "Module name already defined.");
} else {
consume(compiler, TK_NAME, "Expected a name for the module.");
const char* name = compiler->previous.start;
uint32_t len = compiler->previous.length;
script->moudle = newStringLength(vm, name, len);
consumeEndStatement(compiler);
}
}
while (!match(compiler, TK_EOF)) {
2021-06-07 13:54:06 +08:00
compileTopLevelStatement(compiler);
skipNewLines(compiler);
2021-02-12 01:35:43 +08:00
}
2021-02-07 15:40:00 +08:00
emitOpcode(compiler, OP_PUSH_NULL);
2021-06-08 00:56:56 +08:00
emitOpcode(compiler, OP_RETURN);
emitOpcode(compiler, OP_END);
2021-02-07 15:40:00 +08:00
2021-05-20 22:05:57 +08:00
// Resolve forward names (function names that are used before defined).
for (int i = 0; i < compiler->forwards_count; i++) {
ForwardName* forward = &compiler->forwards[i];
const char* name = forward->name;
int length = forward->length;
2021-06-07 13:54:06 +08:00
int index = scriptGetFunc(script, name, (uint32_t)length);
2021-05-20 22:05:57 +08:00
if (index != -1) {
patchForward(compiler, forward->func, forward->instruction, index);
} else {
2021-06-09 18:42:26 +08:00
// need_more_lines is only true for unexpected EOF errors. For syntax
// errors it'll be false by now but. Here it's a semantic errors, so
// we're overriding it to false.
compiler->need_more_lines = false;
resolveError(compiler, forward->line, "Name '%.*s' is not defined.",
length, name);
2021-05-20 22:05:57 +08:00
}
}
2021-05-19 02:59:09 +08:00
vm->compiler = compiler->next_compiler;
2021-02-08 02:30:29 +08:00
2021-06-08 00:56:56 +08:00
// If compilation failed, discard all the invalid functions and globals.
2021-06-07 13:54:06 +08:00
if (compiler->has_errors) {
2021-06-08 00:56:56 +08:00
script->globals.count = script->global_names.count = globals_count;
script->functions.count = script->function_names.count = functions_count;
2021-06-07 13:54:06 +08:00
}
2021-06-08 00:56:56 +08:00
#if DEBUG_DUMP_COMPILED_CODE
dumpFunctionCode(vm, script->body);
#endif
2021-06-09 18:42:26 +08:00
// Return the compilation result.
if (compiler->has_errors) {
if (compiler->options && compiler->options->repl_mode &&
compiler->need_more_lines) {
return PK_RESULT_UNEXPECTED_EOF;
}
return PK_RESULT_COMPILE_ERROR;
}
return PK_RESULT_SUCCESS;
2021-06-07 13:54:06 +08:00
}
PkResult pkCompileModule(PKVM* vm, PkHandle* module, PkStringPtr source,
2021-06-08 00:56:56 +08:00
const PkCompileOptions* options) {
2021-06-07 13:54:06 +08:00
__ASSERT(module != NULL, "Argument module was NULL.");
Var scr = module->value;
__ASSERT(IS_OBJ_TYPE(scr, OBJ_SCRIPT), "Given handle is not a module");
Script* script = (Script*)AS_OBJ(scr);
2021-06-09 18:42:26 +08:00
PkResult result = compile(vm, script, source.string, options);
2021-06-07 13:54:06 +08:00
if (source.on_done) source.on_done(vm, source);
2021-06-09 18:42:26 +08:00
return result;
2021-02-07 15:40:00 +08:00
}
2021-04-26 17:34:30 +08:00
2021-05-19 02:59:09 +08:00
void compilerMarkObjects(PKVM* vm, Compiler* compiler) {
2021-04-26 17:34:30 +08:00
// Mark the script which is currently being compiled.
2021-05-19 02:59:09 +08:00
grayObject(vm, &compiler->script->_super);
2021-04-26 17:34:30 +08:00
// Mark the string literals (they haven't added to the script's literal
// buffer yet).
2021-05-19 02:59:09 +08:00
grayValue(vm, compiler->current.value);
grayValue(vm, compiler->previous.value);
grayValue(vm, compiler->next.value);
if (compiler->next_compiler != NULL) {
compilerMarkObjects(vm, compiler->next_compiler);
}
2021-04-26 17:34:30 +08:00
}