CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-web-tree-sitter

Tree-sitter bindings for the web providing WebAssembly-based incremental parsing of source code

Pending
Overview
Eval results
Files

parser.mddocs/

Parser

Core parsing functionality for creating parsers, setting languages, and converting source code into syntax trees. The Parser class is the main entry point for Tree-sitter operations.

Capabilities

Parser Initialization

Initialize the WebAssembly module before creating parsers.

/**
 * Initialize the WebAssembly module. Must be called before creating any Parser instances.
 * @param moduleOptions - Optional Emscripten module configuration, commonly used to set locateFile for finding the .wasm file
 * @returns Promise that resolves when WASM module is ready
 */
static init(moduleOptions?: EmscriptenModule): Promise<void>;

Usage Example:

import { Parser } from "web-tree-sitter";

// Basic initialization
await Parser.init();

// With custom WASM location
await Parser.init({
  locateFile(scriptName: string, scriptDirectory: string) {
    return "/custom/path/" + scriptName;
  }
});

Parser Creation

Create parser instances for parsing operations.

/**
 * Create a new parser instance
 */
constructor();

/**
 * Delete the parser and free its resources
 */
delete(): void;

Language Configuration

Set the parsing language for the parser.

/**
 * Set the language that the parser should use for parsing
 * @param language - Language instance or null to unset
 * @returns Parser instance for chaining
 * @throws Error if language has incompatible ABI version
 */
setLanguage(language: Language | null): this;

/** The parser's current language */
language: Language | null;

Usage Example:

import { Parser, Language } from "web-tree-sitter";

await Parser.init();
const parser = new Parser();

// Load and set JavaScript language
const JavaScript = await Language.load("/tree-sitter-javascript.wasm");
parser.setLanguage(JavaScript);

console.log(parser.language?.name); // "javascript"

Parsing Operations

Parse source code into syntax trees.

/**
 * Parse source code or use a callback to provide text
 * @param callback - Source code string or callback function that provides text
 * @param oldTree - Previous syntax tree for incremental parsing
 * @param options - Parsing options including ranges and progress callback
 * @returns Tree if parsing succeeded, null if parser has no language or was cancelled
 */
parse(callback: string | ParseCallback, oldTree?: Tree | null, options?: ParseOptions): Tree | null;

/**
 * Reset parser to start next parse from beginning
 * Use this when switching to parse a different document after timeout/cancellation
 */
reset(): void;

Usage Examples:

// Parse source code string
const tree = parser.parse("let x = 1 + 2;");

// Incremental parsing with previous tree
const newTree = parser.parse("let x = 1 + 3;", tree);

// Parse with callback for large documents
const largeTree = parser.parse((index, position) => {
  // Provide text at given byte index and position
  return getTextAtPosition(index, position);
});

// Parse with options
const constrainedTree = parser.parse(sourceCode, null, {
  includedRanges: [
    { startIndex: 0, endIndex: 100, startPosition: {row: 0, column: 0}, endPosition: {row: 5, column: 10} }
  ],
  progressCallback: (state) => {
    console.log(`Parsing at offset: ${state.currentOffset}`);
    // Return to cancel parsing if needed
  }
});

Range Management

Configure which parts of the document to include during parsing.

/**
 * Get the ranges of text that the parser will include when parsing
 * @returns Array of ranges currently set for parsing
 */
getIncludedRanges(): Range[];

Logging Configuration

Set up logging for parser operations.

/**
 * Set the logging callback for parser operations
 * @param callback - Log callback function, true for console logging, or null to disable
 * @returns Parser instance for chaining
 */
setLogger(callback: LogCallback | boolean | null): this;

/**
 * Get the parser's current logger
 * @returns Current log callback or null if not set
 */
getLogger(): LogCallback | null;

Usage Example:

// Enable console logging
parser.setLogger(true);

// Custom logging
parser.setLogger((message, isLex) => {
  console.log(`[${isLex ? 'LEX' : 'PARSE'}] ${message}`);
});

// Disable logging
parser.setLogger(null);

Deprecated Methods

These methods are deprecated in favor of progress callbacks.

/**
 * @deprecated Use progressCallback in parse options instead
 * Get the duration in microseconds that parsing is allowed to take
 */
getTimeoutMicros(): number;

/**
 * @deprecated Use progressCallback in parse options instead  
 * Set the maximum duration in microseconds for parsing
 */
setTimeoutMicros(timeout: number): void;

Types

interface ParseOptions {
  /** Array of ranges to include when parsing */
  includedRanges?: Range[];
  /** Progress callback for monitoring parsing (void return - different from main ProgressCallback) */
  progressCallback?: (state: ParseState) => void;
}

interface ParseState {
  /** Current byte offset in document */
  currentOffset: number;
  /** Whether parser has encountered an error */
  hasError: boolean;
}

/** Callback for providing text during parsing */
type ParseCallback = (index: number, position: Point) => string | undefined;

/** Callback for monitoring parsing progress and optionally cancelling */
type ProgressCallback = (progress: ParseState) => boolean;

/** Callback for logging parser messages */
type LogCallback = (message: string, isLex: boolean) => void;

/** ABI version constants */
const LANGUAGE_VERSION: number;
const MIN_COMPATIBLE_VERSION: number;

Install with Tessl CLI

npx tessl i tessl/npm-web-tree-sitter

docs

index.md

language.md

parser.md

query.md

tree-cursor.md

tree-node.md

tile.json