### Regexp Matching Example (pcomplete.el - Elisp) Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org This Elisp code snippet, likely related to the `pcomplete.el` library, demonstrates a backtracking regular expression matching scenario. It's presented as an example within the context of regexp redesign discussions. ```elisp ;; Example from pcomplete.el, likely related to regexp matching ``` -------------------------------- ### JIT-Capable Format Function Example (Elisp) Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org This Elisp code snippet outlines a potential Just-In-Time (JIT) compilation optimization for the `format` function. The idea is to transform calls like `(format "example: %d" var)` into more efficient concatenations during JIT compilation. ```elisp ;; Conceptual transformation for JIT optimization ;; (format "example: %d" var) => (concat "example" (format-%d var)) ``` -------------------------------- ### JavaScript: Local Variable Slot Allocation Example Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/Notes.org An example demonstrating local variable allocation and slot numbering in JavaScript. This illustrates how variables are assigned numerical slots within a function's scope, a concept relevant to understanding frame-based variable management in JIT compilation. ```javascript function f( a, // slot#0 b, // slot#1 ) { const c = 0; // slot#2 if (a) { let d = 1; // slot#3 b += d + a; } let e = c + b; // slot#4 or slot#3 if reusing slots return e; } ``` -------------------------------- ### Implement 'length' function with multiple specializations in Java Source: https://github.com/gudzpoz/juicemacs/blob/main/CONTRIBUTING.org This example demonstrates how to implement a function ('length') with multiple specializations in Java using Truffle. Each @Specialization method handles a different object type (ELispCons, ELispVectorLike, ELispString) to calculate its size or length. ```java @ELispBuiltIn(name = "length", minArgs = 1, maxArgs = 1) @GenerateNodeFactory public abstract static class FLength extends ELispBuiltInBaseNode { @Specialization public static long lengthCons(ELispCons sequence) { return sequence.size(); } @Specialization public static long lengthVector(ELispVectorLike sequence) { return sequence.size(); } @Specialization public static long lengthString(ELispString sequence) { return sequence.length(); } } ``` -------------------------------- ### Java Example for Lexical Scoping Optimization (Conceptual) Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org Illustrates a conceptual Java code snippet for optimizing lexical scoping in a language interpreter. It shows how a 'let' clause could be compiled into a single stack frame assignment. ```java //while block start ////let block start frame.setSlot(xSlot, resultOfFun); // xSlot: CompilationConstant //... ////let block end //while block end ``` -------------------------------- ### Implementing Emacs Built-ins with Truffle DSL Source: https://context7.com/gudzpoz/juicemacs/llms.txt Shows how to define Emacs built-in functions using Truffle DSL, leveraging type specialization and JIT optimization for improved performance. This example includes specialized and generic methods for addition. ```java import party.iroiro.juicemacs.elisp.forms.ELispBuiltIns; import com.oracle.truffle.api.dsl.*; import party.iroiro.juicemacs.elisp.nodes.ELispExpressionNode; import party.iroiro.juicemacs.elisp.runtime.ELispSignals; import static party.iroiro.juicemacs.elisp.runtime.ELispGlobals.*; public class CustomBuiltIns extends ELispBuiltIns { public CustomBuiltIns() { super(true); } // Simple addition with type specialization @NodeChild(value = "left", type = ELispExpressionNode.class) @NodeChild(value = "right", type = ELispExpressionNode.class) public abstract static class FAdd extends ELispExpressionNode { @Specialization(rewriteOn = ArithmeticException.class) public long addLongs(long left, long right) { return Math.addExact(left, right); } @Specialization public double addDoubles(double left, double right) { return left + right; } @Specialization(replaces = {"addLongs", "addDoubles"}) public Object addGeneric(Object left, Object right) { if (left instanceof Long l && right instanceof Long r) { return l + r; } throw ELispSignals.wrongTypeArgument(NUMBERP, left); } } } ``` -------------------------------- ### Java Example for Current Lexical Scoping Implementation (Conceptual) Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org Presents a conceptual Java code snippet representing the current, less optimized implementation of lexical scoping. This version involves dynamic allocation of lexical scope variables. ```java //... ////let block start ELispLexical lexical = ELispLexical.getLexical(frame); int xSlot = lexical.addVariable(X_SYMBOL); frame.setSlot(xSlot, resultOfFun); ////let block end ``` -------------------------------- ### GraalJS For Loop Node Example Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org A Java code snippet showing how GraalJS handles 'ForNode', which might be relevant for understanding advanced loop and scope management in JavaScript engines. ```java // Java code snippet for GraalJS ForNode would go here if available in the source. ``` -------------------------------- ### Run Juicemacs with Chrome DevTools Protocol Server Source: https://github.com/gudzpoz/juicemacs/blob/main/README.org This command starts the Juicemacs REPL and enables the Chrome DevTools protocol server on port 4242. This allows for debugging and inspection of the running Emacs instance using Chrome's developer tools. ```shell sh -c "cd app && $(./gradlew -q :app:jvmCmd) --inspect=4242" ``` -------------------------------- ### Run Juicemacs REPL with Gradle Source: https://github.com/gudzpoz/juicemacs/blob/main/README.org This command executes the Gradle task `:app:jvmCmd` to start the Juicemacs REPL. It ensures the correct JVM flags for Truffle JIT compilation are applied and sets the working directory to `app/` for hard-coded path resolution. An optional `--help` flag can be used to display available command-line arguments. ```shell sh -c "cd app && $(./gradlew -q :app:jvmCmd)" ``` ```shell sh -c "cd app && $(./gradlew -q :app:jvmCmd) --help" ``` -------------------------------- ### Emacs Lisp: Dynamic Variable Slot Allocation Challenge Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/Notes.org An Emacs Lisp example illustrating the challenge of static analysis for variable slot allocation in dynamic ASTs. The slot number for a variable like 'c' can depend on macro expansion, making it difficult for JIT compilers to cache variable locations reliably. ```elisp (defun f (a ;; slot#0 b ;; slot#1 ) (some-macro ;; the slot of `c' depends on the expansion result of `some-macro' (let ((c 1))))) ``` -------------------------------- ### Juicemacs Buffer Operations with Piece Tree Source: https://context7.com/gudzpoz/juicemacs/llms.txt Java code illustrating buffer manipulation in Juicemacs using its piece tree implementation. Demonstrates inserting text, getting and setting the cursor point, extracting substrings, deleting text ranges, and setting text properties. ```java import party.iroiro.juicemacs.elisp.runtime.objects.ELispBuffer; import party.iroiro.juicemacs.elisp.runtime.string.ELispString; import party.iroiro.juicemacs.piecetree.PieceTreeBase; // Create a new buffer ELispBuffer buffer = new ELispBuffer(new Object[0]); // Insert text at point buffer.setPoint(1L); // 1-based index buffer.insert(ELispString.ofUtf8("Hello, World!")); // Get current point (cursor position) long point = buffer.getPoint(); // => 14 // Extract substring ELispString text = buffer.subString(1L, 6L); // "Hello" // Delete text range buffer.delete(7L, 6L); // Deletes "World!" // Get buffer bounds long min = buffer.pointMin(); // => 1 long max = buffer.pointMax(); // => 8 (after deletion) // Set text properties buffer.putProperty(1L, 6L, intern("face"), intern("bold")); // Get line count int lines = buffer.getLineCount(); // Get character at position int ch = buffer.getChar(1L); // => 'H' ``` -------------------------------- ### Emacs Lisp Function Definition Example Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org Demonstrates how to define a function in Emacs Lisp and inspect its symbol function. With lexical binding enabled, the output changes from a simple lambda to a closure object. ```elisp ;;; -*- lexical-binding: t -*- (defalias 'my-func #'(lambda () 42)) (symbol-function 'my-func) ``` -------------------------------- ### Emacs Buffer-Local Variable Bug Example (Elisp) Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org This Elisp code snippet demonstrates an old Emacs bug related to `let` and buffer-local variables, specifically how setting a buffer-local variable within a `let` block might not behave as expected when the buffer is changed. ```elisp (let ((buffer-file-name "/home/rms/.emacs")) ;; ... (set-buffer other-buffer) ;; ... ) ``` -------------------------------- ### Emacs Bootstrapping Process (pbootstrap and pdump) Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org This outlines the two-stage dumping process in Emacs bootstrapping: 'pbootstrap' for initial compilation and 'pdump' for creating the final executable. It highlights the independence of 'pdump' from 'bootstrap-emacs' and the differing roles of these stages. ```bash # Hypothetical bash commands representing the Emacs bootstrapping stages # Stage 1: pbootstrap - Initial compilation and environment setup echo "Starting pbootstrap..." temacs --load "loadup.el" --eval "(dump-emacs)" --eval "(bootstrap-emacs)" echo "pbootstrap complete." # Expected outcome: Creates .elc files and initial environment # Stage 2: pdump - Creating the final executable from compiled files echo "Starting pdump..." # pdump relies on .elc files generated during pbootstrap # It loads loadup.el (which now uses .elc files) # and dumps the final executable. pdump --load "loadup.el" --eval "(dump-emacs)" echo "pdump complete. Final executable 'emacs' created." ``` -------------------------------- ### Elisp Function Compilation and Interception Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/NativeComp.org Defines a simple Elisp function and intercepts its native compilation. This is a basic example of Elisp code transformation. ```elisp (defun test-func (arg) arg) (pp-intercept-native-compile 'test-func) ``` -------------------------------- ### Running Juicemacs ELisp REPL with Gradle Source: https://context7.com/gudzpoz/juicemacs/llms.txt Commands to run the Juicemacs ELisp REPL using Gradle. Includes options for custom load paths, remote debugging via Chrome DevTools, creating portable dumps, loading from dumps, and compiling to a native image for faster startup. ```bash # Clone and setup cd app sh -c "$(../../gradlew -q :app:jvmCmd)" # With custom load paths sh -c "$(../../gradlew -q :app:jvmCmd) -L/path/to/elisp" # With Chrome DevTools debugger sh -c "$(../../gradlew -q :app:jvmCmd) --inspect=4242" # Create portable dump for fast startup sh -c "$(../../gradlew -q :app:jvmCmd) --dump=pdump" # Load from dump file sh -c "$(../../gradlew -q :app:jvmCmd) --dump-file ./emacs.pdmp" # Compile to native image (fastest startup) ../../gradlew :app:nativeCompile ``` -------------------------------- ### Elisp Pretty Print Bytecode Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/Bytecode.org This Elisp code snippet provides a simple way to pretty-print the entire 'extracted-bytecodes' structure. It's useful for debugging and getting a comprehensive overview of all bytecode information. ```elisp (when (eq output 'print-all) (pp extracted-bytecodes)) ``` -------------------------------- ### JuiceMACs Bytecode Assertions for String Operations Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/Bytecode.org This snippet presents JuiceMACs bytecode assertions for string manipulation. It covers checking if a value is a string, getting substrings, concatenating strings, and comparing strings. ```emacs-lisp (assert-effect '(59) 'byte-stringp '("") '(t)) (assert-effect '(71) 'byte-length '("") '(0)) (assert-effect '(79) 'byte-substring '("str" 1 nil) '("tr")) (assert-effect '(80) 'byte-concat2 '("a" "b") '("ab")) (assert-effect '(81) 'byte-concat3 '("s" "t" "r") '("str")) (assert-effect '(82) 'byte-concat4 '("a" "b" "c" "d") '("abcd")) (assert-effect '(150) 'byte-upcase '("a") '("A")) (assert-effect '(151) 'byte-downcase '("A") '("a")) (assert-effect '(152) 'byte-string= '("abc" "abc") '(t)) (assert-effect '(153) 'byte-string< '("111" "222") '(t)) ``` -------------------------------- ### Execute ERT Tests via Gradle (Bash) Source: https://context7.com/gudzpoz/juicemacs/llms.txt Demonstrates how to run Emacs Lisp Regression Testing (ERT) tests using Gradle commands. This includes running all tests, targeting specific test classes, and compiling to a native image for faster execution. ```bash # Run tests via Gradle ./gradlew :elisp:test # Run specific test class ./gradlew :elisp:test --tests ELispRegressionTest # Run with native image for faster execution ./gradlew :app:nativeCompile ./build/native/nativeCompile/app --batch -l ../test/src/data-tests.el -f ert-run-tests-batch-and-exit ``` -------------------------------- ### Manage Text Properties with Interval Trees (Java) Source: https://context7.com/gudzpoz/juicemacs/llms.txt Demonstrates managing text properties and overlays using interval trees in Java. This includes creating an interval tree, inserting and retrieving properties within specific ranges, and managing overlay intervals. ```java import party.iroiro.juicemacs.piecetree.meta.IntervalPieceTree; import party.iroiro.juicemacs.piecetree.interval.Interval; import party.iroiro.juicemacs.piecetree.interval.IntervalTree; // Create interval tree for text properties IntervalPieceTree intervals = new IntervalPieceTree<>(); // Insert initial interval intervals.insert(0, 100, null); // Entire buffer has no properties // Set property on range intervals.putProperty(10, 10, propertyKey, propertyValue); // Characters 10-20 // Get properties in range intervals.forPropertiesIn(15, 5, true, (props, offset, length) -> { // Process each property interval System.out.printf("Offset: %d, Length: %d, Props: %s%n", offset, length, props); return null; }); // Create overlay tree IntervalTree overlays = new IntervalTree(); Interval overlay = new Interval(10, 20); overlay.put(intern("face"), intern("highlight")); overlays.insert(overlay); // Find overlays at position List found = overlays.findOverlapping(15, 15); for (Interval i : found) { Object face = i.get(intern("face")); } ``` -------------------------------- ### JuiceMACs Bytecode Assertions for Sequence Operations Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/Bytecode.org This code demonstrates JuiceMACs bytecode assertions for sequence operations, including checking for cons cells, getting the car and cdr of a list, and constructing new lists. ```emacs-lisp (assert-effect '(58) 'byte-consp '((t . t)) '(t)) (assert-effect '(64) 'byte-car '((t . nil)) '(t)) (assert-effect '(65) 'byte-cdr '((nil . t)) '(t)) (assert-effect '(66) 'byte-cons '(t nil) '((t . nil))) ``` -------------------------------- ### Emacs Lisp Self-Modifying Function Example Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org This Emacs Lisp snippet defines a function 'self-modifying-f' that demonstrates a potential race condition when accessed concurrently. It uses a local variable 'inner' which is mutated, highlighting the need for careful state management in concurrent scenarios. ```emacs-lisp (defun self-modifying-f (value) (let ((inner '(nil))) (setcar inner value))) ``` -------------------------------- ### Parsing and Evaluating ELisp Code with GraalVM Polyglot Source: https://context7.com/gudzpoz/juicemacs/llms.txt Java code demonstrating how to use GraalVM's Polyglot API to evaluate Emacs Lisp code and parse ELisp source into Truffle AST nodes. It shows context creation with custom environment variables and handling lexical bindings. ```java import party.iroiro.juicemacs.elisp.parser.ELispParser; import party.iroiro.juicemacs.elisp.runtime.ELispContext; import com.oracle.truffle.api.source.Source; import org.graalvm.polyglot.Context; // Create a Polyglot context for ELisp Context context = Context.newBuilder("elisp") .allowExperimentalOptions(true) .environment("EMACSLOADPATH", "/path/to/emacs/lisp") .build(); // Evaluate ELisp code context.eval("elisp", "(+ 1 2 3)"); // => 6 context.eval("elisp", "(cons 'a '(b c))"); // => (a b c) // With lexical binding enabled context.eval("elisp", """ ;;; -*- lexical-binding: t -*- (let ((x 10)) (lambda (y) (+ x y))) """); // Parse source to AST Source source = Source.newBuilder("elisp", "(defun fact (n) (if (<= n 1) 1 (* n (fact (- n 1)))))", "fact.el").build(); ELispContext elispContext = ELispContext.get(null); ELispRootNode root = ELispParser.parse(null, elispContext, source); Object result = root.getCallTarget().call(); // Defines fact function ``` -------------------------------- ### Emacs Lisp Text Insertion and Property Handling Source: https://github.com/gudzpoz/juicemacs/blob/main/commons/piece-tree/README.org Demonstrates how Emacs Lisp handles text insertion with properties, showing how properties are maintained and merged when new text is inserted. This illustrates the behavior relevant to text property management in Emacs buffers. ```elisp (with-temp-buffer (insert #("aa" 1 2 (color red))) ; aa (insert #("cc" 1 2 (color blue))) ; aacc (goto-char 3) (insert "bb") (prin1-to-string (buffer-string))) ; aabbcc ``` -------------------------------- ### Type Checking with instanceof and Pattern Matching in Java Source: https://github.com/gudzpoz/juicemacs/blob/main/CONTRIBUTING.org Demonstrates how to perform type checking for Emacs objects within Java code. It shows the usage of 'instanceof' operator and Java's pattern matching for concisely extracting object types and accessing their methods. ```java if (object instanceof ELispCons cons) { return cons.car(); } switch (object) { case ELispCons cons -> return cons.car(); } ``` -------------------------------- ### Count Emacs Built-in Subroutines (Bash) Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/Status.org Counts the total number of built-in subroutines defined in Emacs C source files. It uses 'grep' to find lines starting with 'DEFUN (' and 'wc' to count them. The output is a single integer representing the total count. ```bash grep -r '^DEFUN ("' ../elisp/emacs/src/*.c | wc --lines ``` -------------------------------- ### Creating ELispCons Objects with Source Location Source: https://github.com/gudzpoz/juicemacs/blob/main/CONTRIBUTING.org Illustrates how to create ELispCons objects, which represent Lisp cons cells. These objects include source location information, essential for stack traces and debugger integration. It also mentions the use of ELispCons.ListBuilder for constructing lists. ```java ELispCons.of(...) ELispCons.ListBuilder ``` -------------------------------- ### Get immediate value from CSTR (Elisp) Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/NativeComp.org This Elisp code retrieves the immediate value from a CSTR object. It requires that the `comp-cstr-imm-vld-p` predicate returns true before calling this function, ensuring that a valid immediate value exists. This is used for accessing constant or direct values within the compilation process. ```elisp =(comp-cstr-imm CSTR)= :: Return the immediate value of CSTR. =comp-cstr-imm-vld-p= *must* be satisfied before calling =comp-cstr-imm=. ``` -------------------------------- ### Callback and Function Call Execution in Juicemacs Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/Notes.org Demonstrates the execution flow for callback nodes and function calls within Juicemacs. It highlights how callback nodes wrap underlying JavaScript function calls and argument creation, illustrating GraalJs's approach to closures by sharing RootNodes and passing extra arguments during function invocation. ```Java callbackNode.apply(index, value, target, callback, callbackThisArg, currentResult) maybeResultNode.apply(index, value, callbackResult, currentResult) callNode.executeCall(JSArguments.create(callbackThisArg, callback, value, boxIndex(index), target)) ``` -------------------------------- ### Implement 'consp' function in Java Source: https://github.com/gudzpoz/juicemacs/blob/main/CONTRIBUTING.org This snippet shows the initial placeholder implementation of the 'consp' function, which is later refined. It uses Truffle annotations for built-in function registration and node factory generation. ```java @ELispBuiltIn(name = "consp", minArgs = 1, maxArgs = 1) @GenerateNodeFactory public abstract static class FConsp extends ELispBuiltInBaseNode { @Specialization public static Void consp(Object object) { throw new UnsupportedOperationException(); } } ``` -------------------------------- ### Extract Compiler Function Documentation and Signatures (Elisp) Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/NativeComp.org This Elisp code snippet processes a list of functions prefixed with 'comp-', extracts their documentation and signatures, and formats them for display. It utilizes `pcase-dolist` to iterate through functions, `symbol-function` and `function-documentation` to get details, and string manipulation for formatting. The output is intended to help understand compiler internals. ```elisp (require 'pcase) (with-temp-buffer (pcase-dolist (`(,n ,name) CALLNI-functions) (when (string-prefix-p "comp-" name) (let* ((symbol (intern-soft name)) (function (symbol-function symbol)) (doc (function-documentation function)) (doc-parts (if doc (string-split doc "\n\n") '("nil" "(fn ...)"))) (doc (string-replace "\n" "\n "(car doc-parts))) (sig (string-replace "fn" name (cadr doc-parts)))) (cl-assert (and symbol function)) (cl-assert (length= doc-parts 2)) (insert (format "- =%s= ::\n %s\n" sig doc))))) (pcase-dolist (`(,regexp . ,replace) '(("`\([A-Za-z-]+\)\'" . "=\1=") ("\n[[:space:]]+" . "\n "))) (goto-char (point-min)) (while (re-search-forward regexp nil t)) (replace-match replace nil nil)) (buffer-string)) ``` -------------------------------- ### Emacs Lisp: Dynamic Argument Handling in Native Compilation Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/NativeComp.org This Emacs Lisp snippet shows the native compilation of a function 'test-func' that accepts a single dynamic argument. The compiler translates the argument access into a 'symbol-value' invocation, indicating how dynamic variable lookups are handled internally during compilation. This is contrasted with lexical argument handling shown in other examples. ```elisp (defun test-func (arg) arg) (pp-intercept-native-compile 'test-func) ``` -------------------------------- ### Truffle Debugging Options Configuration Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/Notes.org A set of options for Truffle context builders used during performance testing. These options enable experimental features, trace compilation, and gather specialization statistics for debugging the GraalVM compiler. ```text .allowExperimentalOptions(true) .option("engine.TraceCompilation", "true") .option("engine.CompilationFailureReaction", "Diagnose") .option("engine.SpecializationStatistics", "true") .option("compiler.TraceMethodExpansion", "truffleTier") ``` -------------------------------- ### Understanding Lisp_Symbol Implementation in JuiceMacs Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org Explains the implementation of Lisp_Symbol (Variables) within JuiceMacs, detailing the various states a symbol can be in, including holding a plain value, pointing to global or buffer-local fields, or aliasing another symbol. It also touches upon the separation of function and value namespaces. ```elisp ;; Understanding Lisp_Symbol (Variables) ;; A symbol can: ;; - Contain a lisp value (plain value symbol) ;; - Point to a field in a global C struct (forward symbol) ;; - Point to a field in a buffer struct (buffer-local symbol) ;; - Contain a user-defined buffer-local symbol (buffer-local symbol) ;; - Point to another symbol (aliased symbol) ;; Lisp functions and values are in different namespaces. ;; In the function namespace, a symbol can: ``` -------------------------------- ### Elisp Function for Compiler Initialization Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/NativeComp.org The 'comp--init-ctxt' function is responsible for acquiring a GCC JIT context, registering emitters, and adding built-in data types. ```elisp (defun comp--final1 () (comp--init-ctxt) (unwind-protect (comp--compile-ctxt-to-file (comp-ctxt-output comp-ctxt)) (comp--release-ctxt))) ``` -------------------------------- ### Function Call Handling in SimpleLanguage using Truffle DSL Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/Notes.org Details how SimpleLanguage handles function calls using SLInvokeNode, which dispatches calls via InteropLibrary. It explains the role of SLFunctionRegistry and SLFunction in mapping names to RootCallTargets and how built-in functions are registered and managed. ```Java // SLInvokeNode corresponds to function call AST node. // It uses InteropLibrary to dispatch calls though. // SLFunctionRegistry: Maps function names to SLFunction objects. // SLFunction wraps a RootCallTarget. // SLBuiltinNode extends SLBuiltinNode (which has the @GenerateNodeFactory annotation and extends SLExpressionNode). // Built-in functions are registered by SLContext::installBuiltins, which in turn calls SLLanguage::lookupBuiltin to setup SLReadArgumentNode and functions. ``` -------------------------------- ### Simulate Concurrent Load in Elisp Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org This Elisp snippet demonstrates a proposed transformation of sequential `load` calls into a concurrent execution model using `parse-cache` and `run-cached`. It aims to parallelize the loading of Elisp files for performance. ```elisp (load "a.el") (load "b.el") ``` ```elisp (concurrent (parse-cache "a.el") (parse-cache "b.el")) (run-cached "a.el") (run-cached "b.el") ``` -------------------------------- ### Configure Truffle Language Options (Java) Source: https://context7.com/gudzpoz/juicemacs/llms.txt Shows how to configure Truffle language options for an Emacs Lisp interpreter using Java. This covers enabling experimental options, setting specific interpreter behaviors like hard exits and debugging metadata, and defining environment variables. ```java import org.graalvm.polyglot.Context; Context context = Context.newBuilder("elisp") .allowExperimentalOptions(true) // Enable hard exits for kill-emacs .option("elisp.hardExit", "true") // Set global variable invalidation threshold .option("elisp.globalVariableMaxInvalidations", "5") // Enable portable dump .option("elisp.portableDump", "pdump") // Load from dump file .option("elisp.dumpFile", "/path/to/emacs.pdmp") // Enable Truffle debugging metadata .option("elisp.truffleDebug", "true") // Convert UnsupportedOperationException to signals .option("elisp.convertUnsupportedException", "true") // Set environment variables .environment("EMACSLOADPATH", "/usr/share/emacs/lisp") .environment("EMACSDATA", "/usr/share/emacs/etc") .build(); ``` -------------------------------- ### Stack Trace Source Position Comparison Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org This snippet highlights a difference in stack trace output, specifically the source position information for root nodes. It shows a scenario where source location info is missing after switching to `load-source-file-function`, potentially due to `eval-buffer`. ```text at /.../Juicemacs/elisp/emacs/lisp/electric.el(Unknown) vs at loadup.el(emacs/lisp/loadup.el:393:0) ``` -------------------------------- ### Emacs Lisp: Decoding and Encoding with ISO-2022-JP Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/Notes.org Demonstrates how Emacs handles character encoding and decoding for the 'iso-2022-jp' charset, illustrating the conversion of bytes to Emacs strings and back. It highlights how Emacs stores non-convertible characters beyond the standard Unicode range. ```elisp (let* (;; 洲﨑神社 if the text were convertible to Unicode (jis-encoded-bytes "\x1b$B='yu?@ #x10FFFF)" non-convertible)))) ``` -------------------------------- ### Symbol Interning and Variable Storage Source: https://context7.com/gudzpoz/juicemacs/llms.txt Illustrates the process of symbol interning and managing variable storage within the ELisp context, including setting and retrieving symbol values, and handling buffer-local variables and function definitions. ```java import party.iroiro.juicemacs.elisp.runtime.ELispContext; import party.iroiro.juicemacs.elisp.runtime.objects.ELispSymbol; import party.iroiro.juicemacs.elisp.runtime.scopes.ValueStorage; // Get context ELispContext context = ELispContext.get(null); // Intern a symbol ELispSymbol sym = context.intern("my-variable"); // Set symbol value context.setValue(sym, 42L); // Get symbol value Object value = context.getValue(sym); // => 42 // Get value storage for buffer-local variables ValueStorage storage = context.getStorage(sym); // Set function definition ELispSymbol funcSym = context.intern("my-function"); context.getFunctionStorage(funcSym).set(lambdaObject); // Check if symbol is nil or t boolean isNil = sym == context.intern("nil"); boolean isT = sym == context.intern("t"); ``` -------------------------------- ### Let and Let* Handling in JuiceMacs Source: https://github.com/gudzpoz/juicemacs/blob/main/docs/TODO.org This snippet addresses the handling of `let` and `let*` forms in JuiceMacs. It notes that dynamic binding is not yet handled and that 'special == true' symbols under lexical scoping still need to be managed. It also clarifies that 'special == true' does not apply to function arguments. ```elisp ;; Dynamic binding not handled yet. ;; Need to handle 'special == true' symbols under lexical scoping. ;; 'special == true' does not apply to function arguments. ``` -------------------------------- ### Refine 'consp' function implementation in Java (Diff) Source: https://github.com/gudzpoz/juicemacs/blob/main/CONTRIBUTING.org This diff illustrates the refined implementation of the 'consp' function, changing the return type and adding logic to check if an object is an instance of ELispCons. This shows a common pattern of modifying placeholder implementations. ```diff @ELispBuiltIn(name = "consp", minArgs = 1, maxArgs = 1) @GenerateNodeFactory public abstract static class FConsp extends ELispBuiltInBaseNode { @Specialization - public static Void consp(Object object) { - throw new UnsupportedOperationException(); + public static boolean consp(Object object) { + return object instanceof ELispCons; } } ``` -------------------------------- ### Compile Juicemacs Native Image Source: https://github.com/gudzpoz/juicemacs/blob/main/README.org This command compiles Juicemacs into a native image using Gradle. Native images generally offer faster startup times and improved performance, especially for features like pdump. ```shell ./gradlew :app:nativeCompile ``` -------------------------------- ### Implement AST-Level Inlining for Functions in Java Source: https://github.com/gudzpoz/juicemacs/blob/main/CONTRIBUTING.org This Java code snippet demonstrates how to implement the InlineFactory interface for a function to support AST-level inlining. It shows handling of different argument counts for an addition function, returning ELispExpressionNode instances for inlined execution. ```java @ELispBuiltIn(name = "+", minArgs = 0, maxArgs = 0, varArgs = true) @GenerateNodeFactory public abstract static class FPlus extends ELispBuiltInBaseNode implements ELispBuiltInBaseNode.InlineFactory { // ... @Override public ELispExpressionNode createNode(ELispExpressionNode[] arguments) { if (arguments.length == 0) { // (+) -> 0 return ELispLiteralNodes.of(0L); } if (arguments.length == 1) { // (+ num) -> num return BuiltInDataFactory.NumberAsIsUnaryNodeGen.create(arguments[0]); } // (+ a b c) -> ((a + b) + c) return varArgsToBinary(arguments, 0, BuiltInDataFactory.FPlusBinaryNodeGen::create); } } ``` -------------------------------- ### Run ERT Tests for Emacs Lisp (Elisp) Source: https://context7.com/gudzpoz/juicemacs/llms.txt Provides Elisp code to execute the Emacs Lisp Regression Testing (ERT) suite. It includes workarounds for unimplemented functions, loading the ERT framework and test files, and running tests in batch mode. ```elisp ;; Workaround for unimplemented functions (require 'pp) (defalias 'pp 'princ) (defun cl--assertion-failed (&rest _) t) ;; Load ERT framework (require 'ert) ;; Load test file (load "../test/src/data-tests") ;; Run tests in batch mode (ert-run-tests-batch) ;; Evaluate without printing huge info object (null (ert-run-tests-batch)) ```