### Developer Setup for OpenSCAD Tree-Sitter Project Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/_media/README.md Commands for cloning the repository, installing dependencies, building packages, running tests, and starting development mode for contributors. ```bash # Clone the repository git clone https://github.com/user/openscad-tree-sitter.git cd openscad-tree-sitter # Install dependencies (requires Node.js 22+ and PNPM 10+) pnpm install # Build all packages pnpm build # Run tests pnpm test # Start development mode pnpm dev ``` -------------------------------- ### Setting Up Local Development for OpenSCAD Demo Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-demo/README.md Instructions to clone the repository, install dependencies, and start the OpenSCAD demo application locally. This allows developers to run and test the application on their machine. ```bash # Clone the repository git clone https://github.com/user/openscad-tree-sitter.git cd openscad-tree-sitter # Install dependencies pnpm install # Start the demo application pnpm dev:demo # Or run from the demo package directory cd packages/openscad-demo pnpm dev ``` -------------------------------- ### Set Up OpenSCAD Parser Development Environment Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/README.md Steps for developers to clone the repository, install dependencies, build packages, run tests, and start development mode for contributing. Requires Node.js 22+ and PNPM 10+. ```bash # Clone the repository git clone https://github.com/user/openscad-tree-sitter.git cd openscad-tree-sitter # Install dependencies (requires Node.js 22+ and PNPM 10+) pnpm install # Build all packages pnpm build # Run tests pnpm test # Start development mode pnpm dev ``` -------------------------------- ### OpenSCAD Basic Code Examples Array Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-demo/README.md Provides a TypeScript array of basic OpenSCAD code examples, including simple primitives and transformations. Each example has a name, description, and the OpenSCAD code snippet itself. ```typescript const basicExamples = [ { name: 'Hello Cube', description: 'Simple cube primitive', code: 'cube(10);', category: 'primitives' }, { name: 'Colored Sphere', description: 'Sphere with color transformation', code: 'color("red") sphere(5);', category: 'transformations' } ]; ``` -------------------------------- ### Install OpenSCAD Parser Package Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/README.md Instructions for installing the `@openscad/parser` package using npm, pnpm, or yarn. ```bash # Using npm npm install @openscad/parser # Using pnpm pnpm add @openscad/parser # Using yarn yarn add @openscad/parser ``` -------------------------------- ### Install OpenSCAD Parser Package Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/README.md Instructions to install the `@openscad/parser` package using npm or pnpm, enabling its use in projects. ```bash # Install the parser package npm install @openscad/parser # Or with pnpm pnpm add @openscad/parser ``` -------------------------------- ### Example: Basic SourceLocation for a single line Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/interfaces/SourceLocation.md Demonstrates the structure of a `SourceLocation` object for a single-line code snippet, including start and end positions and the associated text. ```typescript const location: SourceLocation = { start: { line: 1, column: 0, offset: 0 }, end: { line: 1, column: 8, offset: 8 }, text: 'cube(10)' }; ``` -------------------------------- ### Writing Unit Tests for OpenSCAD Parser Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/README.md Demonstrates how to write unit tests for the `OpenSCAD Parser` using `vitest`. The examples show testing module definitions and gracefully handling syntax errors, including setup and teardown using `beforeEach` and `afterEach` hooks for parser initialization and disposal. ```typescript import { OpenscadParser } from '@openscad/parser'; import { describe, it, expect, beforeEach, afterEach } from 'vitest'; describe('OpenSCAD Parser', () => { let parser: EnhancedOpenscadParser; beforeEach(async () => { parser = new EnhancedOpenscadParser(); await parser.init('./tree-sitter-openscad.wasm'); }); afterEach(() => { parser.dispose(); }); it('should parse module definitions', () => { const code = ` module test_module(size = 10) { cube(size); } `; const ast = parser.parseAST(code); expect(ast).toHaveLength(1); expect(ast[0].type).toBe('module_definition'); expect(ast[0].name).toBe('test_module'); }); it('should handle syntax errors gracefully', () => { const code = ` module invalid_syntax( cube(10); } `; const ast = parser.parseAST(code); const errors = parser.getErrors(); expect(errors.length).toBeGreaterThan(0); expect(errors[0].type).toBe('SYNTAX_ERROR'); }); }); ``` -------------------------------- ### OpenSCAD Advanced Code Examples Array Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-demo/README.md Showcases a TypeScript array of advanced OpenSCAD code examples, featuring recursive modules for complex structures like fractal trees. Each example provides a name, description, and the OpenSCAD code. ```typescript const advancedExamples = [ { name: 'Recursive Tree', description: 'Recursive module creating a fractal tree', code: "\n module tree(size, levels) {\n if (levels > 0) {\n cylinder(h = size, r1 = size/10, r2 = size/20);\n translate([0, 0, size]) {\n for (angle = [0:45:359]) {\n rotate([20, 0, angle]) {\n tree(size * 0.6, levels - 1);\n }\n }\n }\n }\n }\n tree(50, 4);\n ", category: 'advanced' } ]; ``` -------------------------------- ### Install OpenSCAD Parser Package Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/_media/README.md Instructions to install the OpenSCAD parser package using npm or pnpm for user applications. ```bash # Install the parser package npm install @openscad/parser # Or with pnpm pnpm add @openscad/parser ``` -------------------------------- ### Install OpenSCAD Editor and Monaco Editor Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-editor/README.md Instructions for installing the @openscad/editor package along with monaco-editor using npm, pnpm, or yarn. ```bash # Using npm npm install @openscad/editor monaco-editor # Using pnpm pnpm add @openscad/editor monaco-editor # Using yarn yarn add @openscad/editor monaco-editor ``` -------------------------------- ### Install OpenSCAD Parser Package Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/README.md Instructions for installing the @openscad/parser package using popular Node.js package managers: npm, pnpm, and yarn. ```bash # Using npm npm install @openscad/parser # Using pnpm pnpm add @openscad/parser # Using yarn yarn add @openscad/parser ``` -------------------------------- ### Install Tree-sitter OpenSCAD WASM Build Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/README.md Command to install the WebAssembly (WASM) build of the Tree-sitter OpenSCAD grammar, suitable for web environments. ```bash npm install @openscad/tree-sitter-openscad/wasm ``` -------------------------------- ### Install Tree-sitter OpenSCAD Grammar via NPM/PNPM/Yarn Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/README.md Instructions for installing the Tree-sitter OpenSCAD grammar using popular Node.js package managers like npm, pnpm, and yarn. ```bash # Using npm npm install @openscad/tree-sitter-openscad # Using pnpm pnpm add @openscad/tree-sitter-openscad # Using yarn yarn add @openscad/tree-sitter-openscad ``` -------------------------------- ### OpenSCAD Intermediate Code Examples Array Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-demo/README.md Presents a TypeScript array of intermediate OpenSCAD code examples, demonstrating parametric modules. Each entry includes a name, description, and the OpenSCAD module definition. ```typescript const intermediateExamples = [ { name: 'Parametric Module', description: 'Module with parameters and default values', code: "\n module house(width = 10, height = 15) {\n cube([width, width, height]);\n translate([0, 0, height]) {\n rotate([0, 45, 0]) cube([width*1.4, width, 2]);\n }\n }\n house(20, 25);\n ", category: 'modules' } ]; ``` -------------------------------- ### TypeScript Example Item Structure for OpenSCAD Demo Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-demo/README.md Illustrates the TypeScript structure for adding new examples to the OpenSCAD demo, including properties like ID, name, description, category, difficulty, and the OpenSCAD code itself, along with tags and author information. ```typescript // Add to src/examples/index.ts export const newExample: ExampleItem = { id: 'new-example', name: 'New Example', description: 'Description of the new example', category: 'category', difficulty: 'beginner' | 'intermediate' | 'advanced', code: ` // OpenSCAD code here `, tags: ['tag1', 'tag2'], author: 'Your Name', dateAdded: '2024-01-01' }; ``` -------------------------------- ### Install OpenSCAD Parser using npm Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/README.md This command installs the OpenSCAD Parser package from npm, making it available for use in your project. ```bash npm install @openscad/parser ``` -------------------------------- ### Performing Basic Arithmetic Operations in OpenSCAD Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/test/corpus/comprehensive-basic.txt Provides examples of fundamental arithmetic operations in OpenSCAD, including addition, subtraction, multiplication, division, modulo, and exponentiation. ```OpenSCAD result1 = 1 + 2; result2 = 5 - 3; result3 = 4 * 6; result4 = 8 / 2; result5 = 7 % 3; result6 = 2 ^ 3; ``` ```Tree-sitter Parse Tree (source_file (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (addition_operator) right: (number)))) (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (subtraction_operator) right: (number)))) (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (multiplication_operator) right: (number)))) (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (division_operator) right: (number)))) (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (modulo_operator) right: (number)))) (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (exponentiation_operator) right: (number))))) ``` -------------------------------- ### OpenSCAD RangeExpressionVisitor Testing Setup Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/range-expression-visitor.md Illustrates the standard testing setup for the RangeExpressionVisitor using the 'Real Parser Pattern'. This includes initializing the OpenSCADParser and RangeExpressionVisitor, along with an ErrorHandler, before each test, and disposing of the parser afterwards. ```typescript describe('RangeExpressionVisitor', () => { let parser: OpenSCADParser; let visitor: RangeExpressionVisitor; let errorHandler: ErrorHandler; beforeEach(async () => { parser = new OpenSCADParser(); await parser.init(); errorHandler = new ErrorHandler(); visitor = new RangeExpressionVisitor('', errorHandler); }); afterEach(() => { parser.dispose(); }); }); ``` -------------------------------- ### OpenSCAD: Defining Custom Functions Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/test/corpus/comprehensive-basic.txt Shows examples of defining simple functions in OpenSCAD, such as `double()` for multiplication and `add()` for addition. The Tree-sitter parse tree representation for these function definitions is included, demonstrating how function names, parameters, and expressions are structured. ```OpenSCAD function double(x) = x * 2; function add(a, b) = a + b; ``` ```APIDOC (source_file (statement (function_definition name: (identifier) parameters: (parameter_list (parameter_declarations (parameter_declaration (identifier)))) value: (binary_expression left: (identifier) operator: (multiplication_operator) right: (number)))) (statement (function_definition name: (identifier) parameters: (parameter_list (parameter_declarations (parameter_declaration (identifier)) (parameter_declaration (identifier)))) value: (binary_expression left: (identifier) operator: (addition_operator) right: (identifier))))) ``` -------------------------------- ### Building and Previewing OpenSCAD Demo for Production Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-demo/README.md Steps to build the OpenSCAD demo application for production deployment and preview the optimized build. This prepares the application for live environments. ```bash # Build the demo application pnpm build:demo # Preview the production build pnpm preview:demo # Or from the demo package directory cd packages/openscad-demo pnpm build pnpm preview ``` -------------------------------- ### TypeScript Examples: Using pointToPosition Function Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/functions/pointToPosition.md Illustrates various use cases of the `pointToPosition` function in TypeScript. Examples include converting a node's start position, logging error locations with adjusted line/column numbers, and defining an AST range using start and end positions. ```typescript // Convert Tree-sitter point to AST position const position = pointToPosition(node.startPosition, 150); // Returns: { line: 10, column: 5, offset: 150 } ``` ```typescript const errorPosition = pointToPosition(errorNode.startPosition, errorNode.startIndex); console.log(`Error at line ${errorPosition.line + 1}, column ${errorPosition.column + 1}`); ``` ```typescript const startPos = pointToPosition(node.startPosition, node.startIndex); const endPos = pointToPosition(node.endPosition, node.endIndex); const range = { start: startPos, end: endPos }; ``` -------------------------------- ### Example: SourceLocation for multi-line code Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/interfaces/SourceLocation.md Illustrates how `SourceLocation` captures position information for a multi-line code block, showing the start and end positions across multiple lines. ```typescript const multiLineLocation: SourceLocation = { start: { line: 1, column: 0, offset: 0 }, end: { line: 3, column: 1, offset: 25 }, text: 'difference() {\n cube(10);\n}' }; ``` -------------------------------- ### Bash Commands for Manual OpenSCAD Demo Deployment Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-demo/README.md Shows basic Bash commands for building the OpenSCAD demo for production and indicates where the compiled files will be located for manual deployment to a custom hosting provider. ```bash # Build for production pnpm build:demo # Deploy to your hosting provider # The built files will be in packages/openscad-demo/dist/ ``` -------------------------------- ### Netlify Configuration for OpenSCAD Demo Deployment Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-demo/README.md Provides the `netlify.toml` configuration file for automatic deployment of the OpenSCAD demo to Netlify, specifying build commands, publish directory, environment variables, and a redirect rule for single-page application routing. ```yaml # netlify.toml [build] base = "packages/openscad-demo" command = "pnpm build" publish = "dist" [build.environment] NODE_VERSION = "22" PNPM_VERSION = "10" [[redirects]] from = "/*" to = "/index.html" status = 200 ``` -------------------------------- ### Get string representation of NodeLocation in TypeScript Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/classes/NodeLocation.md This example demonstrates how to use the NodeLocation.toString() method to obtain a formatted string representation of a NodeLocation instance, typically used for logging or debugging. ```typescript const location = new NodeLocation( { row: 1, column: 5 }, { row: 1, column: 10 }, 5, 10 ); console.log(location.toString()); // "1:5-1:10 (5-10)" ``` -------------------------------- ### Bash Commands for OpenSCAD Demo Development Workflow Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-demo/README.md Lists common `pnpm` commands for local development of the OpenSCAD demo, including starting the development server, running tests, linting, type checking, and building for production. ```bash # Start development server pnpm dev # Run tests pnpm test # Run linting pnpm lint # Type checking pnpm typecheck # Build for production pnpm build ``` -------------------------------- ### Get Source Range of an AST Node Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/interfaces/PositionUtilities.md Retrieves the precise source code range (start and end positions) for a given Abstract Syntax Tree (AST) node. This is useful for highlighting code or determining the extent of a parsed element. ```APIDOC getNodeRange(node: ASTNode): SourceRange node: ASTNode - The AST node to get the range for. Returns: SourceRange - The source range of the node. ``` -------------------------------- ### Adding New Features to OpenSCAD Tree-sitter Grammar Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/README.md Provides a guide for extending the OpenSCAD Tree-sitter grammar by modifying `grammar.js`, adding tests, updating query files, regenerating the parser, and verifying changes. Includes an example of defining a new feature rule. ```JavaScript // In grammar.js new_feature: $ => seq( 'new_keyword', field('parameter', $.expression), field('body', $.block_statement) ), ``` -------------------------------- ### Dockerfile for OpenSCAD Demo Containerization Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-demo/README.md Provides a multi-stage Dockerfile for building and serving the OpenSCAD demo application. It sets up a Node.js environment for building the application and then uses Nginx to serve the static files efficiently. ```dockerfile # Dockerfile FROM node:22-alpine WORKDIR /app # Copy package files COPY package.json pnpm-lock.yaml ./ COPY packages/openscad-demo/package.json ./packages/openscad-demo/ # Install dependencies RUN npm install -g pnpm RUN pnpm install --frozen-lockfile # Copy source code COPY packages/openscad-demo ./packages/openscad-demo # Build the application RUN pnpm build:demo # Serve with nginx FROM nginx:alpine COPY --from=0 /app/packages/openscad-demo/dist /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] ``` -------------------------------- ### Demonstrate Error Recovery in OpenSCAD Parser Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/error-handling.md This TypeScript example illustrates how the OpenSCAD parser attempts to recover from syntax errors, allowing it to continue processing the input. It shows the setup of an `EnhancedOpenscadParser` with an error handler, parsing code containing both valid and invalid syntax, and then inspecting the generated AST and collected errors. ```typescript const errorHandler = new SimpleErrorHandler(); const parser = new EnhancedOpenscadParser(errorHandler); await parser.init(); const codeWithErrors = ` cube(10); // Valid sphere([5, 10); // Error: invalid sphere parameters cylinder(h=20, r=5); // Valid - parser recovers `; const ast = parser.parseAST(codeWithErrors); // AST may contain partial results console.log(`Generated ${ast.length} AST nodes`); // Check errors const errors = errorHandler.getErrors(); console.log(`Found ${errors.length} errors`); errors.forEach(error => { console.log(`Error: ${error.message} at line ${error.line}`); }); ``` -------------------------------- ### Performing Incremental Parsing for Code Edits in TypeScript Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/parser.md This example illustrates how to use incremental parsing with updateAST() for small changes in existing code, which is significantly faster than re-parsing the entire file. It shows how to provide the updated code along with the start and end indices of the changed segment to efficiently update the Abstract Syntax Tree (AST). ```typescript // Assume 'parser' is an initialized EnhancedOpenscadParser instance const originalCode = 'cube(10);'; parser.parseAST(originalCode); // Initial parse const updatedCode = 'cube(20);'; // User changes '10' to '20' const startIndex = originalCode.indexOf('10'); const oldEndIndex = startIndex + 2; const newEndIndex = startIndex + 2; // Use incremental update for the AST const updatedAST = parser.updateAST(updatedCode, startIndex, oldEndIndex, newEndIndex); ``` -------------------------------- ### OpenSCAD Library and Module Usage Example Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/test/corpus/real-world.txt Demonstrates fundamental OpenSCAD practices including importing external libraries using `use` and `include`, defining variables, and instantiating a custom module `roundedBox` with specific dimensions and parameters. ```OpenSCAD use ; include ; box_width = 50; box_height = 30; wall_thickness = 2; roundedBox([box_width, box_height, 20], wall_thickness, true); ``` -------------------------------- ### OpenSCAD Original Assign Statement Examples Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/_media/ast-types.md Provides examples of the `assign()` statement as used in OpenSCAD, demonstrating single and multiple variable assignments, and scoping a block of code. These examples serve as context for understanding the AST representations. ```openscad assign(x = 5) cube(x); assign(x = 5, y = 10) cube([x, y, 1]); assign(r = 10) { sphere(r); translate([r*2, 0, 0]) sphere(r); } ``` -------------------------------- ### EnhancedOpenscadParser.init Method API Reference Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/parser.md Describes the `init` method of `EnhancedOpenscadParser`, responsible for asynchronously loading the necessary WASM grammars for OpenSCAD and Tree-sitter. It accepts optional paths for these WASM files. ```APIDOC EnhancedOpenscadParser.init: init(wasmPath?: string, treeSitterWasmPath?: string): Promise wasmPath: (optional) Path to the OpenSCAD WASM grammar treeSitterWasmPath: (optional) Path to the Tree-sitter WASM module ``` -------------------------------- ### Performing Basic Comparisons in OpenSCAD Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/test/corpus/comprehensive-basic.txt Illustrates common comparison operators in OpenSCAD, such as greater than, less than, greater than or equal to, less than or equal to, equality, and inequality. ```OpenSCAD comp1 = 5 > 3; comp2 = 2 < 7; comp3 = 4 >= 4; comp4 = 6 <= 8; comp5 = 1 == 1; comp6 = 2 != 3; ``` ```Tree-sitter Parse Tree (source_file (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (greater_than_operator) right: (number)))) (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (less_than_operator) right: (number)))) (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (greater_equal_operator) right: (number)))) (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (less_equal_operator) right: (number)))) (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (equality_operator) right: (number)))) (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (inequality_operator) right: (number))))) ``` -------------------------------- ### Build OpenSCAD Tree-Sitter Packages Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/_media/README.md Commands to build all packages in the monorepo or specific packages like parser, grammar, or editor. ```bash # Build all packages pnpm build # Build specific package pnpm build:parser pnpm build:grammar pnpm build:editor ``` -------------------------------- ### OpenSCAD CylinderNode AST Example Structures Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/ast-types.md Illustrative examples of `CylinderNode` AST objects corresponding to various OpenSCAD `cylinder()` primitive calls. These examples demonstrate how different parameter combinations map to the structured AST representation, including height, radii, diameters, and centering. ```typescript // For: cylinder(h=10, r=5, center=true); // AST Node: { type: 'cylinder', h: 10, r: 5, center: true } // For: cylinder(h=20, r1=8, r2=12, $fn=50); // AST Node: { type: 'cylinder', h: 20, r1: 8, r2: 12, $fn: 50 // center would be undefined (meaning false by OpenSCAD default) } // For: cylinder(15, d1=10, d2=5); // Positional height // AST Node: { type: 'cylinder', h: 15, d1: 10, d2: 5 } ``` -------------------------------- ### Building OpenSCAD Tree-sitter Grammar from Source Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/README.md Provides a sequence of shell commands to set up the development environment, clone the repository, install dependencies, generate the parser, run tests, build WASM and native bindings, and parse specific files for the OpenSCAD Tree-sitter grammar. ```Bash # Clone the repository git clone https://github.com/openscad/tree-sitter-openscad.git cd tree-sitter-openscad # Install dependencies (from root of monorepo) pnpm install # Generate the parser nx generate-grammar tree-sitter-openscad # Run tests nx test tree-sitter-openscad # Build WASM version nx build:wasm tree-sitter-openscad # Build native bindings nx build:native tree-sitter-openscad # Parse specific files nx parse tree-sitter-openscad -- examples/sample.scad # Launch playground nx playground tree-sitter-openscad ``` -------------------------------- ### SquareNode Usage Examples Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/ast-types.md Examples demonstrating how SquareNode objects are structured in the AST for different OpenSCAD `square()` calls, showing variations for size and centering. ```json // For: square(10); { "type": "square", "size": 10 // center would be undefined (false by default) } // For: square([10, 20], center=true); { "type": "square", "size": [10, 20], // This is a Vector2D "center": true } ``` -------------------------------- ### Configure and Build Tree-sitter OpenSCAD Grammar with CMake Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/CMakeLists.txt This CMakeLists.txt file defines the build process for the `tree-sitter-openscad` grammar. It sets the project version, description, and homepage, defines build options like `BUILD_SHARED_LIBS` and `TREE_SITTER_REUSE_ALLOCATOR`, and enforces the Tree-sitter ABI version. It includes custom commands to generate `parser.c` from `grammar.json` using the `tree-sitter` CLI, compiles the grammar into a shared library, and handles the installation of headers, the pkg-config file, the library itself, and query files. A custom target for running Tree-sitter tests is also included. ```CMake cmake_minimum_required(VERSION 3.13) project(tree-sitter-openscad VERSION "0.1.0" DESCRIPTION "Tree-sitter grammar for OpenSCAD" HOMEPAGE_URL "https://github.com/tree-sitter/tree-sitter-openscad" LANGUAGES C) option(BUILD_SHARED_LIBS "Build using shared libraries" ON) option(TREE_SITTER_REUSE_ALLOCATOR "Reuse the library allocator" OFF) set(TREE_SITTER_ABI_VERSION 15 CACHE STRING "Tree-sitter ABI version") if(NOT ${TREE_SITTER_ABI_VERSION} MATCHES "^[0-9]+$") unset(TREE_SITTER_ABI_VERSION CACHE) message(FATAL_ERROR "TREE_SITTER_ABI_VERSION must be an integer") endif() find_program(TREE_SITTER_CLI tree-sitter DOC "Tree-sitter CLI") add_custom_command(OUTPUT "${CMAKE_CURRENT_SOURCE_DIR}/src/parser.c" DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/grammar.json" COMMAND "${TREE_SITTER_CLI}" generate src/grammar.json --abi=${TREE_SITTER_ABI_VERSION} WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" COMMENT "Generating parser.c") add_library(tree-sitter-openscad src/parser.c) if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/src/scanner.c) target_sources(tree-sitter-openscad PRIVATE src/scanner.c) endif() target_include_directories(tree-sitter-openscad PRIVATE src INTERFACE $ $) target_compile_definitions(tree-sitter-openscad PRIVATE $<$:TREE_SITTER_REUSE_ALLOCATOR> $<$:TREE_SITTER_DEBUG>) set_target_properties(tree-sitter-openscad PROPERTIES C_STANDARD 11 POSITION_INDEPENDENT_CODE ON SOVERSION "${TREE_SITTER_ABI_VERSION}.${PROJECT_VERSION_MAJOR}" DEFINE_SYMBOL "") configure_file(bindings/c/tree-sitter-openscad.pc.in "${CMAKE_CURRENT_BINARY_DIR}/tree-sitter-openscad.pc" @ONLY) include(GNUInstallDirs) install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/bindings/c/tree_sitter" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" FILES_MATCHING PATTERN "*.h") install(FILES "${CMAKE_CURRENT_BINARY_DIR}/tree-sitter-openscad.pc" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig") install(TARGETS tree-sitter-openscad LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") file(GLOB QUERIES queries/*.scm) install(FILES ${QUERIES} DESTINATION "${CMAKE_INSTALL_DATADIR}/tree-sitter/queries/openscad") add_custom_target(ts-test "${TREE_SITTER_CLI}" test WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" COMMENT "tree-sitter test") ``` -------------------------------- ### OpenSCAD Basic Cube Primitive Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/test/corpus/comprehensive-basic.txt Demonstrates different ways to instantiate a cube in OpenSCAD, using single size, vector size, named size, and combined size with centering. The Tree-sitter parse tree shows the module instantiation structure for each variation. ```OpenSCAD cube(10); cube([5, 10, 15]); cube(size=20); cube(size=[1,2,3], center=true); ``` ```Tree-sitter (source_file (statement (module_instantiation name: (identifier) arguments: (argument_list (arguments (argument (number)))))) (statement (module_instantiation name: (identifier) arguments: (argument_list (arguments (argument (vector_expression (number) (number) (number))))))) (statement (module_instantiation name: (identifier) arguments: (argument_list (arguments (argument name: (identifier) value: (number)))))) (statement (module_instantiation name: (identifier) arguments: (argument_list (arguments (argument name: (identifier) value: (vector_expression (number) (number) (number))) (argument name: (identifier) value: (boolean))))))) ``` -------------------------------- ### OpenSCAD: Defining Modules with and without Parameters Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/test/corpus/comprehensive-basic.txt Illustrates how to define reusable modules in OpenSCAD, including a basic module without parameters and one with a default parameter. The corresponding Tree-sitter parse tree structures for module definitions are also provided, showing how parameters and their default values are parsed. ```OpenSCAD module simple() { cube(10); } module with_params(size=5) { sphere(size); } ``` ```APIDOC (source_file (statement (module_definition name: (identifier) parameters: (parameter_list) body: (block (statement (module_instantiation name: (identifier) arguments: (argument_list (arguments (argument (number))))))))) (statement (module_definition name: (identifier) parameters: (parameter_list (parameter_declarations (parameter_declaration (identifier) (number)))) body: (block (statement (module_instantiation name: (identifier) arguments: (argument_list (arguments (argument (identifier)))))))))) ``` -------------------------------- ### PolygonNode Usage Examples Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/ast-types.md Examples demonstrating how PolygonNode objects are structured in the AST for different OpenSCAD `polygon()` calls, including simple polygons and those with explicitly defined paths. ```json // For: polygon(points=[[0,0],[10,0],[5,10]]); { "type": "polygon", "points": [[0,0],[10,0],[5,10]] // Each inner array is a Vector2D } // For: polygon(points=[[0,0],[100,0],[100,100],[0,100]], paths=[[0,1,2,3]]); // (Explicitly defining a single path) { "type": "polygon", "points": [[0,0],[100,0],[100,100],[0,100]], "paths": [[0,1,2,3]] } ``` -------------------------------- ### CircleNode Usage Examples Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/ast-types.md Examples demonstrating how CircleNode objects are structured in the AST for different OpenSCAD `circle()` calls, including positional arguments and explicit parameter assignments. ```json // For: circle(10); // Positional argument implies radius // AST Node: { "type": "circle", "r": 10, "location": { "start": { "line": 0, "column": 0, "offset": 0 }, "end": { "line": 0, "column": 10, "offset": 10 } } // Example location } // For: circle(d=20, $fn=50); // AST Node: { "type": "circle", "d": 20, "$fn": 50, "location": { "start": { "line": 1, "column": 0, "offset": 11 }, "end": { "line": 1, "column": 21, "offset": 32 } } // Example location } ``` -------------------------------- ### Running Tests for Tree-sitter Cursor Utilities with pnpm Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/src/lib/openscad-parser/cst/cursor-utils/README.md Provides the command-line instruction to execute the test suite for the cursor utility module using the pnpm package manager. ```bash pnpm test ``` -------------------------------- ### UnionNode AST Interface and Example Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/_media/ast-types.md Documents the `UnionNode` which represents the `union()` boolean operation in OpenSCAD, combining all child geometries. Includes its TypeScript interface and an example AST representation. ```typescript interface UnionNode extends BaseNode { type: 'union'; children: ASTNode[]; // An array of child nodes to be combined } ``` ```json // For: union() { cube(10); sphere(5); } { type: 'union', children: [ { type: 'cube', size: { type: 'literal', value: 10 } /* ... other cube props ... */ }, { type: 'sphere', r: 5, // SphereNode.r is number location: { /*...*/ } } ] } ``` ```APIDOC UnionNode Properties: - type: Always 'union'. - children: An array of ASTNode elements whose geometries are to be combined. ``` -------------------------------- ### Assigning Simple Strings in OpenSCAD Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/test/corpus/comprehensive-basic.txt Illustrates the declaration and assignment of string literals, including empty strings and strings containing spaces, in OpenSCAD. ```OpenSCAD str1 = "hello"; str2 = "world with spaces"; str3 = ""; ``` ```Tree-sitter Parse Tree (source_file (statement (assignment_statement name: (identifier) value: (string))) (statement (assignment_statement name: (identifier) value: (string))) (statement (assignment_statement name: (identifier) value: (string)))) ``` -------------------------------- ### OpenSCAD Echo Statement Usage Examples Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/_media/ast-types.md Provides original OpenSCAD code snippets illustrating the use of the `echo()` statement for logging and debugging, including examples with no arguments and multiple arguments. ```openscad echo(); echo("Demo", myVar, value * 2); ``` -------------------------------- ### VariableNode AST Interface and Example for Variable Access Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/_media/ast-types.md Documents the `VariableNode` used for accessing variables in OpenSCAD expressions or as parameter values. Includes its TypeScript interface and an example AST representation. ```typescript interface VariableNode extends ExpressionNode { expressionType: 'variable'; // Distinguishes it as a variable expression name: string; // The name of the variable } ``` ```json // For an OpenSCAD statement like: size = 10; cube(size); // The 'size' in cube(size) would be parsed as a VariableNode within the parameters of the CubeNode's ModuleInstantiationNode: // AST representation of the VariableNode itself: { type: 'expression', // Inherited from ExpressionNode expressionType: 'variable', name: 'size', location: { start: { offset: 45, line: 3, column: 2 }, end: { offset: 49, line: 3, column: 6 } } // Example location } ``` ```APIDOC VariableNode Properties: - expressionType: Always 'variable'. - name: A string representing the identifier of the variable. ``` -------------------------------- ### Basic Expression Assignments in OpenSCAD Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/test/corpus/basics.txt This snippet illustrates fundamental assignment operations in OpenSCAD. It demonstrates assigning results of arithmetic, logical (OR), and comparison (equality) expressions to variables. The corresponding Tree-sitter parse tree shows how these binary expressions and assignments are structured. ```OpenSCAD result1 = 1 + 2 * 3; result2 = true || false; result3 = "hello" == "world"; ``` ```Tree-sitter Grammar (source_file (statement (assignment_statement name: (identifier) value: (binary_expression left: (number) operator: (addition_operator) right: (binary_expression left: (number) operator: (multiplication_operator) right: (number))))) (statement (assignment_statement name: (identifier) value: (binary_expression left: (boolean) operator: (logical_or_operator) right: (boolean)))) (statement (assignment_statement name: (identifier) value: (binary_expression left: (string) operator: (equality_operator) right: (string))))) ``` -------------------------------- ### Testing OpenSCAD Tree-sitter Grammar Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/README.md Outlines various commands for testing the OpenSCAD Tree-sitter grammar, including running the full test suite, testing specific files, parsing files, generating debug parse trees, and launching an interactive playground. ```Bash # Run the test suite nx test tree-sitter-openscad # Test specific files nx test tree-sitter-openscad --file-name="module definitions" # Parse a specific file nx parse tree-sitter-openscad -- examples/sample.scad # Generate and view the parse tree nx parse tree-sitter-openscad -- examples/sample.scad --debug # Launch interactive playground nx playground tree-sitter-openscad ``` -------------------------------- ### IdentifierNode AST Interface and Examples for Variable References Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/_media/ast-types.md Documents the `IdentifierNode` representing a variable reference in the OpenSCAD AST. Includes its TypeScript interface, an example AST representation, and the corresponding OpenSCAD code. ```typescript interface IdentifierNode extends BaseNode { type: 'expression'; // Inherited from ExpressionNode expressionType: 'identifier'; // Discriminates variable identifiers name: string; // The name of the variable } ``` ```json // Corresponds to: size; { type: 'expression', expressionType: 'identifier', name: 'size', location: { start: { offset: 0, line: 1, column: 1 }, end: { offset: 4, line: 1, column: 5 } } } ``` ```openscad size; ``` ```APIDOC IdentifierNode Properties: - type: Always 'expression'. - expressionType: Always 'identifier'. - name: The identifier string. ``` -------------------------------- ### IntersectionNode AST Interface and Example Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/_media/ast-types.md Documents the `IntersectionNode` which represents the `intersection()` boolean operation in OpenSCAD, computing the common volume of all child elements. Includes its TypeScript interface and an example AST representation. ```typescript interface IntersectionNode extends BaseNode { type: 'intersection'; children: ASTNode[]; // An array of child nodes whose intersection is computed. } ``` ```json // For: intersection() { cube(10); translate([5,5,5]) sphere(8); } // The result is the part of the cube that overlaps with the translated sphere. { type: 'intersection', children: [ { type: 'cube', size: { type: 'literal', value: 10 } /* ... other cube props ... */ }, { type: 'translate', v: [5,5,5], // TranslateNode.v is Vector3D children: [ { type: 'sphere', r: 8, // SphereNode.r is number location: { /*...*/ } } ], location: { /*...*/ } } ] } ``` ```APIDOC IntersectionNode Properties: - type: Always 'intersection'. - children: An array of ASTNode elements. The resulting geometry is the volume common to all child geometries. ``` -------------------------------- ### DifferenceNode AST Interface and Example Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/_media/ast-types.md Documents the `DifferenceNode` which represents the `difference()` boolean operation in OpenSCAD, subtracting subsequent child geometries from the first. Includes its TypeScript interface and an example AST representation. ```typescript interface DifferenceNode extends BaseNode { type: 'difference'; children: ASTNode[]; // An array of child nodes. First is positive, others are subtracted. } ``` ```json // For: difference() { cube(10); translate([5,5,5]) sphere(5); } { type: 'difference', children: [ { type: 'cube', size: { type: 'literal', value: 10 } /* ... other cube props ... */ }, { type: 'translate', v: [5,5,5], // TranslateNode.v is Vector3D children: [ { type: 'sphere', r: 5, // SphereNode.r is number location: { /*...*/ } } ], location: { /*...*/ } } ] } ``` ```APIDOC DifferenceNode Properties: - type: Always 'difference'. - children: An array of ASTNode elements. The geometry of the first child is the base from which the geometries of all subsequent children are subtracted. ``` -------------------------------- ### Build and Distribute OpenSCAD Tree-Sitter Packages Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/README.md Commands to build all packages within the monorepo or specific packages, preparing them for distribution or deployment. ```bash # Build all packages pnpm build # Build specific package pnpm build:parser pnpm build:grammar pnpm build:editor ``` -------------------------------- ### Example Usage of getFunctionName in TypeScript Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/functions/getFunctionName.md Demonstrates how to use the `getFunctionName` utility to extract function names from OpenSCAD module instantiation nodes, showing examples for `cube` and `translate` calls. ```typescript // For OpenSCAD code: cube(10) const functionName = getFunctionName(moduleInstantiationNode); // Returns: "cube" // For OpenSCAD code: translate([1, 2, 3]) const transformName = getFunctionName(translateNode); // Returns: "translate" ``` -------------------------------- ### UnionNode API Definition and Example Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/ast-types.md Represents a `union()` boolean operation, combining all its child geometries into a single object. Extends `BaseNode`. This section defines its TypeScript interface and provides an example of its AST representation. ```typescript interface UnionNode extends BaseNode { type: 'union'; children: ASTNode[]; // An array of child nodes to be combined } ``` ```APIDOC Properties: - type: Always 'union'. - children: An array of ASTNode elements whose geometries are to be combined. ``` ```typescript // For: union() { cube(10); sphere(5); } { type: 'union', children: [ { type: 'cube', size: { type: 'literal', value: 10 } /* ... other cube props ... */ }, { type: 'sphere', r: 5, // SphereNode.r is number location: { /*...*/ } } ] } ``` -------------------------------- ### RotateNode AST Structure Examples Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/ast-types.md Illustrative examples showing how different OpenSCAD `rotate()` calls are represented as `RotateNode` objects in the Abstract Syntax Tree, including handling of Euler angles and axis-angle rotations. ```TypeScript // For: rotate([0,0,90]) cube(5); // Euler angles for rotation // AST Node: { type: 'rotate', a: [0,0,90], // Vector3D representing Euler angles children: [ { type: 'cube', size: { type: 'literal', value: 5 } /* ... other cube props ... */ } ] } // For: rotate(a=45, v=[0,1,0]) cylinder(h=10, r=2); // AST Node: { type: 'rotate', a: 45, // number representing the angle v: [0,1,0], // Vector3D representing the axis of rotation children: [ { type: 'cylinder', h: 10, // CylinderNode.h is number r: 2, // CylinderNode.r is number (assuming r is used for r1 or r) location: { /*...*/ } } ] } // For: rotate(my_angle_vector_var) sphere(d=10); // Assuming my_angle_vector_var resolves to [30,0,0] // AST Node: { type: 'rotate', a: [30,0,0], // Example of 'a' as a resolved Vector3D // v would be undefined children: [ { type: 'sphere', d: 10, // SphereNode.d is number location: { /*...*/ } } ] } ``` -------------------------------- ### OpenSCAD Demo Test Suite Commands Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-demo/README.md Lists various `nx` commands for running unit tests, end-to-end (E2E) tests, specific E2E tests, and all quality checks for the OpenSCAD demo project. These commands facilitate comprehensive testing and validation. ```bash # Run unit tests nx test openscad-demo # Run E2E tests nx e2e openscad-demo # Run specific E2E test nx e2e openscad-demo --grep="Feature Comparison Panel" # Run all quality checks nx test openscad-demo && nx typecheck openscad-demo && nx lint openscad-demo ``` -------------------------------- ### Basic OpenSCAD Editor Setup with Syntax Highlighting Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-editor/README.md This snippet demonstrates the fundamental setup of the OpenSCAD editor component. It initializes the editor with a default OpenSCAD code value, enables basic syntax highlighting, and configures display options like font size and minimap. ```tsx import { OpenscadEditor } from '@openscad/editor'; // Basic editor with syntax highlighting only ``` -------------------------------- ### OpenSCAD List Comprehensions with Let Expressions and Tree-sitter Parse Tree Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/test/corpus/advanced.txt This example illustrates OpenSCAD's list comprehensions, specifically demonstrating the use of 'let' expressions to define local variables within the comprehension. The accompanying Tree-sitter parse tree shows how these complex constructs, including let assignments and loop iterations, are structured in the syntax tree. ```OpenSCAD areas = [let (num=len(vertices)) for (i=[0:num-1]) triarea(vertices[i])]; complex = [let (a=5, b=10) for (x=[0:a]) x*b]; ``` ```Tree-sitter Grammar (source_file (statement (assignment_statement name: (identifier) value: (list_comprehension (let_assignment name: (identifier) value: (call_expression function: (identifier) arguments: (argument_list (arguments (argument (identifier)))))) (list_comprehension_for iterator: (identifier) range: (vector_expression (binary_expression left: (range_expression start: (number) end: (identifier)) operator: (subtraction_operator) right: (number)))) expr: (call_expression function: (identifier) arguments: (argument_list (arguments (argument (index_expression array: (identifier) index: (identifier))))))))) (statement (assignment_statement name: (identifier) value: (list_comprehension (let_assignment name: (identifier) value: (number)) (let_assignment name: (identifier) value: (number)) (list_comprehension_for iterator: (identifier) range: (vector_expression (range_expression start: (number) end: (identifier)))) expr: (binary_expression left: (identifier) operator: (multiplication_operator) right: (identifier)))))) ``` -------------------------------- ### TypeScript AST Examples for EchoStatementNode Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/_media/ast-types.md Demonstrates the JSON structure of `EchoStatementNode` objects within the TypeScript AST, showing how OpenSCAD `echo()` statements are represented, including examples with no arguments and multiple arguments of different types. ```typescript { "type": "echo", "arguments": [], "location": { "start": { "offset": 0, "line": 1, "column": 1 }, "end": { "offset": 6, "line": 1, "column": 7 } } } ``` ```typescript { "type": "echo", "arguments": [ { "type": "expression", "expressionType": "literal", "value": "Hello", "location": { "start": { "offset": 5, "line": 1, "column": 6 }, "end": { "offset": 12, "line": 1, "column": 13 } } }, { "type": "expression", "expressionType": "variable", "name": "x", "location": { "start": { "offset": 14, "line": 1, "column": 15 }, "end": { "offset": 15, "line": 1, "column": 16 } } }, { "type": "expression", "expressionType": "literal", "value": 42, "location": { "start": { "offset": 18, "line": 1, "column": 19 }, "end": { "offset": 20, "line": 1, "column": 21 } } } ], "location": { "start": { "offset": 0, "line": 1, "column": 1 }, "end": { "offset": 23, "line": 1, "column": 24 } } } ``` -------------------------------- ### Run OpenSCAD Tree-Sitter Project Tests Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/_media/README.md Commands to execute all tests, run tests for specific packages (parser, grammar, editor), run tests in watch mode, and generate a coverage report. ```bash # Run all tests pnpm test # Run tests for specific package pnpm test:parser pnpm test:grammar pnpm test:editor # Run tests in watch mode pnpm test:watch # Generate coverage report pnpm test:coverage ``` -------------------------------- ### IdentifierNode API Definition and Example Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/ast-types.md Represents a variable reference. Extends `ExpressionNode`. This node captures the name of the variable. This section defines its TypeScript interface and provides an example of its AST representation and corresponding OpenSCAD code. ```typescript interface IdentifierNode extends BaseNode { type: 'expression'; // Inherited from ExpressionNode expressionType: 'identifier'; // Discriminates variable identifiers name: string; // The name of the variable } ``` ```APIDOC Properties: - type: Always 'expression'. - expressionType: Always 'identifier'. - name: The identifier string. ``` ```typescript // Corresponds to: size; { type: 'expression', expressionType: 'identifier', name: 'size', location: { start: { offset: 0, line: 1, column: 1 }, end: { offset: 4, line: 1, column: 5 } } } ``` ```openscad size; ``` -------------------------------- ### Example AST Representations for OpenSCAD Translate Primitive Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/ast-types.md Illustrates how OpenSCAD `translate()` primitives are represented as `TranslateNode`s in the Abstract Syntax Tree, showing examples for both 3D and 2D translation vectors and their respective child nodes. ```typescript // For: translate([10,20,30]) cube(5); { type: 'translate', v: [10,20,30], // Vector3D children: [ { type: 'cube', size: { type: 'literal', value: 5 } /* ... other cube props ... */ } ] } // For: translate([5, -5]) square(10); { type: 'translate', v: [5, -5], // Vector2D children: [ { type: 'square', size: 10 /* ... other square props ... */ } ] } ``` -------------------------------- ### Load OpenSCAD WASM Bindings with web-tree-sitter Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/bindings/wasm/README.md This JavaScript snippet demonstrates how to initialize `web-tree-sitter`, load the compiled OpenSCAD WASM grammar, and set it for parsing. It includes an example of parsing a simple OpenSCAD expression and logging the root node of the generated parse tree. ```javascript import Parser from 'web-tree-sitter'; async function initParser() { await Parser.init(); const parser = new Parser(); const language = await Parser.Language.load('path/to/bindings/wasm/tree-sitter-openscad.wasm'); parser.setLanguage(language); return parser; } // Example usage const parser = await initParser(); const tree = parser.parse('cube([10, 10, 10]);'); console.log(tree.rootNode.toString()); ``` -------------------------------- ### OpenSCAD Basic Transformations Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/tree-sitter-openscad/test/corpus/comprehensive-basic.txt Demonstrates common 3D transformations in OpenSCAD: 'translate', 'rotate', and 'scale', applied to primitive shapes. The Tree-sitter parse tree illustrates how these transformations wrap the module instantiations. ```OpenSCAD translate([10, 0, 0]) cube(5); rotate([0, 0, 45]) sphere(3); scale([2, 1, 1]) cylinder(h=5, r=2); ``` ```Tree-sitter (source_file (statement (module_instantiation name: (identifier) arguments: (argument_list (arguments (argument (vector_expression (number) (number) (number))))) (statement (module_instantiation name: (identifier) arguments: (argument_list (arguments (argument (number)))))))) (statement (module_instantiation name: (identifier) arguments: (argument_list (arguments (argument (vector_expression (number) (number) (number))))) (statement (module_instantiation name: (identifier) arguments: (argument_list (arguments (argument (number)))))))) (statement (module_instantiation name: (identifier) arguments: (argument_list (arguments (argument (vector_expression (number) (number) (number))))) (statement (module_instantiation name: (identifier) arguments: (argument_list ``` -------------------------------- ### OpenSCAD Parser API: RangeExpressionNode Interface Definition Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/typedocs/interfaces/RangeExpressionNode.md Defines the `RangeExpressionNode` interface, which represents OpenSCAD range expressions such as `[start:end]` or `[start:step:end]`. This interface extends the `ExpressionNode`. ```APIDOC Interface: RangeExpressionNode Defined in: openscad-parser/ast/ast-types.ts:895 Description: Represents a range expression [start:end] or [start:step:end] Extends: ExpressionNode ``` -------------------------------- ### Example Parsed RangeExpressionNode for Literal Range `[0:2:10]` Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/ast-types.md Illustrates the JSON structure of a `RangeExpressionNode` when parsing an OpenSCAD range like `[0:2:10]`. This example shows how literal values are represented as nested `LiteralNodes` within the range expression. ```typescript { type: 'expression', expressionType: 'range_expression', start: { type: 'expression', expressionType: 'literal', value: 0, location: { start: { offset: 45, line: 3, column: 2 }, end: { offset: 46, line: 3, column: 3 } } }, step: { type: 'expression', expressionType: 'literal', value: 2, location: { start: { offset: 47, line: 3, column: 4 }, end: { offset: 48, line: 3, column: 5 } } }, end: { type: 'expression', expressionType: 'literal', value: 10, location: { start: { offset: 49, line: 3, column: 6 }, end: { offset: 51, line: 3, column: 8 } } }, location: { start: { offset: 44, line: 3, column: 1 }, end: { offset: 52, line: 3, column: 9 } } } ``` -------------------------------- ### ScaleNode AST Structure Examples Source: https://github.com/holistic-stack/openscad-tree-sitter/blob/main/packages/openscad-parser/docs/api/ast-types.md Illustrative examples showing how different OpenSCAD `scale()` calls are represented as `ScaleNode` objects in the Abstract Syntax Tree, including handling of scalar and 2D vector promotions to a 3D vector. ```TypeScript // For: scale([2,1,0.5]) cube(5); // AST Node: { type: 'scale', v: [2,1,0.5], // Vector3D children: [ { type: 'cube', size: { type: 'literal', value: 5 } /* ... other cube props ... */ } ] } // For: scale(my_scale_vector_var) sphere(d=10); // Assuming my_scale_vector_var resolves to [1, 2, 0.5] // AST Node: { type: 'scale', v: [1, 2, 0.5], // Example of 'v' as a resolved Vector3D children: [ { type: 'sphere', d: 10, // SphereNode.d is number location: { /*...*/ } } ] } ```