### Example Method Access - Lox Source: https://craftinginterpreters.com/methods-and-initializers Demonstrates accessing a method on an instance and calling it. This shows the separation of method access (getting the method object) and method invocation (calling the method object). ```lox instance.method(argument); ``` -------------------------------- ### Static Methods in Lox (Example) Source: https://craftinginterpreters.com/classes This example demonstrates the concept of static methods in Lox, where a method can be called directly on the class itself rather than on an instance. It shows the syntax for defining and calling such methods. ```Lox class Math { class square(n) { return n * n; } } print Math.square(3); // Prints "9". ``` -------------------------------- ### Basic C "Hello, world!" Example Source: https://craftinginterpreters.com/optimization A simple C code snippet demonstrating the fundamental 'Hello, world!' output. This serves as a basic example of program output, though it is not directly related to the CLox virtual machine's internal workings. ```c #include int main() { printf("Hello, world!\n"); return 0; } ``` -------------------------------- ### Example Lox Class and Method Call Source: https://craftinginterpreters.com/classes A simple Lox code example demonstrating the definition of a class 'Bacon' with an 'eat' method and calling that method on a new instance. ```lox class Bacon { eat() { print "Crunch crunch crunch!"; } } Bacon().eat(); // Prints "Crunch crunch crunch!". ``` -------------------------------- ### Instance Creation Example (Lox) Source: https://craftinginterpreters.com/classes-and-instances Demonstrates how to define a class and create an instance of it in the Lox programming language. The example shows a simple class definition followed by invoking the class name with parentheses to create and print a new instance. ```lox class Brioche {} print Brioche(); ``` -------------------------------- ### Compile Entry Point in C Source: https://craftinginterpreters.com/local-variables Sets up the compiler for a new compilation unit by initializing a Compiler instance and assigning the target chunk. This function is typically called at the start of compiling a source file or module. ```c Compiler compiler; initCompiler(&compiler); compilingChunk = chunk; ``` -------------------------------- ### Getter Methods in Lox (Example) Source: https://craftinginterpreters.com/classes This example illustrates the implementation of getter methods in Lox. Getters are declared without parameters and their bodies execute when a property with the same name is accessed on an instance. ```Lox class Circle { init(radius) { this.radius = radius; } area { return 3.141592653 * this.radius * this.radius; } } var circle = Circle(4); print circle.area; // Prints roughly "50.2655". ``` -------------------------------- ### Lox Class Inheritance and Super Method Call Example Source: https://craftinginterpreters.com/inheritance Demonstrates a Lox program with a class hierarchy (A, B, C) showcasing how 'super.method()' correctly calls the superclass's method. This example highlights the difference between 'this' and the class containing the 'super' expression for method lookup. ```lox class A { method() { print "A method"; } } class B < A { method() { print "B method"; } test() { super.method(); } } class C < B {} C().test(); ``` -------------------------------- ### Anonymous Function Example (Lox) Source: https://craftinginterpreters.com/functions Illustrates how Lox would handle anonymous functions if they had direct syntax, using a `var` declaration to assign a function literal to a variable. ```lox var add = fun (a, b) { print a + b; }; ``` -------------------------------- ### Method Call with 'this' Binding Example - Lox Source: https://craftinginterpreters.com/methods-and-initializers A Lox example demonstrating method access and invocation where the `this` keyword is used within the method. This highlights the need for the method object to capture the instance it was accessed from to correctly bind `this`. ```lox class Person { sayName() { print this.name; } } var jane = Person(); jane.name = "Jane"; var method = jane.sayName; method(); // ? ``` -------------------------------- ### VM Initialization for Object List (C) Source: https://craftinginterpreters.com/strings Initializes the VM's 'objects' pointer to NULL, indicating that there are no allocated objects when the VM starts. ```c vm.objects = NULL; ``` -------------------------------- ### Example of Superclass Method Call in Lox Source: https://craftinginterpreters.com/inheritance Demonstrates how a subclass (BostonCream) can extend the behavior of a superclass method (cook) using the 'super.cook()' syntax. This allows for refining, rather than completely replacing, superclass functionality. ```lox class Doughnut { cook() { print "Fry until golden brown."; } } class BostonCream < Doughnut { cook() { super.cook(); print "Pipe full of custard and coat with chocolate."; } } BostonCream().cook(); ``` -------------------------------- ### Create a Token in C (scanner.c) Source: https://craftinginterpreters.com/scanning-on-demand The `makeToken` function constructs and returns a `Token` object. It captures the lexeme by calculating the length from the `start` and `current` pointers of the scanner, and also records the token type and line number. ```c static Token makeToken(TokenType type) { Token token; token.type = type; token.start = scanner.start; token.length = (int)(scanner.current - scanner.start); token.line = scanner.line; return token; } ``` -------------------------------- ### Runtime Behavior of 'this' in Methods (Conceptual) Source: https://craftinginterpreters.com/classes Illustrates the runtime behavior of the 'this' keyword using a Lox code example. When a method is accessed and then called, 'this' should refer to the instance from which the method was accessed. ```lox class Egotist { speak() { print this; } } var method = Egotist().speak; method(); ``` ```lox class Cake { taste() { var adjective = "delicious"; print "The " + this.flavor + " cake is " + adjective + "!"; } } var cake = Cake(); cake.flavor = "German chocolate"; cake.taste(); // Prints "The German chocolate cake is delicious!". ``` ```lox class Thing { getCallback() { fun localFunction() { print this; } return localFunction; } } var callback = Thing().getCallback(); callback(); ``` -------------------------------- ### Initialize and Run clox Interpreter (C) Source: https://craftinginterpreters.com/scanning-on-demand Sets up the Virtual Machine and determines whether to run a script file or enter the REPL based on command-line arguments. Handles script execution and displays usage information for incorrect arguments. ```c int main(int argc, const char* argv[]) { initVM(); if (argc == 1) { repl(); } else if (argc == 2) { runFile(argv[1]); } else { fprintf(stderr, "Usage: clox [path]\n"); exit(64); } freeVM(); return 0; } ``` -------------------------------- ### Expression Target Example in Lox Source: https://craftinginterpreters.com/statements-and-state Demonstrates using an expression as a target in Lox. This code snippet illustrates getting a field's value. ```lox newPoint(x + 2, 0).y; ``` -------------------------------- ### Parsing 'Get' Expressions in LoxParser Source: https://craftinginterpreters.com/classes Implements the parsing logic for 'Get' expressions within the `call()` method of the Lox parser. It handles the dot (.) operator followed by an identifier, constructing a 'Get' AST node. This code is part of the loop that chains calls and property accesses. ```Java } else if (match(DOT)) { Token name = consume(IDENTIFIER, "Expect property name after '.'."); expr = new Expr.Get(expr, name); ``` -------------------------------- ### Example Instance Creation and Usage (Lox) Source: https://craftinginterpreters.com/classes Demonstrates creating an instance of a Lox class 'Bagel' by calling the class object and then printing the instance. This showcases the mechanism for object instantiation in Lox, where classes act as callable factories. ```lox class Bagel {} Bagel(); ``` ```lox class Bagel {} var bagel = Bagel(); print bagel; // Prints "Bagel instance". ``` -------------------------------- ### Interpreting 'Get' Expressions in LoxInterpreter Source: https://craftinginterpreters.com/classes Implements the interpretation logic for 'Get' expressions. It first evaluates the object expression, then checks if the resulting object is a LoxInstance. If it is, it calls the instance's `get` method to retrieve the property; otherwise, it throws a runtime error indicating that only instances have properties. ```Java @Override public Object visitGetExpr(Expr.Get expr) { Object object = evaluate(expr.object); if (object instanceof LoxInstance) { return ((LoxInstance) object).get(expr.name); } throw new RuntimeError(expr.name, "Only instances have properties."); } ``` -------------------------------- ### Set Up Initial CallFrame in C Source: https://craftinginterpreters.com/calls-and-functions Sets up the initial CallFrame for executing top-level code. This involves pushing the function onto the stack and then calling the `call` function to initialize the frame. ```c push(OBJ_VAL(function)); call(function, 0); ``` -------------------------------- ### Initialize VM Gray Stack (C) Source: https://craftinginterpreters.com/garbage-collection Initializes the gray stack related fields within the VM structure to their default values (zero count, zero capacity, and NULL stack) when the VM starts. This ensures a clean state for garbage collection. ```c vm.grayCount = 0; v ``` ```c m.grayCapacity = 0; v ``` ```c m.grayStack = NULL; ``` -------------------------------- ### Lox Program Example Source: https://craftinginterpreters.com/statements-and-state An example of a simple Lox program demonstrating the use of print statements and basic expressions. ```lox print "one"; print true; print 2 + 1; ``` -------------------------------- ### Write Bytecode Instructions for Arithmetic Operations (C) Source: https://craftinginterpreters.com/a-virtual-machine Demonstrates how to write bytecode instructions for basic arithmetic operations and constant pushing using `writeChunk` and `addConstant`. It shows the sequence for an addition followed by a division and negation, illustrating stack-based data flow. ```c writeChunk(&chunk, OP_ADD, 123); constant = addConstant(&chunk, 5.6); writeChunk(&chunk, OP_CONSTANT, 123); writeChunk(&chunk, constant, 123); writeChunk(&chunk, OP_DIVIDE, 123); writeChunk(&chunk, OP_NEGATE, 123); writeChunk(&chunk, OP_RETURN, 123); ``` -------------------------------- ### Lox Example Usage Source: https://craftinginterpreters.com/global-variables Demonstrates the usage of the print statement in Lox code. These examples show printing the result of arithmetic expressions. ```lox print 1 + 2; print 3 * 4; ``` -------------------------------- ### Initialize Garbage Collection Tracing (C) Source: https://craftinginterpreters.com/garbage-collection Initiates the garbage collection tracing process by calling `markRoots` and then `traceReferences` to handle marked objects. ```c markRoots(); traceReferences(); ``` -------------------------------- ### Example Class Definition and Usage (Clox) Source: https://craftinginterpreters.com/methods-and-initializers This code demonstrates the usage of the class system, including an initializer and a method, in the Clox language. It defines a 'CoffeeMaker' class with an 'init' method to set a 'coffee' property and a 'brew' method to print a message. An instance is created, and its 'brew' method is called. ```clox class CoffeeMaker { init(coffee) { this.coffee = coffee; } brew() { print "Enjoy your cup of " + this.coffee; // No reusing the grounds! this.coffee = nil; } } var maker = CoffeeMaker("coffee and chicory"); maker.brew(); ``` -------------------------------- ### Nested String Interpolation Example (Conceptual) Source: https://craftinginterpreters.com/scanning-on-demand This example shows a more complex string interpolation scenario with nested interpolation. It poses a challenge for scanner implementation regarding how to correctly tokenize such nested structures. ```plaintext "Nested ${'interpolation?! Are you ${'mad?!'}'}"} ``` -------------------------------- ### Basic C main function for VM Source: https://craftinginterpreters.com/chunks-of-bytecode This C code snippet defines the entry point for the virtual machine application. It includes necessary headers and sets up the main function, which will be the foundation for building the interpreter. ```c #include "common.h" int main(int argc, const char* argv[]) { return 0; } ``` -------------------------------- ### Get Variable Value (Java) Source: https://craftinginterpreters.com/statements-and-state Implements the `get` method to retrieve the value associated with a variable name. It checks if the variable exists in the environment and throws a `RuntimeError` if it is undefined. ```java Object get(Token name) { if (values.containsKey(name.lexeme)) { return values.get(name.lexeme); } throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'."); } ``` -------------------------------- ### Lox: Example variable assignment and printing Source: https://craftinginterpreters.com/global-variables An example of Lox code demonstrating variable assignment, string concatenation, and printing the result. This showcases basic scripting capabilities. ```lox var breakfast = "beignets"; var beverage = "cafe au lait"; breakfast = "beignets with " + beverage; print breakfast; ``` -------------------------------- ### VM: Initializing String Table in _vm.c_ Source: https://craftinginterpreters.com/calls-and-functions This snippet shows the initialization of the string table within the _initVM_ function in _vm.c_. This table is crucial for managing string interning, which optimizes string storage and comparison. ```c initTable(&vm.strings); ``` -------------------------------- ### AST Node for Get Expressions Source: https://craftinginterpreters.com/classes Defines the syntax tree node for 'Get' expressions, which represent accessing a property on an object. It holds the object and the property name token. This node is used during parsing and AST traversal. ```Java "Get : Expr object, Token name", ``` -------------------------------- ### Example Class Declaration in Lox Source: https://craftinginterpreters.com/classes A concrete example of a class declaration in the Lox programming language. This 'Breakfast' class includes two methods, 'cook' and 'serve', demonstrating method definition without a 'fun' keyword. ```lox class Breakfast { cook() { print "Eggs a-fryin'!"; } serve(who) { print "Enjoy your breakfast, " + who + "."; } } ``` -------------------------------- ### Intern String Allocation and Table Insertion in C Source: https://craftinginterpreters.com/garbage-collection This snippet shows the process of allocating a new string, calculating its hash, and then storing it in the VM's string table. It ensures the string is pushed onto the stack before table operations to protect it from garbage collection during potential table resizing. ```c string->chars = chars; string->hash = hash; push(OBJ_VAL(string)); tableSet(&vm.strings, string, NIL_VAL); pop(); return string; } ``` -------------------------------- ### Initialize Hash Table Buckets (C) Source: https://craftinginterpreters.com/hash-tables Allocates and initializes an array of buckets for a hash table. Each bucket is set to an empty state with a NULL key and a NIL value. This is used for the initial allocation of the table. ```c static void adjustCapacity(Table* table, int capacity) { Entry* entries = ALLOCATE(Entry, capacity); for (int i = 0; i < capacity; i++) { entries[i].key = NULL; entries[i].value = NIL_VAL; } table->entries = entries; table->capacity = capacity; } ``` -------------------------------- ### Example Lox Class Definition and Usage (Lox) Source: https://craftinginterpreters.com/classes An example of defining a simple class 'DevonshireCream' in the Lox scripting language and printing its name. This demonstrates the basic syntax for class declaration and how class objects are represented and can be printed. ```lox class DevonshireCream { serveOn() { return "Scones"; } } print DevonshireCream; // Prints "DevonshireCream". ``` -------------------------------- ### Detect Misuse of 'this' (Lox Compiler) Source: https://craftinginterpreters.com/methods-and-initializers This section shows examples of incorrect 'this' usage in Lox, which should be caught by the compiler. These include 'this' at the top level or within a function not nested in a method. ```lox print this; // At top level. fun notMethod() { print this; // In a function. } ``` -------------------------------- ### Hash Table Initialization Implementation (table.c) Source: https://craftinginterpreters.com/hash-tables Provides the C implementation for initializing a hash table. It sets the count and capacity to zero and the entries pointer to NULL. ```c #include #include #include "memory.h" #include "object.h" #include "table.h" #include "value.h" void initTable(Table* table) { table->count = 0; table->capacity = 0; table->entries = NULL; } ``` -------------------------------- ### Lox Print Statement Example Source: https://craftinginterpreters.com/a-virtual-machine An example of a Lox print statement involving arithmetic operations. This snippet illustrates the need for instructions to handle constants, the print operation, and subtraction, and how operands are identified for operations. ```lox print 3 - 2; ``` -------------------------------- ### VM Initialization for GC (C) Source: https://craftinginterpreters.com/garbage-collection Initializes the `bytesAllocated` counter to 0 and sets an initial arbitrary threshold for `nextGC` in the `initVM` function in `vm.c`. The initial `nextGC` value is chosen to avoid triggering GCs too quickly initially but also to prevent waiting too long. ```c void initVM() { // ... other initializations vm.bytesAllocated = 0; vm.nextGC = 1024 * 1024; // Initial threshold, e.g., 1MB // ... other initializations } ``` -------------------------------- ### Example Class Declaration - Lox Source: https://craftinginterpreters.com/methods-and-initializers An example of a simple class declaration in the Lox programming language. This class 'Brunch' contains two empty methods, 'bacon' and 'eggs'. It serves as input for the compiler to generate bytecode. ```lox class Brunch { bacon() {} eggs() {} } ``` -------------------------------- ### Initializing and Freeing the String Table Source: https://craftinginterpreters.com/hash-tables These C code snippets demonstrate the initialization and cleanup of the `vm.strings` table in `vm.c`. `initTable(&vm.strings)` is called within `_initVM_()` to prepare the table for use, and `freeTable(&vm.strings)` is called in `_freeVM_()` to release its resources when the VM is shut down. ```c void initVM() { initTable(&vm.strings); vm.objects = NULL; } ``` ```c void freeVM() { freeTable(&vm.strings); freeObjects(); } ``` -------------------------------- ### Resolving 'Get' Expressions in LoxResolver Source: https://craftinginterpreters.com/classes Handles the resolution of 'Get' expressions in the Lox resolver. It recursively resolves the object part of the property access but does not resolve the property name itself, as properties are looked up dynamically. This ensures that only the object's structure is checked during the resolution phase. ```Java @Override public Void visitGetExpr(Expr.Get expr) { resolve(expr.object); return null; } ``` -------------------------------- ### Initialize Garbage Collection Function (C) Source: https://craftinginterpreters.com/garbage-collection Provides an empty shell implementation for the `collectGarbage` function in `memory.c`. This serves as a placeholder before the full logic is implemented. ```c void collectGarbage() { } ``` -------------------------------- ### Lox Get and Set Expressions with Dot Syntax Source: https://craftinginterpreters.com/classes-and-instances Demonstrates the usage of dot syntax for accessing and modifying object properties in Lox. This highlights the 'get' and 'set' expressions that allow users to interact with instance state. ```lox eclair.filling = "pastry creme"; print eclair.filling; ``` -------------------------------- ### Hand-Compile Expression to Bytecode (C) Source: https://craftinginterpreters.com/a-virtual-machine Demonstrates hand-compiling a simple expression involving constants and arithmetic operations into Lox bytecode in main.c. It shows the sequence of writing OP_CONSTANT and the constant value, followed by the appropriate arithmetic operation. ```c int constant = addConstant(&chunk, 1.2); writeChunk(&chunk, OP_CONSTANT, 123); writeChunk(&chunk, constant, 123); constant = addConstant(&chunk, 3.4); writeChunk(&chunk, OP_CONSTANT, 123); writeChunk(&chunk, constant, 123); ``` -------------------------------- ### Insert Receiver into CallFrame Slot (Example) Source: https://craftinginterpreters.com/methods-and-initializers This code snippet illustrates how a method call's receiver is inserted into the correct slot in the CallFrame on the stack. It's part of the VM's execution logic for method invocations. ```lox scone.topping("berries", "cream"); ``` -------------------------------- ### Example Usage of Logical NOT (Lox) Source: https://craftinginterpreters.com/types-of-values This snippet shows a basic example of using the logical NOT operator in Lox. Printing '!true' results in 'false', demonstrating the operator's functionality. This code would be compiled and executed by the interpreter. ```lox print !true; ``` -------------------------------- ### Initialize and Execute Bytecode Chunk Source: https://craftinginterpreters.com/a-virtual-machine This snippet shows the sequence of operations to initialize the VM, interpret a given bytecode chunk, and then clean up the VM resources. It is typically called from the main entry point of the program. ```c #include "common.h" #include "chunk.h" #include "vm.h" #include int main() { initVM(); Chunk chunk; initChunk(&chunk); // Add some bytecode here for testing, e.g., OP_RETURN int constant = addConstant(&chunk, 1.2); writeChunk(&chunk, OP_CONSTANT, 123); writeChunk(&chunk, (uint8_t)constant, 123); writeChunk(&chunk, OP_RETURN, 123); disassembleChunk(&chunk, "test chunk"); InterpretResult result = interpret(&chunk); freeChunk(&chunk); if (result == INTERPRET_OK) return 0; return 1; } ``` -------------------------------- ### VM Integration in Main Entrypoint (C) Source: https://craftinginterpreters.com/a-virtual-machine Integrates VM initialization and cleanup into the main function of the interpreter. This ensures the VM is ready before executing code and properly shut down upon exit. It also includes setup for disassembling chunks. ```C int main(int argc, const char* argv[]) { initVM(); Chunk chunk; disassembleChunk(&chunk, "test chunk"); freeVM(); freeChunk(&chunk); } ``` ```C #include "debug.h" #include "vm.h" int main(int argc, const char* argv[]) { ``` -------------------------------- ### Ternary Operator Example Expression Source: https://craftinginterpreters.com/compiling-expressions This is an example of a complex expression that might be used to test parser functionality, particularly involving operator precedence and parsing rules. It includes parentheses, arithmetic operations, and unary negation. ```plaintext (-1 + 2) * 3 - -4 ``` -------------------------------- ### Initialize New Compiler Context (C) Source: https://craftinginterpreters.com/calls-and-functions Initializes a new Compiler instance and sets it as the current compiler. It captures the previous `current` compiler in the `enclosing` field, establishing the link in the compiler stack. This function is called when starting the compilation of a new function. ```c static void initCompiler(Compiler* compiler, FunctionType type) { compiler->enclosing = current; compiler->function = NULL; // ... (rest of initCompiler) } ``` -------------------------------- ### Lox Class Instance Creation with Initializer Call (Java) Source: https://craftinginterpreters.com/classes This Java code snippet shows how a new LoxInstance is created within the 'call' method of LoxClass. It then searches for an 'init' method and, if found, binds it to the instance and invokes it with the provided arguments. This handles the user-defined initialization of a new object. ```java LoxInstance instance = new LoxInstance(this); LoxFunction initializer = findMethod("init"); if (initializer != null) { initializer.bind(instance).call(interpreter, arguments); } return instance; ``` -------------------------------- ### Method Inheritance and Super Call Example (jlox) Source: https://craftinginterpreters.com/superclasses Demonstrates method inheritance and the behavior of super calls within a class structure. This example highlights how `super.method()` in a subclass `B` correctly invokes the `method` from its superclass `A`, even when called on an instance of a further subclass `C`. ```jlox class A { method() { print "A method"; } } class B < A { method() { print "B method"; } test() { super.method(); } } class C < B {} C().test(); ``` -------------------------------- ### Integrating Parser with Lox Main Class (Java) Source: https://craftinginterpreters.com/parsing-expressions This section demonstrates how to integrate the newly implemented `Parser` into the main `Lox.java` class. It involves creating a `Parser` instance, calling its `parse()` method, and then printing the resulting expression tree using `AstPrinter` if no syntax errors occurred. ```java Parser parser = new Parser(tokens); Expr expression = parser.parse(); // Stop if there was a syntax error. if (hadError) return; System.out.println(new AstPrinter().print(expression)); ``` -------------------------------- ### Create LoxClass Instance with Methods (Java) Source: https://craftinginterpreters.com/inheritance Constructs a LoxClass instance, which represents a class in the Lox language. It takes the class name, its superclass (if any), and a map of its methods. The methods' closures capture the correct environment, including the 'super' binding. ```java LoxClass klass = new LoxClass(stmt.name.lexeme, (LoxClass)superclass, methods); ``` -------------------------------- ### Variable Declaration and Scope Example Source: https://craftinginterpreters.com/statements-and-state Demonstrates how local variable declarations within a block can shadow global variables of the same name. After the block exits, the local variable is discarded, and the global variable remains unaffected. This example highlights the need for proper scope management. ```lox // How loud? var volume = 11; // Silence. volume = 0; // Calculate size of 3x4x5 cuboid. { var volume = 3 * 4 * 5; print volume; } ``` -------------------------------- ### Include System Headers for clox (C) Source: https://craftinginterpreters.com/scanning-on-demand Includes standard C library headers required for input/output, memory allocation, string manipulation, and common definitions used throughout the clox project. ```c #include #include #include #include "common.h" #include "vm.h" ``` -------------------------------- ### Lox Function Call and Expression Evaluation Example Source: https://craftinginterpreters.com/a-virtual-machine A complex Lox expression involving nested function calls and arithmetic operations. The example highlights the order of evaluation and the side effects of a function that prints and returns its argument, demonstrating the need for precise value tracking. ```lox fun echo(n) { print n; return n; } print echo(echo(1) + echo(2)) + echo(echo(4) + echo(5)); ``` -------------------------------- ### Implement Instance Creation in C Source: https://craftinginterpreters.com/classes-and-instances Implements the `newInstance` function. This function allocates memory for an `ObjInstance`, sets its class, initializes its fields table, and returns the new instance. ```c #include "memory.h" #include "table.h" #include "value.h" ObjInstance* newInstance(ObjClass* klass) { ObjInstance* instance = ALLOCATE_OBJ(ObjInstance, OBJ_INSTANCE); instance->klass = klass; initTable(&instance->fields); return instance; } ``` -------------------------------- ### Variable Lookup in Chained Environments Source: https://craftinginterpreters.com/statements-and-state Implements the 'get' method in the Environment class to handle variable lookups. If a variable is not found in the current environment, it recursively calls 'get' on the 'enclosing' environment. This process continues until the variable is found or the global scope is reached, throwing an error if undefined. ```java // In class Environment.java, in get() if (enclosing != null) return enclosing.get(name); throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'."); ``` -------------------------------- ### VM: Handling Function Calls in _vm.c_ Source: https://craftinginterpreters.com/calls-and-functions This snippet from _vm.c_ in the _callValue_ function demonstrates how the virtual machine dispatches different object types for function calls. It specifically handles the OBJ_FUNCTION case, delegating the call to a helper function. ```c case OBJ_FUNCTION: return call(AS_FUNCTION(callee), argCount); ``` -------------------------------- ### Closure Implementation and Execution Example Source: https://craftinginterpreters.com/closures This example illustrates the concept of a closure in JavaScript. The 'makeClosure' function creates a local variable 'local' and returns an inner function 'closure' that captures and prints this 'local' variable. When the returned 'closure' is executed, it successfully accesses the 'local' variable from its enclosing scope. ```javascript fun makeClosure() { var local = "local"; fun closure() { print local; } return closure; } var closure = makeClosure(); closure(); ``` -------------------------------- ### Initialize and Disassemble Chunk in C Source: https://craftinginterpreters.com/chunks-of-bytecode Demonstrates the initialization of a chunk, writing an `OP_RETURN` instruction, disassembling the chunk for debugging, and freeing the chunk. It requires `chunk.h` and `debug.h` for chunk operations and disassembling. ```c #include "common.h" #include "chunk.h" #include "debug.h" int main(int argc, const char* argv[]) { Chunk chunk; initChunk(&chunk); writeChunk(&chunk, OP_RETURN); disassembleChunk(&chunk, "test chunk"); freeChunk(&chunk); return 0; } ``` -------------------------------- ### Function Scope and Variable Access Example Source: https://craftinginterpreters.com/closures This example demonstrates a common scoping issue where an inner function, 'inner', attempts to access a variable 'x' declared in an outer scope. Without closure support, it incorrectly accesses the global 'x' instead of the 'outer' scope's 'x'. ```javascript var x = "global"; fun outer() { var x = "outer"; fun inner() { print x; } inner(); } outer(); ``` -------------------------------- ### VM: Initialize and Interpret Function Declarations Source: https://craftinginterpreters.com/scanning-on-demand Declares the function to free the virtual machine and the primary interpret function. The interpret function takes a source code string and returns an interpretation result. ```c void freeVM(); InterpretResult interpret(const char* source); ``` -------------------------------- ### Example Usage of Logical Operators Source: https://craftinginterpreters.com/control-flow Illustrates the short-circuiting behavior of the 'or' operator with different operand types in Lox. ```lox print "hi" or 2; // "hi". print nil or "yes"; // "yes". ``` -------------------------------- ### Compile Function Body and Parameters (C) Source: https://craftinginterpreters.com/calls-and-functions Provides the 'function' helper method to compile the parameters and body of a function. It initializes a new compiler, manages scope, parses the function signature and body, and emits the function object as a constant. ```c static void function(FunctionType type) { Compiler compiler; initCompiler(&compiler, type); beginScope(); consume(TOKEN_LEFT_PAREN, "Expect '(' after function name."); consume(TOKEN_RIGHT_PAREN, "Expect ')' after parameters."); consume(TOKEN_LEFT_BRACE, "Expect '{' before function body."); block(); ObjFunction* function = endCompiler(); emitBytes(OP_CONSTANT, makeConstant(OBJ_VAL(function))); } ``` -------------------------------- ### Number Detection in Scanner (C) Source: https://craftinginterpreters.com/scanning-on-demand Checks if the current character is a digit, used to determine if a lexeme starts a number. ```c if (isDigit(c)) return number(); ``` -------------------------------- ### Identifier Detection in Scanner (C) Source: https://craftinginterpreters.com/scanning-on-demand Checks if the current character is an alphabet character or an underscore, used to determine if a lexeme starts an identifier. ```c if (isAlpha(c)) return identifier(); ```