Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type Hints #757

Draft
wants to merge 3 commits into
base: develop
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/vm/compiler.c
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,13 @@ static void block(Compiler *compiler) {
consume(compiler, TOKEN_RIGHT_BRACE, "Expect '}' after block.");
}

inline static void checkTypeHint(Compiler *compiler) {
if (match(compiler, TOKEN_COLON)) {
match(compiler, TOKEN_QUESTION);
consume(compiler, TOKEN_IDENTIFIER, "Expect type hint identifier");
}
}

static void beginFunction(Compiler *compiler, Compiler *fnCompiler, FunctionType type, AccessLevel level) {
initCompiler(compiler->parser, fnCompiler, compiler, type, level);
beginScope(fnCompiler);
Expand Down Expand Up @@ -888,6 +895,8 @@ static void beginFunction(Compiler *compiler, Compiler *fnCompiler, FunctionType
error(fnCompiler->parser, "Cannot have more than 255 parameters.");
}
index++;

checkTypeHint(compiler);
} while (match(fnCompiler, TOKEN_COMMA));

if (fnCompiler->function->arityOptional > 0) {
Expand Down Expand Up @@ -1577,6 +1586,9 @@ static void function(Compiler *compiler, FunctionType type, AccessLevel level) {
// Setup function and parse parameters
beginFunction(compiler, &fnCompiler, type, level);

// Type hint
checkTypeHint(compiler);

// The body.
consume(&fnCompiler, TOKEN_LEFT_BRACE, "Expect '{' before function body.");
block(&fnCompiler);
Expand Down Expand Up @@ -2097,6 +2109,8 @@ static void enumDeclaration(Compiler *compiler) {

emitBytes(compiler, OP_ENUM, nameConstant);

checkTypeHint(compiler);

consume(compiler, TOKEN_LEFT_BRACE, "Expect '{' before enum body.");

int index = 0;
Expand Down Expand Up @@ -2138,6 +2152,8 @@ static void varDeclaration(Compiler *compiler, bool constant) {
consume(compiler, TOKEN_IDENTIFIER, "Expect variable name.");
variables[varCount] = compiler->parser->previous;
varCount++;

checkTypeHint(compiler);
} while (match(compiler, TOKEN_COMMA));

consume(compiler, TOKEN_RIGHT_BRACKET, "Expect ']' after list destructure.");
Expand All @@ -2162,6 +2178,8 @@ static void varDeclaration(Compiler *compiler, bool constant) {
do {
uint8_t global = parseVariable(compiler, "Expect variable name.", constant);

checkTypeHint(compiler);

if (match(compiler, TOKEN_EQUAL) || constant) {
// Compile the initializer.
expression(compiler);
Expand Down
Loading