├── .gitignore ├── LICENSE ├── README.md ├── build.zig └── src ├── chunk.zig ├── common.zig ├── compiler.zig ├── debug.zig ├── main.zig ├── memory.zig ├── object.zig ├── scanner.zig ├── table.zig ├── tests.zig ├── value.zig └── vm.zig /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | zig-cache 3 | zig-out 4 | scripts/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ZLox 2 | 3 | A stack-based bytecode Virtual Machine for the [Lox Programming Language](https://craftinginterpreters.com/the-lox-language.html) written in [Zig](https://ziglang.org/). 4 | 5 | ## Run 6 | 7 | Start REPL: 8 | ```bash 9 | $ zig build run 10 | > print 1+1; 11 | 2 12 | > 13 | ``` 14 | 15 | ## Test 16 | 17 | ```bash 18 | $ zig build test 19 | All tests passed. 20 | ``` 21 | 22 | ## Troubleshoot 23 | 24 | Enable tracing: 25 | ```bash 26 | $ zig build -Denable-tracing 27 | ``` 28 | 29 | Enable disassembly: 30 | ```bash 31 | $ zig build -Denable-dump 32 | ``` 33 | 34 | For more build options use `zig build --help` -------------------------------------------------------------------------------- /build.zig: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | 3 | pub fn build(b: *std.build.Builder) void { 4 | // Standard target options allows the person running `zig build` to choose 5 | // what target to build for. Here we do not override the defaults, which 6 | // means any target is allowed, and the default is native. Other options 7 | // for restricting supported target set are available. 8 | const target = b.standardTargetOptions(.{}); 9 | 10 | // Standard release options allow the person running `zig build` to select 11 | // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. 12 | const mode = b.standardReleaseOptions(); 13 | 14 | var options = b.addOptions(); 15 | options.addOption(bool, "trace_enable", b.option(bool, "enable-tracing", "enables Lox VM tracing.") orelse false); 16 | options.addOption(bool, "dump_code", b.option(bool, "enable-dump", "enables bytecode printing after compilation.") orelse false); 17 | options.addOption(bool, "stress_gc", b.option(bool, "enable-gc-stress", "enables stressing the garbage collector.") orelse false); 18 | options.addOption(bool, "log_gc", b.option(bool, "enable-log-gc", "enables logging gc operation.") orelse false); 19 | options.addOption(bool, "nan_boxing", b.option(bool, "enable-nan-boxing", "enables NaN boxing") orelse false); 20 | const exe = b.addExecutable("zlox", "src/main.zig"); 21 | exe.setTarget(target); 22 | exe.setBuildMode(mode); 23 | exe.addOptions("build_options", options); 24 | exe.linkLibC(); 25 | exe.install(); 26 | 27 | const run_cmd = exe.run(); 28 | run_cmd.step.dependOn(b.getInstallStep()); 29 | if (b.args) |args| { 30 | run_cmd.addArgs(args); 31 | } 32 | 33 | const run_step = b.step("run", "Run the app"); 34 | run_step.dependOn(&run_cmd.step); 35 | const exe_tests = b.addTest("src/tests.zig"); 36 | exe_tests.setTarget(target); 37 | exe_tests.setBuildMode(mode); 38 | exe_tests.addOptions("build_options", options); 39 | 40 | const test_step = b.step("test", "Run unit tests"); 41 | test_step.dependOn(&exe_tests.step); 42 | } 43 | -------------------------------------------------------------------------------- /src/chunk.zig: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | const memory = @import("./memory.zig"); 3 | const common = @import("./common.zig"); 4 | const ValueArray = @import("./value.zig").ValueArray; 5 | const Value = @import("./value.zig").Value; 6 | 7 | pub const OpCode = enum(u8) { 8 | op_constant, // arg 1: constant index 9 | op_nil, 10 | op_true, 11 | op_false, 12 | op_pop, 13 | op_get_local, 14 | op_get_global, 15 | op_get_upvalue, 16 | op_define_global, 17 | op_set_local, 18 | op_set_global, 19 | op_set_upvalue, 20 | op_get_property, 21 | op_set_property, 22 | op_equal, 23 | op_greater, 24 | op_less, 25 | op_add, 26 | op_subtract, 27 | op_multiply, 28 | op_divide, 29 | op_not, 30 | op_negate, 31 | op_print, 32 | op_jump, 33 | op_jump_if_false, 34 | op_loop, 35 | op_call, 36 | op_invoke, 37 | op_super_invoke, 38 | op_closure, 39 | op_close_upvalue, 40 | op_return, 41 | op_class, 42 | op_inherit, 43 | op_get_super, 44 | op_method, 45 | }; 46 | 47 | pub const Chunk = struct { 48 | allocator: std.mem.Allocator, 49 | count: u32 = 0, 50 | capacity: u32 = 0, 51 | code: [*]u8 = undefined, 52 | constants: ValueArray, 53 | lines: [*]u32 = undefined, 54 | 55 | pub fn init(allocator: std.mem.Allocator) Chunk { 56 | return .{ 57 | .allocator = allocator, 58 | .constants = ValueArray.init(allocator), 59 | }; 60 | } 61 | 62 | pub fn writeChunk(self: *Chunk, byte: u8, line: u32) void { 63 | if (self.capacity <= self.count) { 64 | const old_c = self.capacity; 65 | self.capacity = common.growCapacity(old_c); 66 | self.code = memory.growArray(u8, self.code, old_c, self.capacity); 67 | self.lines = memory.growArray(u32, self.lines, old_c, self.capacity); 68 | } 69 | self.code[self.count] = byte; 70 | self.lines[self.count] = line; 71 | self.count += 1; 72 | } 73 | 74 | pub fn addConstant(self: *Chunk, value: Value) u32 { 75 | memory.vm.push(value); 76 | self.constants.writeValueArray(value); 77 | _ = memory.vm.pop(); 78 | return @intCast(u32, self.constants.count - 1); 79 | } 80 | 81 | pub fn freeChunk(self: *Chunk) void { 82 | memory.freeArray(u8, self.code, self.capacity); 83 | memory.freeArray(u32, self.lines, self.capacity); 84 | self.count = 0; 85 | self.capacity = 0; 86 | self.code = undefined; 87 | self.constants.freeValueArray(); 88 | } 89 | }; 90 | -------------------------------------------------------------------------------- /src/common.zig: -------------------------------------------------------------------------------- 1 | const Value = @import("./value.zig").Value; 2 | const std = @import("std"); 3 | const builtin = @import("builtin"); 4 | pub const alloc = if (builtin.mode == std.builtin.Mode.Debug) std.testing.allocator else std.heap.c_allocator; 5 | pub const trace_enabled = @import("build_options").trace_enable; 6 | pub const dump_enabled = @import("build_options").dump_code; 7 | pub const stress_gc = @import("build_options").stress_gc; 8 | pub const log_gc = @import("build_options").log_gc; 9 | pub const nan_boxing = @import("build_options").nan_boxing; 10 | pub const gc_heap_growth_factor = 2; 11 | pub const stdout = if (builtin.is_test) buffer_stream.writer() else std.io.getStdOut().writer(); 12 | pub const stderr = std.io.getStdErr().writer(); 13 | 14 | pub var buffer: if (builtin.is_test) [1 << 10 << 10]u8 else [0]u8 = if (builtin.is_test) .{0} ** (1 << 10 << 10) else .{}; 15 | pub var buffer_stream = if (builtin.is_test) std.io.fixedBufferStream(buffer[0..]) else @compileError("only used for testing"); 16 | 17 | pub fn add(a: f64, b: f64) Value { 18 | return Value.Number(a + b); 19 | } 20 | 21 | pub fn sub(a: f64, b: f64) Value { 22 | return Value.Number(a - b); 23 | } 24 | 25 | pub fn mul(a: f64, b: f64) Value { 26 | return Value.Number(a * b); 27 | } 28 | 29 | pub fn div(a: f64, b: f64) Value { 30 | return Value.Number(a / b); 31 | } 32 | 33 | pub fn greater(a: f64, b: f64) Value { 34 | return Value.Boolean(a > b); 35 | } 36 | 37 | pub fn less(a: f64, b: f64) Value { 38 | return Value.Boolean(a < b); 39 | } 40 | 41 | pub inline fn growCapacity(old_c: anytype) @TypeOf(old_c) { 42 | return if (old_c < 8) 8 else old_c * 2; 43 | } 44 | -------------------------------------------------------------------------------- /src/compiler.zig: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | const scanner = @import("./scanner.zig"); 3 | const memory = @import("./memory.zig"); 4 | const common = @import("./common.zig"); 5 | const debug = @import("./debug.zig"); 6 | const object = @import("./object.zig"); 7 | const Chunk = @import("./chunk.zig").Chunk; 8 | const Value = @import("./value.zig").Value; 9 | const OpCode = @import("./chunk.zig").OpCode; 10 | const TokenType = scanner.TokenType; 11 | const Token = scanner.Token; 12 | const ObjFunction = object.ObjFunction; 13 | const Obj = object.Obj; 14 | 15 | const stdout = common.stdout; 16 | const stderr = common.stderr; 17 | 18 | const Parser = struct { 19 | current: Token = undefined, 20 | previous: Token = undefined, 21 | had_error: bool = false, 22 | panic_mode: bool = false, 23 | }; 24 | 25 | const Precedence = enum(u8) { 26 | prec_none, 27 | prec_assignment, 28 | prec_or, 29 | prec_and, 30 | prec_equality, 31 | prec_comparison, 32 | prec_term, 33 | prec_factor, 34 | prec_unary, 35 | prec_call, 36 | prec_primary, 37 | }; 38 | 39 | const ParseFn = fn (can_assign: bool) void; 40 | 41 | const ParseRule = struct { 42 | prefix: ?ParseFn, 43 | infix: ?ParseFn, 44 | precedence: Precedence, 45 | }; 46 | 47 | const Compiler = struct { 48 | enclosing: ?*Compiler, 49 | function: *ObjFunction, 50 | fun_t: FunctionType, 51 | locals: [256]Local = undefined, 52 | local_count: u8 = 0, 53 | scope_depth: usize = 0, 54 | upvalues: [256]Upvalue = undefined, 55 | 56 | fn init(self: *Compiler, fun_t: FunctionType) void { 57 | var c: Compiler = .{ .enclosing = current, .fun_t = fun_t, .function = object.newFunction() }; 58 | self.* = c; 59 | current = self; 60 | if (fun_t != .type_script) { 61 | c.function.name = object.copyString(p.previous.start, p.previous.length).asString(); 62 | } 63 | var local = &self.locals[self.local_count]; 64 | local.depth = 0; 65 | local.is_captured = false; 66 | if (fun_t != .type_function) { 67 | local.name.start = "this"; 68 | local.name.length = 4; 69 | } else { 70 | local.name.start = ""; 71 | local.name.length = 0; 72 | } 73 | self.local_count += 1; 74 | } 75 | }; 76 | 77 | const ClassCompiler = struct { 78 | enclosing: ?*ClassCompiler, 79 | has_superclass: bool, 80 | }; 81 | 82 | const Local = struct { 83 | name: Token, 84 | depth: isize, 85 | is_captured: bool, 86 | }; 87 | 88 | const Upvalue = struct { 89 | index: u8, 90 | is_local: bool, 91 | }; 92 | 93 | const FunctionType = enum { type_function, type_script, type_method, type_initializer }; 94 | 95 | const rules: [@enumToInt(TokenType.lox_eof) + 1]ParseRule = blk: { 96 | comptime var tmp: [@enumToInt(TokenType.lox_eof) + 1]ParseRule = .{.{ .prefix = null, .infix = null, .precedence = .prec_none }} ** (@enumToInt(TokenType.lox_eof) + 1); 97 | tmp[@enumToInt(TokenType.left_paren)] = .{ .prefix = grouping, .infix = call, .precedence = .prec_call }; 98 | tmp[@enumToInt(TokenType.minus)] = .{ .prefix = unary, .infix = binary, .precedence = .prec_term }; 99 | tmp[@enumToInt(TokenType.bang)] = .{ .prefix = unary, .infix = null, .precedence = .prec_none }; 100 | tmp[@enumToInt(TokenType.bang_equal)] = .{ .prefix = null, .infix = binary, .precedence = .prec_equality }; 101 | tmp[@enumToInt(TokenType.equal_equal)] = .{ .prefix = null, .infix = binary, .precedence = .prec_equality }; 102 | tmp[@enumToInt(TokenType.greater)] = .{ .prefix = null, .infix = binary, .precedence = .prec_comparison }; 103 | tmp[@enumToInt(TokenType.greater_equal)] = .{ .prefix = null, .infix = binary, .precedence = .prec_comparison }; 104 | tmp[@enumToInt(TokenType.less)] = .{ .prefix = null, .infix = binary, .precedence = .prec_comparison }; 105 | tmp[@enumToInt(TokenType.less_equal)] = .{ .prefix = null, .infix = binary, .precedence = .prec_comparison }; 106 | tmp[@enumToInt(TokenType.plus)] = .{ .prefix = null, .infix = binary, .precedence = .prec_term }; 107 | tmp[@enumToInt(TokenType.slash)] = .{ .prefix = null, .infix = binary, .precedence = .prec_factor }; 108 | tmp[@enumToInt(TokenType.star)] = .{ .prefix = null, .infix = binary, .precedence = .prec_factor }; 109 | tmp[@enumToInt(TokenType.number)] = .{ .prefix = number, .infix = null, .precedence = .prec_none }; 110 | tmp[@enumToInt(TokenType.lox_false)] = .{ .prefix = literal, .infix = null, .precedence = .prec_none }; 111 | tmp[@enumToInt(TokenType.lox_true)] = .{ .prefix = literal, .infix = null, .precedence = .prec_none }; 112 | tmp[@enumToInt(TokenType.lox_nil)] = .{ .prefix = literal, .infix = null, .precedence = .prec_none }; 113 | tmp[@enumToInt(TokenType.string)] = .{ .prefix = string, .infix = null, .precedence = .prec_none }; 114 | tmp[@enumToInt(TokenType.identifier)] = .{ .prefix = variable, .infix = null, .precedence = .prec_none }; 115 | tmp[@enumToInt(TokenType.lox_and)] = .{ .prefix = null, .infix = and_, .precedence = .prec_and }; 116 | tmp[@enumToInt(TokenType.lox_or)] = .{ .prefix = null, .infix = or_, .precedence = .prec_or }; 117 | tmp[@enumToInt(TokenType.dot)] = .{ .prefix = null, .infix = dot, .precedence = .prec_call }; 118 | tmp[@enumToInt(TokenType.lox_this)] = .{ .prefix = this_, .infix = null, .precedence = .prec_none }; 119 | tmp[@enumToInt(TokenType.lox_super)] = .{ .prefix = super_, .infix = null, .precedence = .prec_none }; 120 | break :blk tmp; 121 | }; 122 | 123 | var p: Parser = undefined; 124 | var current: ?*Compiler = null; 125 | var current_class: ?*ClassCompiler = null; 126 | var s: scanner.Scanner = undefined; 127 | 128 | fn getRule(t: TokenType) *const ParseRule { 129 | return &rules[@enumToInt(t)]; 130 | } 131 | 132 | fn currentChunk() *Chunk { 133 | return current.?.function.chunk(); 134 | } 135 | 136 | pub fn compile(source: [:0]const u8) ?*ObjFunction { 137 | p = Parser{}; 138 | s = scanner.Scanner.init(source); 139 | var compiler: Compiler = undefined; 140 | Compiler.init(&compiler, .type_script); 141 | advance(); 142 | while (!match(.lox_eof)) declaration(); 143 | const fun = endCompiler(); 144 | return if (p.had_error) null else fun; 145 | } 146 | 147 | pub fn markCompilerRoots() void { 148 | var compiler: ?*Compiler = current; 149 | while (compiler) |comp| : (compiler = comp.enclosing) { 150 | memory.markObject(@ptrCast(*Obj, comp.function)); 151 | } 152 | } 153 | 154 | fn synchronize() void { 155 | p.panic_mode = false; 156 | 157 | while (p.current.t != .lox_eof) { 158 | if (p.previous.t == .semicolon) return; 159 | switch (p.current.t) { 160 | .lox_class, .lox_fun, .lox_var, .lox_for, .lox_if, .lox_while, .lox_print, .lox_return => return, 161 | else => {}, 162 | } 163 | advance(); 164 | } 165 | } 166 | 167 | fn expression() void { 168 | parsePrecedence(.prec_assignment); 169 | } 170 | 171 | fn block() void { 172 | while (!check(.right_brace) and !check(.lox_eof)) declaration(); 173 | consume(.right_brace, "Expect '}' after block."); 174 | } 175 | 176 | fn function(t: FunctionType) void { 177 | var c: Compiler = undefined; 178 | Compiler.init(&c, t); 179 | beginScope(); 180 | 181 | consume(.left_paren, "Expect '(' after functions name."); 182 | if (!check(.right_paren)) { 183 | while (true) { 184 | current.?.function.arity += 1; 185 | if (current.?.function.arity > 255) { 186 | errorAtCurrent("Can't have more than 255 parameters."); 187 | } 188 | const constant = parseVariable("Expect parameter name."); 189 | defineVariable(constant); 190 | if (!match(.comma)) break; 191 | } 192 | } 193 | consume(.right_paren, "Expect ')' after parameters."); 194 | consume(.left_brace, "Expect '{' before function body."); 195 | block(); 196 | 197 | const fun = endCompiler(); 198 | emitBytes(&.{ @enumToInt(OpCode.op_closure), makeConstant(Value.Object(@ptrCast(*object.Obj, fun))) }); 199 | 200 | for (c.upvalues[0..fun.upvalue_count]) |upvalue| { 201 | emitByte(if (upvalue.is_local) 1 else 0); 202 | emitByte(upvalue.index); 203 | } 204 | } 205 | 206 | fn method() void { 207 | consume(.identifier, "Expect method name."); 208 | const constant = identifierConstant(&p.previous); 209 | const t: FunctionType = if (p.previous.length == 4 and std.mem.eql(u8, @ptrCast(*const [4]u8, p.previous.start), "init")) 210 | .type_initializer 211 | else 212 | .type_method; 213 | function(t); 214 | emitBytes(&.{ @enumToInt(OpCode.op_method), constant }); 215 | } 216 | 217 | fn beginScope() void { 218 | current.?.scope_depth += 1; 219 | } 220 | 221 | fn endScope() void { 222 | current.?.scope_depth -= 1; 223 | while (current.?.local_count > 0 and current.?.locals[@intCast(usize, current.?.local_count - 1)].depth > current.?.scope_depth) { 224 | if (current.?.locals[current.?.local_count - 1].is_captured) { 225 | emitByte(@enumToInt(OpCode.op_close_upvalue)); 226 | } else { 227 | emitByte(@enumToInt(OpCode.op_pop)); 228 | } 229 | current.?.local_count -= 1; 230 | } 231 | } 232 | 233 | fn varDeclaration() void { 234 | const global = parseVariable("Expect variable name."); 235 | 236 | if (match(.equal)) expression() else emitByte(@enumToInt(OpCode.op_nil)); 237 | consume(.semicolon, "Expect ';' after a variable declaration."); 238 | 239 | defineVariable(global); 240 | } 241 | 242 | fn funDeclaration() void { 243 | const global = parseVariable("Expect function name"); 244 | markInitialized(); 245 | function(.type_function); 246 | defineVariable(global); 247 | } 248 | 249 | fn defineVariable(global: u8) void { 250 | if (current.?.scope_depth > 0) { 251 | markInitialized(); 252 | return; 253 | } 254 | emitBytes(&.{ @enumToInt(OpCode.op_define_global), global }); 255 | } 256 | 257 | fn markInitialized() void { 258 | if (current.?.scope_depth == 0) return; 259 | current.?.locals[current.?.local_count - 1].depth = @intCast(isize, current.?.scope_depth); 260 | } 261 | 262 | fn declareVariable() void { 263 | if (current.?.scope_depth == 0) return; 264 | const name = &p.previous; 265 | var i: usize = current.?.local_count; 266 | while (i >= 0) : (i -= 1) { 267 | const local = ¤t.?.locals[i]; 268 | if (local.depth != -1 and local.depth < current.?.scope_depth) break; 269 | if (identifiersEqual(name, &local.name)) { 270 | errorAtPrevious("Already a variable with this name in this scope."); 271 | } 272 | } 273 | addLocal(name.*); 274 | } 275 | 276 | fn addLocal(name: Token) void { 277 | defer current.?.local_count += 1; 278 | if (current.?.local_count >= 256) { 279 | errorAtPrevious("Too many local variables in function."); 280 | return; 281 | } 282 | const local = ¤t.?.locals[current.?.local_count]; 283 | local.name = name; 284 | local.depth = -1; 285 | local.is_captured = false; 286 | } 287 | 288 | fn syntheticToken(text: []const u8) Token { 289 | return .{ 290 | .t = TokenType.lox_nil, 291 | .start = text.ptr, 292 | .length = text.len, 293 | .line = 0, 294 | }; 295 | } 296 | 297 | fn expressionStatement() void { 298 | expression(); 299 | consume(.semicolon, "Expect ';' after expression."); 300 | emitByte(@enumToInt(OpCode.op_pop)); 301 | } 302 | 303 | fn ifStatement() void { 304 | consume(.left_paren, "Expect '(' after 'if'."); 305 | expression(); 306 | consume(.right_paren, "Expect ')' after condition."); 307 | 308 | const then_jump = emitJump(.op_jump_if_false); 309 | emitByte(@enumToInt(OpCode.op_pop)); 310 | statement(); 311 | const else_jump = emitJump(.op_jump); 312 | patchJump(then_jump); 313 | 314 | emitByte(@enumToInt(OpCode.op_pop)); 315 | if (match(.lox_else)) statement(); 316 | patchJump(else_jump); 317 | } 318 | 319 | fn and_(_: bool) void { 320 | const end_jump = emitJump(.op_jump_if_false); 321 | 322 | emitByte(@enumToInt(OpCode.op_pop)); 323 | parsePrecedence(.prec_and); 324 | 325 | patchJump(end_jump); 326 | } 327 | 328 | fn or_(_: bool) void { 329 | const else_jump = emitJump(.op_jump_if_false); 330 | const end_jump = emitJump(.op_jump); 331 | 332 | patchJump(else_jump); 333 | emitByte(@enumToInt(OpCode.op_pop)); 334 | 335 | parsePrecedence(.prec_or); 336 | patchJump(end_jump); 337 | } 338 | 339 | fn printStatement() void { 340 | expression(); 341 | consume(.semicolon, "Expect ';' after value."); 342 | emitByte(@enumToInt(OpCode.op_print)); 343 | } 344 | 345 | fn whileStatement() void { 346 | const loop_start = currentChunk().count; 347 | consume(.left_paren, "Expect '(' after 'while'."); 348 | expression(); 349 | consume(.right_paren, "Expect ')' after condition"); 350 | 351 | const exit_jump = emitJump(.op_jump_if_false); 352 | emitByte(@enumToInt(OpCode.op_pop)); 353 | statement(); 354 | emitLoop(loop_start); 355 | 356 | patchJump(exit_jump); 357 | emitByte(@enumToInt(OpCode.op_pop)); 358 | } 359 | 360 | fn forStatement() void { 361 | beginScope(); 362 | defer endScope(); 363 | consume(.left_paren, "Expect '(' after 'for'."); 364 | if (match(.semicolon)) {} else if (match(.lox_var)) { 365 | varDeclaration(); 366 | } else { 367 | expressionStatement(); 368 | } 369 | 370 | var loop_start = currentChunk().count; 371 | var exit_jump: ?u32 = null; 372 | if (!match(.semicolon)) { 373 | expression(); 374 | consume(.semicolon, "Expect ';' after loop condition"); 375 | exit_jump = emitJump(.op_jump_if_false); 376 | emitByte(@enumToInt(OpCode.op_pop)); 377 | } 378 | 379 | if (!match(.right_paren)) { 380 | const body_jump = emitJump(.op_jump); 381 | const increment_start = currentChunk().count; 382 | expression(); 383 | emitByte(@enumToInt(OpCode.op_pop)); 384 | consume(.right_paren, "Expect ')' after for clauses"); 385 | 386 | emitLoop(loop_start); 387 | loop_start = increment_start; 388 | patchJump(body_jump); 389 | } 390 | 391 | statement(); 392 | emitLoop(loop_start); 393 | if (exit_jump) |ej| { 394 | patchJump(ej); 395 | emitByte(@enumToInt(OpCode.op_pop)); 396 | } 397 | } 398 | 399 | fn declaration() void { 400 | if (match(.lox_class)) classDeclaration() else if (match(.lox_fun)) funDeclaration() else if (match(.lox_var)) varDeclaration() else statement(); 401 | 402 | if (p.panic_mode) synchronize(); 403 | } 404 | 405 | fn classDeclaration() void { 406 | consume(.identifier, "Expect class name."); 407 | var class_name = p.previous; 408 | const name_constant = identifierConstant(&p.previous); 409 | declareVariable(); 410 | 411 | emitBytes(&.{ @enumToInt(OpCode.op_class), name_constant }); 412 | defineVariable(name_constant); 413 | 414 | var class_compiler = ClassCompiler{ .enclosing = current_class, .has_superclass = false }; 415 | current_class = &class_compiler; 416 | 417 | if (match(.less)) { 418 | consume(.identifier, "Expect superclass name."); 419 | variable(false); 420 | if (identifiersEqual(&class_name, &p.previous)) { 421 | errorAtPrevious("A class can't inherit from itself."); 422 | } 423 | beginScope(); 424 | addLocal(syntheticToken("super")); 425 | defineVariable(0); 426 | namedVariable(&class_name, false); 427 | emitByte(@enumToInt(OpCode.op_inherit)); 428 | class_compiler.has_superclass = true; 429 | } 430 | 431 | namedVariable(&class_name, false); 432 | consume(.left_brace, "Expect '{' before class body."); 433 | while (!check(.right_brace) and !check(.lox_eof)) { 434 | method(); 435 | } 436 | consume(.right_brace, "Expect '}' after class body."); 437 | emitByte(@enumToInt(OpCode.op_pop)); 438 | 439 | if (class_compiler.has_superclass) { 440 | endScope(); 441 | } 442 | 443 | current_class = current_class.?.enclosing; 444 | } 445 | 446 | fn statement() void { 447 | if (match(.lox_print)) { 448 | printStatement(); 449 | } else if (match(.lox_for)) { 450 | forStatement(); 451 | } else if (match(.lox_if)) { 452 | ifStatement(); 453 | } else if (match(.lox_return)) { 454 | returnStatement(); 455 | } else if (match(.lox_while)) { 456 | whileStatement(); 457 | } else if (match(.left_brace)) { 458 | beginScope(); 459 | block(); 460 | endScope(); 461 | } else { 462 | expressionStatement(); 463 | } 464 | } 465 | 466 | fn returnStatement() void { 467 | if (current.?.fun_t == .type_script) errorAtPrevious("Can't return from top-level code."); 468 | if (match(.semicolon)) emitReturn() else { 469 | if (current.?.fun_t == .type_initializer) { 470 | errorAtCurrent("Can't return a value from an initializer."); 471 | } 472 | expression(); 473 | consume(.semicolon, "Expect ';' after return value."); 474 | emitByte(@enumToInt(OpCode.op_return)); 475 | } 476 | } 477 | 478 | fn number(_: bool) void { 479 | var value = std.fmt.parseFloat(f64, p.previous.start[0..p.previous.length]) catch { 480 | errorAtPrevious("Invalid character in number."); 481 | return; 482 | }; 483 | emitConstant(Value.Number(value)); 484 | } 485 | 486 | fn string(_: bool) void { 487 | emitConstant(Value.Object(object.copyString(p.previous.start + 1, p.previous.length - 2))); 488 | } 489 | 490 | fn variable(can_assign: bool) void { 491 | namedVariable(&p.previous, can_assign); 492 | } 493 | 494 | fn this_(_: bool) void { 495 | if (current_class) |_| { 496 | variable(false); 497 | } else { 498 | errorAtPrevious("Can't use 'this' outside of a class."); 499 | } 500 | } 501 | 502 | fn super_(_: bool) void { 503 | if (current_class) |cc| { 504 | if (!cc.has_superclass) { 505 | errorAtPrevious("Can't use 'super' in a class with no superclass."); 506 | } 507 | consume(.dot, "Expect '.' after 'super'."); 508 | consume(.identifier, "Expect superclass method name."); 509 | const name = identifierConstant(&p.previous); 510 | 511 | namedVariable(&syntheticToken("this"), false); 512 | if (match(.left_paren)) { 513 | const arg_count = argumentList(); 514 | namedVariable(&syntheticToken("super"), false); 515 | emitBytes(&.{ @enumToInt(OpCode.op_super_invoke), name }); 516 | emitByte(arg_count); 517 | } else { 518 | namedVariable(&syntheticToken("super"), true); 519 | emitBytes(&.{ @enumToInt(OpCode.op_get_super), name }); 520 | } 521 | } else { 522 | errorAtPrevious("Can't use 'super' outside of a class."); 523 | } 524 | } 525 | 526 | fn namedVariable(name: *Token, can_assign: bool) void { 527 | var getOp: u8 = undefined; 528 | var setOp: u8 = undefined; 529 | var arg = resolveLocal(current.?, name); 530 | if (arg) |_| { 531 | getOp = @enumToInt(OpCode.op_get_local); 532 | setOp = @enumToInt(OpCode.op_set_local); 533 | } else { 534 | arg = resolveUpvalue(current.?, name); 535 | if (arg) |_| { 536 | getOp = @enumToInt(OpCode.op_get_upvalue); 537 | setOp = @enumToInt(OpCode.op_set_upvalue); 538 | } else { 539 | arg = identifierConstant(name); 540 | getOp = @enumToInt(OpCode.op_get_global); 541 | setOp = @enumToInt(OpCode.op_set_global); 542 | } 543 | } 544 | if (can_assign and match(.equal)) { 545 | expression(); 546 | emitBytes(&.{ setOp, arg.? }); 547 | } else { 548 | emitBytes(&.{ getOp, arg.? }); 549 | } 550 | } 551 | 552 | fn grouping(_: bool) void { 553 | expression(); 554 | consume(.right_paren, "Expect ')' after expression."); 555 | } 556 | 557 | fn call(_: bool) void { 558 | const arg_count = argumentList(); 559 | emitBytes(&.{ @enumToInt(OpCode.op_call), arg_count }); 560 | } 561 | 562 | fn dot(can_assign: bool) void { 563 | consume(.identifier, "Expect property name after '.'."); 564 | const name = identifierConstant(&p.previous); 565 | 566 | if (can_assign and match(.equal)) { 567 | expression(); 568 | emitBytes(&.{ @enumToInt(OpCode.op_set_property), name }); 569 | } else if (match(.left_paren)) { 570 | const arg_count = argumentList(); 571 | emitBytes(&.{ @enumToInt(OpCode.op_invoke), name }); 572 | emitByte(arg_count); 573 | } else { 574 | emitBytes(&.{ @enumToInt(OpCode.op_get_property), name }); 575 | } 576 | } 577 | 578 | fn argumentList() u8 { 579 | var arg_count: u8 = 0; 580 | if (!check(.right_paren)) { 581 | while (true) { 582 | expression(); 583 | if (arg_count == 255) { 584 | errorAtPrevious("Can't have more than 255 arguments."); 585 | } 586 | arg_count += 1; 587 | if (!match(.comma)) break; 588 | } 589 | } 590 | consume(.right_paren, "Expect ')' after arguments."); 591 | return arg_count; 592 | } 593 | 594 | fn unary(_: bool) void { 595 | const operator_type = p.previous.t; 596 | 597 | parsePrecedence(.prec_unary); 598 | 599 | switch (operator_type) { 600 | .bang => emitByte(@enumToInt(OpCode.op_not)), 601 | .minus => emitByte(@enumToInt(OpCode.op_negate)), 602 | else => unreachable, 603 | } 604 | } 605 | 606 | fn binary(_: bool) void { 607 | const operator_type = p.previous.t; 608 | const rule = getRule(operator_type); 609 | parsePrecedence(@intToEnum(Precedence, @enumToInt(rule.precedence) + 1)); 610 | switch (operator_type) { 611 | .bang_equal => emitBytes(&.{ @enumToInt(OpCode.op_equal), @enumToInt(OpCode.op_not) }), 612 | .equal_equal => emitByte(@enumToInt(OpCode.op_equal)), 613 | .greater => emitByte(@enumToInt(OpCode.op_greater)), 614 | .greater_equal => emitBytes(&.{ @enumToInt(OpCode.op_less), @enumToInt(OpCode.op_not) }), 615 | .less => emitByte(@enumToInt(OpCode.op_less)), 616 | .less_equal => emitBytes(&.{ @enumToInt(OpCode.op_greater), @enumToInt(OpCode.op_not) }), 617 | .plus => emitByte(@enumToInt(OpCode.op_add)), 618 | .minus => emitByte(@enumToInt(OpCode.op_subtract)), 619 | .star => emitByte(@enumToInt(OpCode.op_multiply)), 620 | .slash => emitByte(@enumToInt(OpCode.op_divide)), 621 | else => return, 622 | } 623 | } 624 | 625 | fn literal(_: bool) void { 626 | switch (p.previous.t) { 627 | .lox_false => emitByte(@enumToInt(OpCode.op_false)), 628 | .lox_true => emitByte(@enumToInt(OpCode.op_true)), 629 | .lox_nil => emitByte(@enumToInt(OpCode.op_nil)), 630 | else => unreachable, 631 | } 632 | } 633 | 634 | fn parsePrecedence(precedence: Precedence) void { 635 | advance(); 636 | const prefix_rule = getRule(p.previous.t).prefix; 637 | var can_assign: bool = undefined; 638 | if (prefix_rule) |rule| { 639 | can_assign = @enumToInt(precedence) <= @enumToInt(Precedence.prec_assignment); 640 | rule(can_assign); 641 | } else { 642 | errorAtPrevious("Expect expression."); 643 | return; 644 | } 645 | 646 | while (@enumToInt(precedence) <= @enumToInt(getRule(p.current.t).precedence)) { 647 | advance(); 648 | const infix_rule = getRule(p.previous.t).infix; 649 | infix_rule.?(can_assign); 650 | } 651 | if (can_assign and match(.equal)) { 652 | errorAtPrevious("Invalid assignment target."); 653 | } 654 | } 655 | 656 | fn parseVariable(errorMessage: []const u8) u8 { 657 | consume(.identifier, errorMessage); 658 | declareVariable(); 659 | if (current.?.scope_depth > 0) return 0; 660 | return identifierConstant(&p.previous); 661 | } 662 | 663 | fn identifierConstant(name: *Token) u8 { 664 | return makeConstant(Value.Object(object.copyString(name.start, name.length))); 665 | } 666 | 667 | fn identifiersEqual(a: *Token, b: *Token) bool { 668 | return std.mem.eql(u8, a.start[0..a.length], b.start[0..b.length]); 669 | } 670 | 671 | fn resolveLocal(compiler: *Compiler, name: *Token) ?u8 { 672 | var i: isize = compiler.local_count; 673 | i -= 1; 674 | while (i >= 0) : (i -= 1) { 675 | const local = &compiler.locals[@intCast(u8, i)]; 676 | if (identifiersEqual(name, &local.name)) { 677 | if (local.depth == -1) { 678 | errorAtPrevious("Can't read local variable in its own initializer."); 679 | } 680 | return @intCast(u8, i); 681 | } 682 | } 683 | return null; 684 | } 685 | 686 | fn resolveUpvalue(compiler: *Compiler, name: *Token) ?u8 { 687 | const enc = compiler.enclosing orelse return null; 688 | const local = resolveLocal(enc, name); 689 | if (local) |index| { 690 | enc.locals[index].is_captured = true; 691 | return addUpvalue(compiler, index, true); 692 | } 693 | 694 | const upvalue = resolveUpvalue(enc, name); 695 | if (upvalue) |index| { 696 | return addUpvalue(compiler, index, false); 697 | } 698 | return null; 699 | } 700 | 701 | fn addUpvalue(compiler: *Compiler, index: u8, is_local: bool) u8 { 702 | const upvalue_count = compiler.function.upvalue_count; 703 | 704 | for (compiler.upvalues[0..upvalue_count]) |*upvalue, i| { 705 | if (upvalue.index == index and upvalue.is_local == is_local) return @intCast(u8, i); 706 | } 707 | 708 | if (upvalue_count == 256) { 709 | errorAtPrevious("Too many closure variables in function."); 710 | return 0; 711 | } 712 | 713 | compiler.upvalues[upvalue_count].is_local = is_local; 714 | compiler.upvalues[upvalue_count].index = index; 715 | compiler.function.upvalue_count += 1; 716 | return upvalue_count; 717 | } 718 | 719 | fn advance() void { 720 | p.previous = p.current; 721 | 722 | while (true) { 723 | p.current = s.scanToken(); 724 | if (p.current.t != .lox_error) break; 725 | 726 | errorAtCurrent(p.current.start[0..p.current.length]); 727 | } 728 | } 729 | 730 | fn consume(t: TokenType, message: []const u8) void { 731 | if (p.current.t == t) { 732 | advance(); 733 | return; 734 | } 735 | 736 | errorAtCurrent(message); 737 | } 738 | 739 | fn match(token: TokenType) bool { 740 | if (!check(token)) return false; 741 | advance(); 742 | return true; 743 | } 744 | 745 | fn check(token: TokenType) bool { 746 | return p.current.t == token; 747 | } 748 | 749 | fn makeConstant(value: Value) u8 { 750 | const constant = currentChunk().addConstant(value); 751 | if (constant >= std.math.maxInt(u8)) { 752 | errorAtPrevious("Too many constants in one chunk."); 753 | return 0; 754 | } 755 | 756 | return @intCast(u8, constant); 757 | } 758 | 759 | fn emitByte(byte: u8) void { 760 | currentChunk().writeChunk(byte, @intCast(u32, p.previous.line)); 761 | } 762 | 763 | fn emitBytes(bytes: []const u8) void { 764 | for (bytes) |byte| { 765 | emitByte(byte); 766 | } 767 | } 768 | 769 | fn emitJump(instruction: OpCode) u32 { 770 | emitByte(@enumToInt(instruction)); 771 | emitByte(0xFF); 772 | emitByte(0xFF); 773 | return currentChunk().count - 2; 774 | } 775 | 776 | fn emitLoop(start: u32) void { 777 | emitByte(@enumToInt(OpCode.op_loop)); 778 | const offset = currentChunk().count - start + 2; 779 | if (offset > 0xFFFF) errorAtPrevious("Loop body too large."); 780 | emitByte(@truncate(u8, offset >> 8)); 781 | emitByte(@truncate(u8, offset)); 782 | } 783 | 784 | fn patchJump(offset: u32) void { 785 | const jump = currentChunk().count - offset - 2; 786 | if (jump > 0xFFFF) { 787 | errorAtPrevious("Too much code to jump over."); 788 | } 789 | currentChunk().code[offset] = @truncate(u8, jump >> 8); 790 | currentChunk().code[offset + 1] = @truncate(u8, jump); 791 | } 792 | 793 | fn emitReturn() void { 794 | if (current.?.fun_t == .type_initializer) { 795 | emitBytes(&.{ @enumToInt(OpCode.op_get_local), 0 }); 796 | } else { 797 | emitByte(@enumToInt(OpCode.op_nil)); 798 | } 799 | emitByte(@enumToInt(OpCode.op_return)); 800 | } 801 | 802 | fn emitConstant(value: Value) void { 803 | emitBytes(&.{ @enumToInt(OpCode.op_constant), makeConstant(value) }); 804 | } 805 | 806 | fn endCompiler() *ObjFunction { 807 | emitReturn(); 808 | const fun = current.?.function; 809 | if (comptime common.dump_enabled) { 810 | if (!p.had_error) { 811 | debug.disassembleChunk(currentChunk(), if (fun.name) |name| name.chars[0..name.length] else "