Something went wrong. Try again.
A general purpose .. programming language written in zig ijadux2.tngl.sh/Rinnescript
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943// parser_v2.zig — RinneScript v2 front end.//// Architecture (see V2.md): v2 source is parsed here and *lowered in memory*// to the v1 AST (`parser.Program`), which the existing compiler and VM then// consume unchanged. Anything outside the implemented stages fails loudly// with "v2: ... (stage N)" instead of mis-compiling.//// Stage 1 (runs today):// use std / use <known module>; prelude calls (println/eprintln/assert/// assert_eq/panic/len/range) routed to std.*; string interpolation// ({{ }} => literal braces, {} interpolates); optional semicolons;// if/while/loop/for-in/range-for/return/break/continue/defer; var/const// declarations; assignment and compound assignment (+= -= *= /= %=);// ** operator (lowered to std.math.pow); arrays; record/map literals// (bare keys = record, quoted keys = dynamic map).//// Parse error today (Stage 2):// if/match expressions, ?T / !T / try / catch / fail, tuples, record// destructuring, for k, v / for x, idx, named arguments, test blocks,// payload enums, struct methods, sized numeric semantics.
const std = @import("std");const Lexer = @import("lexer.zig").Lexer;const Token = @import("lexer.zig").Token;const TokenType = @import("lexer.zig").TokenType;const parser_mod = @import("parser.zig");const DataType = parser_mod.DataType;const Primitive = DataType.Primitive;
pub const ParseError = parser_mod.Parser.ParseError;
pub const ParserV2 = struct { lexer: Lexer, current: Token, allocator: std.mem.Allocator, err_msg: ?[]u8 = null, err_line: usize = 0, err_col: usize = 0,
pub fn init(allocator: std.mem.Allocator, source: []const u8) ParserV2 { var p: ParserV2 = .{ .lexer = Lexer.init(source), .current = undefined, .allocator = allocator, }; p.current = p.lexer.nextToken(); return p; }
fn fail(self: *ParserV2, e: ParseError, comptime fmt: []const u8, args: anytype) ParseError { if (self.err_msg == null) { self.err_msg = std.fmt.allocPrint(self.allocator, "v2: " ++ fmt ++ " (line {d}:{d})", args ++ .{ self.current.line, self.current.column }) catch null; self.err_line = self.current.line; self.err_col = self.current.column; } return e; }
fn advance(self: *ParserV2) Token { const t = self.current; self.current = self.lexer.nextToken(); return t; }
fn match(self: *ParserV2, tag: TokenType) bool { if (self.current.tag == tag) { _ = self.advance(); return true; } return false; }
fn expect(self: *ParserV2, tag: TokenType) ParseError!Token { const t = self.current; if (t.tag == tag) { _ = self.advance(); return t; } return self.fail(error.UnexpectedToken, "expected '{s}', got '{s}'", .{ @tagName(tag), t.lexeme }); }
fn peekIs(self: *const ParserV2, tag: TokenType) bool { return self.current.tag == tag; }
fn dupe(self: *ParserV2, s: []const u8) ParseError![]u8 { return self.allocator.dupe(u8, s) catch error.OutOfMemory; }
/// v2 annotations parse and are stored, then erased (runtime is dynamic). /// `?T` / `!T` unwrap to the inner type for now (Stage 2 adds semantics). fn parseType(self: *ParserV2) ParseError!DataType { if (self.match(.question) or self.match(.bang)) { const inner = try self.parseType(); return inner; // erased: inner type, ? semantics land in Stage 2 } const t = self.current; _ = self.advance(); return switch (t.tag) { .type_int => DataType{ .primitive = .int }, .type_float => DataType{ .primitive = .float }, .type_str => DataType{ .primitive = .str }, .type_bool => DataType{ .primitive = .bool }, .kw_null => DataType{ .primitive = .void_type }, .identifier => switch (t.lexeme[0]) { 'i' => DataType{ .primitive = .int }, 'u' => DataType{ .primitive = .int }, 'f' => DataType{ .primitive = .float }, else => DataType{ .primitive = .inferred }, }, .kw_struct, .kw_enum => DataType{ .primitive = .inferred }, else => self.fail(error.UnexpectedToken, "unknown type '{s}'", .{t.lexeme}), }; }
// ---- program ------------------------------------------------------
pub fn parseProgram(self: *ParserV2) ParseError!parser_mod.Program { var directives: std.ArrayList(parser_mod.Directive) = .empty; var structs: std.ArrayList(parser_mod.StructDecl) = .empty; var enums: std.ArrayList(parser_mod.EnumDecl) = .empty; var fns: std.ArrayList(parser_mod.FnDecl) = .empty; var globals: std.ArrayList(parser_mod.Stmt) = .empty; var gl_lines: std.ArrayList(u32) = .empty; var gl_cols: std.ArrayList(u32) = .empty;
while (!self.peekIs(.eof)) { const ln = @as(u32, @intCast(self.current.line)); const cl = @as(u32, @intCast(self.current.column)); switch (self.current.tag) { .semicolon => _ = self.advance(), .identifier => { const kw = self.current.lexeme; if (std.mem.eql(u8, kw, "use")) { try self.parseUse(&directives); } else if (std.mem.eql(u8, kw, "test")) { return self.fail(error.UnexpectedToken, "'test' blocks are stage 2", .{}); } else { try globals.append(self.allocator, try self.parseStatement()); try gl_lines.append(self.allocator, ln); try gl_cols.append(self.allocator, cl); } }, .kw_struct => try structs.append(self.allocator, try self.parseStruct(false)), .kw_enum => try enums.append(self.allocator, try self.parseEnum(false)), .kw_pub => { _ = self.advance(); switch (self.current.tag) { .kw_struct => try structs.append(self.allocator, try self.parseStruct(true)), .kw_enum => try enums.append(self.allocator, try self.parseEnum(true)), .kw_fn => try fns.append(self.allocator, try self.parseFn(true)), else => return self.fail(error.UnexpectedToken, "'pub' must precede fn, struct or enum", .{}), } }, .kw_fn => try fns.append(self.allocator, try self.parseFn(false)), else => { try globals.append(self.allocator, try self.parseStatement()); try gl_lines.append(self.allocator, ln); try gl_cols.append(self.allocator, cl); }, } }
return .{ .directives = try directives.toOwnedSlice(self.allocator), .struct_decls = try structs.toOwnedSlice(self.allocator), .enum_decls = try enums.toOwnedSlice(self.allocator), .fn_decls = try fns.toOwnedSlice(self.allocator), .global_stmts = .{ .stmts = try globals.toOwnedSlice(self.allocator), .lines = try gl_lines.toOwnedSlice(self.allocator), .cols = try gl_cols.toOwnedSlice(self.allocator), }, }; }
fn parseUse(self: *ParserV2, directives: *std.ArrayList(parser_mod.Directive)) ParseError!void { _ = try self.expect(.identifier); // "use" — caller has verified the lexeme const first = try self.expect(.identifier); if (std.mem.eql(u8, first.lexeme, "std")) { try directives.append(self.allocator, .{ .import_directive = try self.dupe("std") }); if (self.match(.period)) { if (!self.peekIs(.l_brace)) { return self.fail(error.UnexpectedToken, "expected '.{{ ... }}' after 'use std', e.g. `use std.{{ math, fs }}`; topic namespaces are stage 3", .{}); } _ = try self.expect(.l_brace); while (!self.peekIs(.r_brace) and !self.peekIs(.eof)) { _ = try self.expect(.identifier); if (!self.match(.comma)) break; } _ = try self.expect(.r_brace); } _ = self.match(.semicolon); return; } const known = [_][]const u8{ "net", "ai", "llm", "c", "runic" }; for (known) |k| { if (std.mem.eql(u8, first.lexeme, k)) { try directives.append(self.allocator, .{ .import_directive = try self.dupe(first.lexeme) }); _ = self.match(.semicolon); return; } } return self.fail(error.UnexpectedToken, "unknown module '{s}' in use (known: std, net, ai, llm, c, runic)", .{first.lexeme}); }
fn parseStruct(self: *ParserV2, is_pub: bool) ParseError!parser_mod.StructDecl { _ = try self.expect(.kw_struct); const name_tok = try self.expect(.identifier); _ = try self.expect(.l_brace); var fields: std.ArrayList(parser_mod.StructFieldDef) = .empty; while (!self.peekIs(.r_brace) and !self.peekIs(.eof)) { if (self.peekIs(.kw_fn)) { return self.fail(error.UnexpectedToken, "struct methods are stage 2", .{}); } const fname = try self.expect(.identifier); _ = try self.expect(.colon); const ftype = try self.parseType(); var def_val: ?parser_mod.Expr = null; if (self.match(.assign)) def_val = try self.parseOr(); try fields.append(self.allocator, .{ .name = fname.lexeme, .field_type = ftype, .default_value = def_val, .is_required = def_val == null, }); _ = self.match(.comma); } _ = try self.expect(.r_brace); return .{ .name = name_tok.lexeme, .is_pub = is_pub, .fields = try fields.toOwnedSlice(self.allocator), }; }
fn parseEnum(self: *ParserV2, is_pub: bool) ParseError!parser_mod.EnumDecl { _ = try self.expect(.kw_enum); const name_tok = try self.expect(.identifier); _ = try self.expect(.l_brace); var variants: std.ArrayList(parser_mod.EnumVariant) = .empty; while (!self.peekIs(.r_brace) and !self.peekIs(.eof)) { const vname = try self.expect(.identifier); var value: ?i64 = null; if (self.match(.assign)) { if (self.current.tag == .int_literal) { value = std.fmt.parseInt(i64, self.current.lexeme, 10) catch null; _ = self.advance(); } else { return self.fail(error.UnexpectedToken, "enum tag must be an integer literal", .{}); } } else if (self.peekIs(.l_paren)) { return self.fail(error.UnexpectedToken, "payload enums are stage 2", .{}); } try variants.append(self.allocator, .{ .name = vname.lexeme, .value = value }); _ = self.match(.comma); } _ = try self.expect(.r_brace); return .{ .name = name_tok.lexeme, .is_pub = is_pub, .variants = try variants.toOwnedSlice(self.allocator), }; }
fn parseFn(self: *ParserV2, is_pub: bool) ParseError!parser_mod.FnDecl { _ = try self.expect(.kw_fn); const name_tok = try self.expect(.identifier); _ = try self.expect(.l_paren); var params: std.ArrayList(parser_mod.FnParam) = .empty; while (!self.peekIs(.r_paren) and !self.peekIs(.eof)) { const pname = try self.expect(.identifier); var ptype: DataType = .{ .primitive = .inferred }; if (self.match(.colon)) ptype = try self.parseType(); if (self.peekIs(.assign)) { return self.fail(error.UnexpectedToken, "default parameter values are stage 2", .{}); } try params.append(self.allocator, .{ .name = pname.lexeme, .param_type = ptype }); if (!self.match(.comma)) break; } _ = try self.expect(.r_paren); var rtype: DataType = .{ .primitive = .inferred }; if (self.match(.arrow)) { rtype = try self.parseType(); } else if (self.peekIs(.bang)) { rtype = try self.parseType(); } else if (self.peekIs(.type_int) or self.peekIs(.type_float) or self.peekIs(.type_str) or self.peekIs(.type_bool)) { rtype = try self.parseType(); } const body = try self.parseBlock(); return .{ .is_pub = is_pub, .name = name_tok.lexeme, .params = try params.toOwnedSlice(self.allocator), .return_type = rtype, .decorators = &.{}, .body = body, }; }
fn parseBlock(self: *ParserV2) ParseError!parser_mod.Block { _ = try self.expect(.l_brace); var stmts: std.ArrayList(parser_mod.Stmt) = .empty; var lines: std.ArrayList(u32) = .empty; var cols: std.ArrayList(u32) = .empty; while (!self.peekIs(.r_brace) and !self.peekIs(.eof)) { const ln = @as(u32, @intCast(self.current.line)); const cl = @as(u32, @intCast(self.current.column)); try stmts.append(self.allocator, try self.parseStatement()); try lines.append(self.allocator, ln); try cols.append(self.allocator, cl); } _ = try self.expect(.r_brace); return .{ .stmts = try stmts.toOwnedSlice(self.allocator), .lines = try lines.toOwnedSlice(self.allocator), .cols = try cols.toOwnedSlice(self.allocator), }; }
fn parseStatement(self: *ParserV2) ParseError!parser_mod.Stmt { // Contextual v2 keywords: statements may not fall through to // expressions for these — the v1 grammar treats them as identifiers. if (self.current.tag == .identifier) { const kw = self.current.lexeme; if (std.mem.eql(u8, kw, "loop")) { _ = self.advance(); const body = try self.parseBlock(); return .{ .while_stmt = .{ .condition = .{ .bool_lit = true }, .body = body } }; } if (std.mem.eql(u8, kw, "match")) return self.fail(error.UnexpectedToken, "match expressions are stage 2", .{}); if (std.mem.eql(u8, kw, "fail")) return self.fail(error.UnexpectedToken, "fail is stage 2", .{}); if (std.mem.eql(u8, kw, "catch")) return self.fail(error.UnexpectedToken, "catch is stage 2", .{}); if (std.mem.eql(u8, kw, "use")) return self.fail(error.UnexpectedToken, "'use' is only valid at module top level", .{}); if (std.mem.eql(u8, kw, "test")) return self.fail(error.UnexpectedToken, "'test' blocks are stage 2", .{}); } switch (self.current.tag) { .kw_const, .kw_var => { const kw = self.current; _ = self.advance(); const name_tok = try self.expect(.identifier); var type_ann: ?DataType = null; if (self.match(.colon)) type_ann = try self.parseType(); _ = try self.expect(.assign); const init_expr = try self.parseOr(); _ = self.match(.semicolon); return .{ .var_decl = .{ .is_const = kw.tag == .kw_const, .name = name_tok.lexeme, .type_ann = type_ann, .initializer = init_expr, } }; }, .kw_if => { const s = try self.parseIfStmt(); _ = self.match(.semicolon); return s; }, .kw_while => { const s = try self.parseWhileStmt(); _ = self.match(.semicolon); return s; }, .kw_for => { const s = try self.parseForStmt(); _ = self.match(.semicolon); return s; }, .kw_return => { _ = self.advance(); if (self.peekIs(.r_brace) or self.peekIs(.semicolon)) { _ = self.match(.semicolon); return .{ .return_stmt = null }; } const e = try self.parseOr(); _ = self.match(.semicolon); return .{ .return_stmt = e }; }, .kw_break => { _ = self.advance(); _ = self.match(.semicolon); return .break_stmt; }, .kw_continue => { _ = self.advance(); _ = self.match(.semicolon); return .continue_stmt; }, .kw_defer => { _ = self.advance(); const e = try self.parseOr(); _ = self.match(.semicolon); return .{ .defer_stmt = e }; }, .semicolon => { _ = self.advance(); return .{ .expr_stmt = .{ .null_lit = {} } }; }, else => { const lhs = try self.parseOr(); const tag = self.current.tag; if (tag == .assign or tag == .plus_eq or tag == .minus_eq or tag == .star_eq or tag == .slash_eq or tag == .percent_eq) { return try self.parseAssignLike(lhs, tag); } _ = self.match(.semicolon); return .{ .expr_stmt = lhs }; }, } }
fn parseAssignLike(self: *ParserV2, lhs: parser_mod.Expr, op: TokenType) ParseError!parser_mod.Stmt { _ = self.advance(); // consume the operator const value = try self.parseOr(); _ = self.match(.semicolon); if (op == .assign) { return .{ .assignment = .{ .target = lhs, .value = value } }; } // Compound: target op= value => target = clone(target) <op> value. const bin_op: TokenType = switch (op) { .plus_eq => .plus, .minus_eq => .minus, .star_eq => .star, .slash_eq => .slash, .percent_eq => .percent, else => unreachable, }; const read_side = try cloneExpr(self.allocator, &lhs); const rhs = try self.allocator.create(parser_mod.Expr); rhs.* = value; const rhsp = parser_mod.Expr{ .binary = .{ .op = bin_op, .lhs = read_side, .rhs = rhs } }; return .{ .assignment = .{ .target = lhs, .value = rhsp } }; }
fn parseIfStmt(self: *ParserV2) ParseError!parser_mod.Stmt { _ = try self.expect(.kw_if); const cond = try self.parseOr(); const then_b = try self.parseBlock(); var else_b: ?parser_mod.Block = null; if (self.match(.kw_else)) { if (self.peekIs(.kw_if)) { const inner = try self.parseIfStmt(); const stmts = self.allocator.alloc(parser_mod.Stmt, 1) catch return error.OutOfMemory; stmts[0] = inner; const lines = self.allocator.alloc(u32, 1) catch return error.OutOfMemory; const cols = self.allocator.alloc(u32, 1) catch return error.OutOfMemory; lines[0] = 0; cols[0] = 0; else_b = .{ .stmts = stmts, .lines = lines, .cols = cols }; } else { else_b = try self.parseBlock(); } } return .{ .if_stmt = .{ .condition = cond, .then_branch = then_b, .else_branch = else_b } }; }
fn parseWhileStmt(self: *ParserV2) ParseError!parser_mod.Stmt { _ = try self.expect(.kw_while); const cond = try self.parseOr(); const body = try self.parseBlock(); return .{ .while_stmt = .{ .condition = cond, .body = body } }; }
fn parseForStmt(self: *ParserV2) ParseError!parser_mod.Stmt { _ = try self.expect(.kw_for); const name_tok = try self.expect(.identifier); var idx_name: ?[]const u8 = null; if (self.match(.comma)) { idx_name = (try self.expect(.identifier)).lexeme; } _ = try self.expect(.kw_in); const lo = try self.parseTerm(); if (self.peekIs(.dot_dot) or self.peekIs(.dot_dot_equal)) { const inclusive = self.current.tag == .dot_dot_equal; _ = self.advance(); const hi = try self.parseTerm(); const body = try self.parseBlock(); if (idx_name != null) return self.fail(error.UnexpectedToken, "two-name for is only for arrays/maps", .{}); return .{ .range_for = .{ .var_name = name_tok.lexeme, .lo = lo, .hi = hi, .hi_inclusive = inclusive, .body = body } }; } if (idx_name != null) { return self.fail(error.UnexpectedToken, "for name, idx in xs is stage 2", .{}); } const body = try self.parseBlock(); return .{ .for_stmt = .{ .var_name = name_tok.lexeme, .iter = lo, .body = body } }; }
// ---- expressions ---------------------------------------------------
fn binary(self: *ParserV2, op: TokenType, lhs: parser_mod.Expr, rhs: parser_mod.Expr) ParseError!parser_mod.Expr { const l = try self.allocator.create(parser_mod.Expr); const r = try self.allocator.create(parser_mod.Expr); l.* = lhs; r.* = rhs; return .{ .binary = .{ .op = op, .lhs = l, .rhs = r } }; }
fn unary(self: *ParserV2, op: TokenType, operand: parser_mod.Expr) ParseError!parser_mod.Expr { const operand_ptr = try self.allocator.create(parser_mod.Expr); operand_ptr.* = operand; return .{ .unary = .{ .op = op, .operand = operand_ptr } }; }
fn parseOr(self: *ParserV2) ParseError!parser_mod.Expr { var lhs = try self.parseAnd(); while (self.match(.kw_or)) lhs = try self.binary(.kw_or, lhs, try self.parseAnd()); return lhs; }
fn parseAnd(self: *ParserV2) ParseError!parser_mod.Expr { var lhs = try self.parseEquality(); while (self.match(.kw_and)) lhs = try self.binary(.kw_and, lhs, try self.parseEquality()); return lhs; }
fn parseEquality(self: *ParserV2) ParseError!parser_mod.Expr { var lhs = try self.parseComparison(); while (true) { const op: TokenType = if (self.match(.equal_equal)) .equal_equal else if (self.match(.not_equal)) .not_equal else break; lhs = try self.binary(op, lhs, try self.parseComparison()); } return lhs; }
fn parseComparison(self: *ParserV2) ParseError!parser_mod.Expr { var lhs = try self.parseTerm(); while (true) { const op: TokenType = if (self.match(.less)) .less else if (self.match(.less_equal)) .less_equal else if (self.match(.greater)) .greater else if (self.match(.greater_equal)) .greater_equal else break; lhs = try self.binary(op, lhs, try self.parseTerm()); } return lhs; }
fn parseTerm(self: *ParserV2) ParseError!parser_mod.Expr { var lhs = try self.parseFactor(); while (true) { const op: TokenType = if (self.match(.plus)) .plus else if (self.match(.minus)) .minus else break; lhs = try self.binary(op, lhs, try self.parseFactor()); } return lhs; }
fn parseFactor(self: *ParserV2) ParseError!parser_mod.Expr { var lhs = try self.parseUnary(); while (true) { const op: TokenType = if (self.match(.star)) .star else if (self.match(.slash)) .slash else if (self.match(.percent)) .percent else break; lhs = try self.binary(op, lhs, try self.parseUnary()); } return lhs; }
fn parseUnary(self: *ParserV2) ParseError!parser_mod.Expr { if (self.current.tag == .identifier) { const kw = self.current.lexeme; if (std.mem.eql(u8, kw, "match")) return self.fail(error.UnexpectedToken, "match expressions are stage 2", .{}); if (std.mem.eql(u8, kw, "fail")) return self.fail(error.UnexpectedToken, "fail is stage 2", .{}); if (std.mem.eql(u8, kw, "catch")) return self.fail(error.UnexpectedToken, "catch is stage 2", .{}); } if (self.match(.kw_not) or self.match(.bang)) { return self.unary(.kw_not, try self.parseUnary()); } if (self.match(.minus)) { return self.unary(.minus, try self.parseUnary()); } return self.parsePower(); }
fn parsePower(self: *ParserV2) ParseError!parser_mod.Expr { const base = try self.parsePostfix(); if (self.match(.star_star)) { const exp = try self.parseUnary(); // Lower x ** y to std.math.pow(x, y). const std_ident = parser_mod.Expr{ .identifier = try self.dupe("std") }; const math = parser_mod.Expr{ .field_access = .{ .object = blk: { const p = try self.allocator.create(parser_mod.Expr); p.* = std_ident; break :blk p; }, .field = "math", } }; const pow = parser_mod.Expr{ .field_access = .{ .object = blk: { const p = try self.allocator.create(parser_mod.Expr); p.* = math; break :blk p; }, .field = "pow", } }; const args = self.allocator.alloc(parser_mod.Expr, 2) catch return error.OutOfMemory; args[0] = base; args[1] = exp; const callee = try self.allocator.create(parser_mod.Expr); callee.* = pow; return .{ .call = .{ .callee = callee, .args = args } }; } return base; }
fn namespaceCall(self: *ParserV2, path: []const []const u8, args: []parser_mod.Expr) ParseError!parser_mod.Expr { var recv: parser_mod.Expr = .{ .identifier = try self.dupe("std") }; for (path) |seg| { const obj = try self.allocator.create(parser_mod.Expr); obj.* = recv; recv = .{ .field_access = .{ .object = obj, .field = seg } }; } const callee = try self.allocator.create(parser_mod.Expr); callee.* = recv; return .{ .call = .{ .callee = callee, .args = args } }; }
fn parsePostfix(self: *ParserV2) ParseError!parser_mod.Expr { var e = try self.parsePrimary(); while (true) { if (self.current.tag == .identifier and std.mem.eql(u8, self.current.lexeme, "catch")) { return self.fail(error.UnexpectedToken, "catch is stage 2", .{}); } if (self.match(.l_paren)) { var args: std.ArrayList(parser_mod.Expr) = .empty; while (!self.peekIs(.r_paren) and !self.peekIs(.eof)) { try args.append(self.allocator, try self.parseOr()); if (self.peekIs(.colon)) { return self.fail(error.UnexpectedToken, "named arguments are stage 2 (positional only)", .{}); } if (!self.match(.comma)) break; } _ = try self.expect(.r_paren); return self.maybeLowerPreludeCall(e, try args.toOwnedSlice(self.allocator)); } if (self.match(.l_bracket)) { const idx = try self.parseOr(); _ = try self.expect(.r_bracket); e = try self.indexAccess(e, idx); continue; } if (self.match(.period)) { const field = try self.expect(.identifier); const obj = try self.allocator.create(parser_mod.Expr); obj.* = e; e = .{ .field_access = .{ .object = obj, .field = field.lexeme } }; continue; } break; } return e; }
fn indexAccess(self: *ParserV2, obj: parser_mod.Expr, idx: parser_mod.Expr) ParseError!parser_mod.Expr { const o = try self.allocator.create(parser_mod.Expr); const i = try self.allocator.create(parser_mod.Expr); o.* = obj; i.* = idx; return .{ .index_access = .{ .object = o, .index = i } }; }
fn maybeLowerPreludeCall(self: *ParserV2, callee: parser_mod.Expr, args: []parser_mod.Expr) ParseError!parser_mod.Expr { const args_out = args; // ownership passes straight through const maybe_fname: ?[]const u8 = switch (callee) { .identifier => |id| id, else => null, }; const fname: []const u8 = maybe_fname orelse { const c = try self.allocator.create(parser_mod.Expr); c.* = callee; return .{ .call = .{ .callee = c, .args = args_out } }; };
if (std.mem.eql(u8, fname, "println") or std.mem.eql(u8, fname, "eprintln")) { if (args_out.len != 1) { return self.fail(error.UnexpectedToken, "{s} takes exactly one argument", .{fname}); } const fmt = parser_mod.Expr{ .string_lit = try self.dupe("{}\n") }; const tuple = parser_mod.Expr{ .array_lit = args_out }; var call_args = self.allocator.alloc(parser_mod.Expr, 2) catch return error.OutOfMemory; call_args[0] = fmt; call_args[1] = tuple; const target: []const []const u8 = if (std.mem.eql(u8, fname, "println")) &.{ "print" } else &.{ "stderr" }; return self.namespaceCall(target, call_args); } if (std.mem.eql(u8, fname, "assert")) return self.namespaceCall(&.{ "assert" }, args_out); if (std.mem.eql(u8, fname, "assert_eq")) return self.namespaceCall(&.{ "assert_eq" }, args_out); if (std.mem.eql(u8, fname, "panic")) return self.namespaceCall(&.{ "panic" }, args_out); if (std.mem.eql(u8, fname, "len")) return self.namespaceCall(&.{ "strings", "len" }, args_out); if (std.mem.eql(u8, fname, "range")) return self.namespaceCall(&.{ "collections", "range" }, args_out);
const c = try self.allocator.create(parser_mod.Expr); c.* = callee; return .{ .call = .{ .callee = c, .args = args_out } }; }
fn parsePrimary(self: *ParserV2) ParseError!parser_mod.Expr { const t = self.current; switch (t.tag) { .int_literal => { _ = self.advance(); const v = std.fmt.parseInt(i64, t.lexeme, 10) catch return self.fail(error.Overflow, "integer '{s}'", .{t.lexeme}); return .{ .int_lit = v }; }, .float_literal => { _ = self.advance(); const v = std.fmt.parseFloat(f64, t.lexeme) catch return self.fail(error.InvalidExpression, "float '{s}'", .{t.lexeme}); return .{ .float_lit = v }; }, .string_literal => { _ = self.advance(); return self.parseStringInterp(t.lexeme); }, .kw_true => { _ = self.advance(); return .{ .bool_lit = true }; }, .kw_false => { _ = self.advance(); return .{ .bool_lit = false }; }, .kw_null => { _ = self.advance(); return .null_lit; }, .identifier => { _ = self.advance(); return .{ .identifier = t.lexeme }; }, .type_int, .type_float, .type_str, .type_bool => { _ = self.advance(); return .{ .identifier = t.lexeme }; }, .l_paren => { _ = self.advance(); const e = try self.parseOr(); _ = try self.expect(.r_paren); return e; }, .l_bracket => { _ = self.advance(); var items: std.ArrayList(parser_mod.Expr) = .empty; while (!self.peekIs(.r_bracket) and !self.peekIs(.eof)) { try items.append(self.allocator, try self.parseOr()); if (!self.match(.comma)) break; } _ = try self.expect(.r_bracket); return .{ .array_lit = try items.toOwnedSlice(self.allocator) }; }, .l_brace => { _ = self.advance(); var fields: std.ArrayList(parser_mod.Expr.StructFieldInit) = .empty; while (!self.peekIs(.r_brace) and !self.peekIs(.eof)) { if (self.peekIs(.string_literal)) { const key_tok = self.current; _ = self.advance(); _ = try self.expect(.colon); const value = try self.parseOr(); const ks = try unescapeBody(self.allocator, key_tok.lexeme[1 .. key_tok.lexeme.len - 1]); try fields.append(self.allocator, .{ .name = self.dupe("") catch return error.OutOfMemory, .explicit_type = null, .value = value, .key_expr = .{ .string_lit = ks }, }); if (!self.match(.comma)) break; continue; } const key_tok = try self.expect(.identifier); _ = try self.expect(.colon); const value = try self.parseOr(); try fields.append(self.allocator, .{ .name = key_tok.lexeme, .explicit_type = null, .value = value }); if (!self.match(.comma)) break; } _ = try self.expect(.r_brace); return .{ .struct_lit = try fields.toOwnedSlice(self.allocator) }; }, else => return self.fail(error.UnexpectedToken, "unexpected '{s}'", .{t.lexeme}), } }
fn parseStringInterp(self: *ParserV2, raw: []const u8) ParseError!parser_mod.Expr { const body = raw[1 .. raw.len - 1]; if (std.mem.indexOfScalar(u8, body, '{') == null and std.mem.indexOfScalar(u8, body, '}') == null) { return .{ .string_lit = try unescapeBody(self.allocator, body) }; } var acc: ?parser_mod.Expr = null; var i: usize = 0; var buf: std.ArrayList(u8) = .empty; while (i < body.len) { const c = body[i]; if (c == '{' and i + 1 < body.len and body[i + 1] == '{') { try buf.append(self.allocator, '{'); i += 2; continue; } if (c == '}' and i + 1 < body.len and body[i + 1] == '}') { try buf.append(self.allocator, '}'); i += 2; continue; } if (c == '}') { return self.fail(error.UnexpectedToken, "unmatched '}}' in string", .{}); } if (c == '{') { if (buf.items.len > 0) { acc = try concatWith(self.allocator, acc, .{ .string_lit = try unescapeBody(self.allocator, buf.items) }); buf.clearRetainingCapacity(); } const start = i + 1; var depth: usize = 1; var j = start; while (j < body.len and depth > 0) { const d = body[j]; if (d == '{') depth += 1 else if (d == '}') depth -= 1; if (depth == 0) break; j += 1; } if (depth != 0) return self.fail(error.UnexpectedToken, "unterminated '{{' interpolation", .{}); const seg = body[start..j]; i = j + 1; var sub = ParserV2.init(self.allocator, seg); const e = sub.parseOr() catch |e2| return e2; if (sub.current.tag != .eof) { return self.fail(error.UnexpectedToken, "stray expression in interpolation", .{}); } const args = self.allocator.alloc(parser_mod.Expr, 1) catch return error.OutOfMemory; args[0] = e; acc = try concatWith(self.allocator, acc, .{ .call_directive = .{ .name = try self.dupe("str"), .args = args } }); continue; } try buf.append(self.allocator, c); i += 1; } if (buf.items.len > 0) { acc = try concatWith(self.allocator, acc, .{ .string_lit = try unescapeBody(self.allocator, buf.items) }); } if (acc) |a| return a; return .{ .string_lit = try self.dupe("") }; }};
fn concatWith(allocator: std.mem.Allocator, lhs: ?parser_mod.Expr, rhs: parser_mod.Expr) ParseError!parser_mod.Expr { if (lhs) |l| { const lp = try allocator.create(parser_mod.Expr); const rp = try allocator.create(parser_mod.Expr); lp.* = l; rp.* = rhs; return .{ .binary = .{ .op = .plus, .lhs = lp, .rhs = rp } }; } return rhs;}
/// Clone an expression tree into a fresh tree with independent ownership./// Identifier/lexeme slices are borrowed from source text (the lexer owns/// the buffer); everything else allocates its own copy.pub fn cloneExpr(allocator: std.mem.Allocator, e: *const parser_mod.Expr) ParseError!*parser_mod.Expr { const out = try allocator.create(parser_mod.Expr); out.* = switch (e.*) { .int_lit, .float_lit, .bool_lit, .enum_lit, .identifier, .null_lit => e.*, .string_lit => |s| .{ .string_lit = try allocator.dupe(u8, s) }, .array_lit => |items| blk: { const copy = try allocator.alloc(parser_mod.Expr, items.len); for (items, 0..) |*item, i| { const cloned = try cloneExpr(allocator, item); copy[i] = cloned.*; allocator.destroy(cloned); } break :blk .{ .array_lit = copy }; }, .struct_lit => |fields| blk: { const copy = try allocator.alloc(parser_mod.Expr.StructFieldInit, fields.len); for (fields, 0..) |*f, i| { var nf: parser_mod.Expr.StructFieldInit = .{ .name = f.name, .explicit_type = null, .value = .null_lit, }; const cloned_val = try cloneExpr(allocator, &f.value); nf.value = cloned_val.*; allocator.destroy(cloned_val); if (f.key_expr) |ke| { const cloned_key = try cloneExpr(allocator, &ke); nf.key_expr = cloned_key.*; allocator.destroy(cloned_key); } copy[i] = nf; } break :blk .{ .struct_lit = copy }; }, .binary => |b| .{ .binary = .{ .op = b.op, .lhs = try cloneExpr(allocator, b.lhs), .rhs = try cloneExpr(allocator, b.rhs) } }, .unary => |u| .{ .unary = .{ .op = u.op, .operand = try cloneExpr(allocator, u.operand) } }, .field_access => |fa| .{ .field_access = .{ .object = try cloneExpr(allocator, fa.object), .field = fa.field } }, .index_access => |ia| .{ .index_access = .{ .object = try cloneExpr(allocator, ia.object), .index = try cloneExpr(allocator, ia.index) } }, .call => |c| blk: { const callee = try cloneExpr(allocator, c.callee); const args = try allocator.alloc(parser_mod.Expr, c.args.len); for (c.args, 0..) |*a, i| { const cloned = try cloneExpr(allocator, a); args[i] = cloned.*; allocator.destroy(cloned); } break :blk .{ .call = .{ .callee = callee, .args = args } }; }, .call_directive => |cd| blk: { const args = try allocator.alloc(parser_mod.Expr, cd.args.len); for (cd.args, 0..) |*a, i| { const cloned = try cloneExpr(allocator, a); args[i] = cloned.*; allocator.destroy(cloned); } break :blk .{ .call_directive = .{ .name = cd.name, .args = args } }; }, else => return error.UnexpectedToken, }; return out;}
fn unescapeBody(allocator: std.mem.Allocator, body: []const u8) ParseError![]const u8 { if (std.mem.indexOfScalar(u8, body, '\\') == null) { return allocator.dupe(u8, body) catch error.OutOfMemory; } var out: std.ArrayList(u8) = .empty; var i: usize = 0; while (i < body.len) { const c = body[i]; if (c != '\\') { try out.append(allocator, c); i += 1; continue; } if (i + 1 >= body.len) break; switch (body[i + 1]) { 'n' => try out.append(allocator, '\n'), 't' => try out.append(allocator, '\t'), 'r' => try out.append(allocator, '\r'), '\\' => try out.append(allocator, '\\'), '"' => try out.append(allocator, '"'), else => { try out.append(allocator, '\\'); try out.append(allocator, body[i + 1]); }, } i += 2; } return out.toOwnedSlice(allocator) catch error.OutOfMemory;}