const std = @import("std"); const logger = @import("logger.zig"); const tables = @import("js_lexer_tables.zig"); const alloc = @import("alloc.zig"); const build_options = @import("build_options"); const js_ast = @import("js_ast.zig"); usingnamespace @import("ast/base.zig"); usingnamespace @import("strings.zig"); const _f = @import("./test/fixtures.zig"); const unicode = std.unicode; const Source = logger.Source; pub const T = tables.T; pub const CodePoint = tables.CodePoint; pub const Keywords = tables.Keywords; pub const tokenToString = tables.tokenToString; pub const jsxEntity = tables.jsxEntity; pub const StrictModeReservedWords = tables.StrictModeReservedWords; // TODO: JSON const IS_JSON_FILE = false; pub const Lexer = struct { // pub const Error = error{ // UnexpectedToken, // EndOfFile, // }; // err: ?Lexer.Error, log: logger.Log, source: logger.Source, current: usize = 0, start: usize = 0, end: usize = 0, approximate_newline_count: i32 = 0, legacy_octal_loc: logger.Loc = logger.Loc.Empty, previous_backslash_quote_in_jsx: logger.Range = logger.Range.None, token: T = T.t_end_of_file, has_newline_before: bool = false, has_pure_comment_before: bool = false, preserve_all_comments_before: bool = false, is_legacy_octal_literal: bool = false, comments_to_preserve_before: ?[]js_ast.G.Comment = null, all_original_comments: ?[]js_ast.G.Comment = null, code_point: CodePoint = -1, string_literal: JavascriptString, identifier: []const u8 = "", jsx_factory_pragma_comment: ?js_ast.Span = null, jsx_fragment_pragma_comment: ?js_ast.Span = null, source_mapping_url: ?js_ast.Span = null, number: f64 = 0.0, rescan_close_brace_as_template_token: bool = false, for_global_name: bool = false, prev_error_loc: logger.Loc = logger.Loc.Empty, allocator: *std.mem.Allocator, pub fn loc(self: *Lexer) logger.Loc { return logger.usize2Loc(self.start); } fn nextCodepointSlice(it: *Lexer) callconv(.Inline) ?[]const u8 { if (it.current >= it.source.contents.len) { return null; } const cp_len = unicode.utf8ByteSequenceLength(it.source.contents[it.current]) catch unreachable; it.end = it.current; it.current += cp_len; return it.source.contents[it.current - cp_len .. it.current]; } pub fn syntaxError(self: *Lexer) void { self.addError(self.start, "Syntax Error!!", .{}, true); } pub fn addDefaultError(self: *Lexer, msg: []const u8) void { self.addError(self.start, "{s}", .{msg}, true); } pub fn addError(self: *Lexer, _loc: usize, comptime format: []const u8, args: anytype, panic: bool) void { var __loc = logger.usize2Loc(_loc); if (__loc.eql(self.prev_error_loc)) { return; } const errorMessage = std.fmt.allocPrint(self.allocator, format, args) catch unreachable; self.log.addError(self.source, __loc, errorMessage) catch unreachable; self.prev_error_loc = __loc; // if (panic) { self.doPanic(errorMessage); // } } pub fn addRangeError(self: *Lexer, r: logger.Range, comptime format: []const u8, args: anytype, panic: bool) void { if (self.prev_error_loc.eql(r.loc)) { return; } const errorMessage = std.fmt.allocPrint(self.allocator, format, args) catch unreachable; var msg = self.log.addRangeError(self.source, r, errorMessage); self.prev_error_loc = r.loc; if (panic) { self.doPanic(errorMessage); } } fn doPanic(self: *Lexer, content: []const u8) void { std.debug.panic("{s}", .{content}); } pub fn codePointEql(self: *Lexer, a: u8) bool { return @intCast(CodePoint, a) == self.code_point; } fn nextCodepoint(it: *Lexer) callconv(.Inline) CodePoint { const slice = it.nextCodepointSlice() orelse return @as(CodePoint, -1); switch (slice.len) { 1 => return @as(CodePoint, slice[0]), 2 => return @as(CodePoint, unicode.utf8Decode2(slice) catch unreachable), 3 => return @as(CodePoint, unicode.utf8Decode3(slice) catch unreachable), 4 => return @as(CodePoint, unicode.utf8Decode4(slice) catch unreachable), else => unreachable, } } /// Look ahead at the next n codepoints without advancing the iterator. /// If fewer than n codepoints are available, then return the remainder of the string. fn peek(it: *Lexer, n: usize) []const u8 { const original_i = it.current; defer it.current = original_i; var end_ix = original_i; var found: usize = 0; while (found < n) : (found += 1) { const next_codepoint = it.nextCodepointSlice() orelse return it.source.contents[original_i..]; end_ix += next_codepoint.len; } return it.source.contents[original_i..end_ix]; } fn parseStringLiteral(lexer: *Lexer) void { var quote: CodePoint = lexer.code_point; var needs_slow_path = false; var suffixLen: usize = 1; if (quote != '`') { lexer.token = T.t_string_literal; } else if (lexer.rescan_close_brace_as_template_token) { lexer.token = T.t_template_tail; } else { lexer.token = T.t_no_substitution_template_literal; } lexer.step(); stringLiteral: while (true) { switch (lexer.code_point) { '\\' => { needs_slow_path = true; lexer.step(); // Handle Windows CRLF if (lexer.code_point == '\r' and IS_JSON_FILE) { lexer.step(); if (lexer.code_point == '\n') { lexer.step(); } continue :stringLiteral; } }, // This indicates the end of the file -1 => { lexer.addDefaultError("Unterminated string literal"); }, '\r' => { if (quote != '`') { lexer.addDefaultError("Unterminated string literal"); } // Template literals require newline normalization needs_slow_path = true; }, '\n' => { if (quote != '`') { lexer.addDefaultError("Unterminated string literal"); } }, '$' => { if (quote == '`') { lexer.step(); if (lexer.code_point == '{') { suffixLen = 2; lexer.step(); if (lexer.rescan_close_brace_as_template_token) { lexer.token = T.t_template_middle; } else { lexer.token = T.t_template_head; } break :stringLiteral; } continue :stringLiteral; } }, else => { if (quote == lexer.code_point) { lexer.step(); break :stringLiteral; } // Non-ASCII strings need the slow path if (lexer.code_point >= 0x80) { needs_slow_path = true; } else if (IS_JSON_FILE and lexer.code_point < 0x20) { lexer.syntaxError(); } }, } lexer.step(); } const text = lexer.source.contents[lexer.start + 1 .. lexer.end - suffixLen]; // TODO: actually implement proper utf16 lexer.string_literal = lexer.allocator.alloc(u16, text.len) catch unreachable; var i: usize = 0; for (text) |byte| { lexer.string_literal[i] = byte; i += 1; } // for (text) // // if (needs_slow_path) { // // // Slow path // // // lexer.string_literal = lexer.(lexer.start + 1, text); // // } else { // // // Fast path // // } } fn step(lexer: *Lexer) void { lexer.code_point = lexer.nextCodepoint(); // Track the approximate number of newlines in the file so we can preallocate // the line offset table in the printer for source maps. The line offset table // is the #1 highest allocation in the heap profile, so this is worth doing. // This count is approximate because it handles "\n" and "\r\n" (the common // cases) but not "\r" or "\u2028" or "\u2029". Getting this wrong is harmless // because it's only a preallocation. The array will just grow if it's too small. if (lexer.code_point == '\n') { lexer.approximate_newline_count += 1; } } pub fn expect(self: *Lexer, token: T) void { if (self.token != token) { self.expected(token); } self.next(); } pub fn expectOrInsertSemicolon(lexer: *Lexer) void { if (lexer.token == T.t_semicolon or (!lexer.has_newline_before and lexer.token != T.t_close_brace and lexer.token != T.t_end_of_file)) { lexer.expect(T.t_semicolon); } } pub fn addUnsupportedSyntaxError(self: *Lexer, msg: []const u8) void { self.addError(self.end, "Unsupported syntax: {s}", .{msg}, true); } pub fn scanIdentifierWithEscapes(self: *Lexer) void { self.addUnsupportedSyntaxError("escape sequence"); return; } pub fn debugInfo(self: *Lexer) void { if (self.log.errors > 0) { const stderr = std.io.getStdErr().writer(); self.log.print(stderr) catch unreachable; } else { if (self.token == T.t_identifier or self.token == T.t_string_literal) { std.debug.print(" {s} ", .{self.raw()}); } else { std.debug.print(" <{s}> ", .{tokenToString.get(self.token)}); } } } pub fn expectContextualKeyword(self: *Lexer, keyword: string) void { if (!self.isContextualKeyword(keyword)) { self.addError(self.start, "\"{s}\"", .{keyword}, true); } self.next(); } pub fn next(lexer: *Lexer) void { lexer.has_newline_before = lexer.end == 0; lex: while (lexer.log.errors == 0) { lexer.start = lexer.end; lexer.token = T.t_end_of_file; switch (lexer.code_point) { -1 => { lexer.token = T.t_end_of_file; break :lex; }, '#' => { if (lexer.start == 0 and lexer.source.contents[1] == '!') { lexer.addUnsupportedSyntaxError("#!hashbang is not supported yet."); return; } lexer.step(); if (!isIdentifierStart(lexer.code_point)) { lexer.syntaxError(); } lexer.step(); if (isIdentifierStart(lexer.code_point)) { lexer.step(); while (isIdentifierContinue(lexer.code_point)) { lexer.step(); } if (lexer.code_point == '\\') { lexer.scanIdentifierWithEscapes(); lexer.token = T.t_private_identifier; // lexer.Identifier, lexer.Token = lexer.scanIdentifierWithEscapes(normalIdentifier); } else { lexer.token = T.t_private_identifier; lexer.identifier = lexer.raw(); } break; } }, '\r', '\n', 0x2028, 0x2029 => { lexer.step(); lexer.has_newline_before = true; continue; }, '\t', ' ' => { lexer.step(); continue; }, '(' => { lexer.step(); lexer.token = T.t_open_paren; }, ')' => { lexer.step(); lexer.token = T.t_close_paren; }, '[' => { lexer.step(); lexer.token = T.t_open_bracket; }, ']' => { lexer.step(); lexer.token = T.t_close_bracket; }, '{' => { lexer.step(); lexer.token = T.t_open_brace; }, '}' => { lexer.step(); lexer.token = T.t_close_brace; }, ',' => { lexer.step(); lexer.token = T.t_comma; }, ':' => { lexer.step(); lexer.token = T.t_colon; }, ';' => { lexer.step(); lexer.token = T.t_semicolon; }, '@' => { lexer.step(); lexer.token = T.t_at; }, '~' => { lexer.step(); lexer.token = T.t_tilde; }, '?' => { // '?' or '?.' or '??' or '??=' lexer.step(); switch (lexer.code_point) { '?' => { lexer.step(); switch (lexer.code_point) { '=' => { lexer.step(); lexer.token = T.t_question_question_equals; }, else => { lexer.token = T.t_question_question; }, } }, '.' => { lexer.token = T.t_question; const current = lexer.current; const contents = lexer.source.contents; // Lookahead to disambiguate with 'a?.1:b' if (current < contents.len) { const c = contents[current]; if (c < '0' or c > '9') { lexer.step(); lexer.token = T.t_question_dot; } } }, else => { lexer.token = T.t_question; }, } }, '%' => { // '%' or '%=' lexer.step(); switch (lexer.code_point) { '=' => { lexer.step(); lexer.token = T.t_percent_equals; }, else => { lexer.token = T.t_percent; }, } }, '&' => { // '&' or '&=' or '&&' or '&&=' lexer.step(); switch (lexer.code_point) { '=' => { lexer.step(); lexer.token = T.t_ampersand_equals; }, '&' => { lexer.step(); switch (lexer.code_point) { '=' => { lexer.step(); lexer.token = T.t_ampersand_ampersand_equals; }, else => { lexer.token = T.t_ampersand_ampersand; }, } }, else => { lexer.token = T.t_ampersand; }, } }, '|' => { // '|' or '|=' or '||' or '||=' lexer.step(); switch (lexer.code_point) { '=' => { lexer.step(); lexer.token = T.t_bar_equals; }, '|' => { lexer.step(); switch (lexer.code_point) { '=' => { lexer.step(); lexer.token = T.t_bar_bar_equals; }, else => { lexer.token = T.t_bar_bar; }, } }, else => { lexer.token = T.t_bar; }, } }, '^' => { // '^' or '^=' lexer.step(); switch (lexer.code_point) { '=' => { lexer.step(); lexer.token = T.t_caret_equals; }, else => { lexer.token = T.t_caret; }, } }, '+' => { // '+' or '+=' or '++' lexer.step(); switch (lexer.code_point) { '=' => { lexer.step(); lexer.token = T.t_plus_equals; }, '+' => { lexer.step(); lexer.token = T.t_plus_plus; }, else => { lexer.token = T.t_plus; }, } }, '=' => { // '=' or '=>' or '==' or '===' lexer.step(); switch (lexer.code_point) { '>' => { lexer.step(); lexer.token = T.t_equals_greater_than; }, '=' => { lexer.step(); switch (lexer.code_point) { '=' => { lexer.step(); lexer.token = T.t_equals_equals_equals; }, else => { lexer.token = T.t_equals_equals; }, } }, else => { lexer.token = T.t_equals; }, } }, '<' => { // '<' or '<<' or '<=' or '<<=' or '