From 9de1d1752970ba09f9d0b77a8ae6c0d4b8910bc7 Mon Sep 17 00:00:00 2001 From: Hannes Bredberg Date: Thu, 5 Oct 2023 01:36:00 +0200 Subject: [PATCH] Parse while expressions --- selfhost/parser.n | 13 +++++++++++++ selfhost/tokenizer.n | 10 ++++++++++ 2 files changed, 23 insertions(+) diff --git a/selfhost/parser.n b/selfhost/parser.n index ff02894..ea54c8d 100644 --- a/selfhost/parser.n +++ b/selfhost/parser.n @@ -38,6 +38,10 @@ const NodeType = enum(u8) { // payload: loop body @"loop", + // idx - 1: condition + // payload: while body + @"while", + // token is the keyword // payload is optional value return_expr, @@ -297,6 +301,15 @@ fn parse_primary_expression(context: *ParserContext, require: bool, precedence: node_payload.get(result).* = parse_block(context); return result; } + else if(p == .while_keyword) { + const token = context.advance(); + context.expect("Expected '(' after 'while'".&, .@"("); + parse_expression(context); + const result = add_with_token(token, .@"while"); + context.expect("Expected ')' after while condition".&, .@")"); + node_payload.get(result).* = parse_expression_with_precedence(context, true, precedence); + return result; + } else if(p == .@"{") { const result = add_with_token(context.current_token, .block); node_payload.get(result).* = parse_block(context); diff --git a/selfhost/tokenizer.n b/selfhost/tokenizer.n index 491cf73..209a8da 100644 --- a/selfhost/tokenizer.n +++ b/selfhost/tokenizer.n @@ -37,6 +37,7 @@ const TokenType = enum(u8) { unreachable_keyword, var_keyword, //volatile_keyword, + while_keyword, __keyword, //bool_keyword, @@ -312,6 +313,15 @@ fn init() void { } }.&; + token_handlers['w'] = fn(context: *TokenizationContext) void { + if(context.matches("while".&)) { + context.add_token_advance(.while_keyword, 5); + } + else { + ident_handler(context); + } + }.&; + { var ch: u32 = 0; loop(ch <= 0xFF) {