### TypeScript Arrow Functions and Generator Functions Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt Provides examples of TypeScript arrow functions and generator functions, including type parameters, parameter type annotations, and return type annotations. It demonstrates concise syntax for asynchronous operations and common functional programming patterns. ```typescript (amount, interestRate, duration): number => 2 function* foo(amount, interestRate, duration): number { yield amount * interestRate * duration / 12 } (module: any): number => 2 ``` ```tree-sitter-typescript (program (expression_statement (arrow_function type_parameters: (type_parameters (type_parameter name: (type_identifier))) parameters: (formal_parameters (required_parameter pattern: (identifier)) (required_parameter pattern: (identifier)) (required_parameter pattern: (identifier))) return_type: (type_annotation (predefined_type)) body: (number))) (generator_function_declaration name: (identifier) type_parameters: (type_parameters (type_parameter name: (type_identifier))) parameters: (formal_parameters (required_parameter pattern: (identifier)) (required_parameter pattern: (identifier)) (required_parameter pattern: (identifier))) return_type: (type_annotation (predefined_type)) body: (statement_block))) (expression_statement (arrow_function parameters: (formal_parameters (required_parameter pattern: (identifier) type: (type_annotation (predefined_type)))) return_type: (type_annotation (predefined_type)) body: (number)))) ``` -------------------------------- ### TypeScript Functions with Typed Parameters and Generics Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt Demonstrates TypeScript functions with explicitly typed parameters, generic type parameters, and return types. Includes examples of simple greeter functions, generic identity functions, and functions operating on arrays with generic types. This snippet showcases the flexibility of TypeScript's type system. ```typescript function greeter(person: string) { return "Hello, " + person; } function foo(x: T): T { } function foo(a: T[], f: (x: T) => U): U[] { } function foo(this: T[]): U[] { return [] } function foo(x: T, y: U) { } ``` ```tree-sitter-typescript (program (function_declaration name: (identifier) parameters: (formal_parameters (required_parameter pattern: (identifier) type: (type_annotation (predefined_type)))) body: (statement_block (return_statement (binary_expression left: (string (string_fragment)) right: (identifier))))) (function_declaration name: (identifier) type_parameters: (type_parameters (type_parameter name: (type_identifier))) parameters: (formal_parameters (required_parameter pattern: (identifier) type: (type_annotation (type_identifier)))) return_type: (type_annotation (type_identifier)) body: (statement_block)) (function_declaration name: (identifier) type_parameters: (type_parameters (type_parameter name: (type_identifier))) (type_parameter name: (type_identifier))) parameters: (formal_parameters (required_parameter pattern: (identifier) type: (type_annotation (array_type (type_identifier)))) (required_parameter pattern: (identifier) type: (type_annotation (function_type parameters: (formal_parameters (required_parameter pattern: (identifier) type: (type_annotation (type_identifier)))) return_type: (type_identifier)))))) return_type: (type_annotation (array_type (type_identifier))) body: (statement_block)) (function_declaration name: (identifier) type_parameters: (type_parameters (type_parameter name: (type_identifier))) (type_parameter name: (type_identifier))) parameters: (formal_parameters (required_parameter pattern: (this) type: (type_annotation (array_type (type_identifier)))))) return_type: (type_annotation (array_type (type_identifier))) body: (statement_block (return_statement (array)))) (function_declaration name: (identifier) type_parameters: (type_parameters (type_parameter name: (type_identifier)) (type_parameter name: (type_identifier) constraint: (constraint (predefined_type))))) parameters: (formal_parameters (required_parameter pattern: (identifier) type: (type_annotation (type_identifier))) (required_parameter pattern: (identifier) type: (type_annotation (type_identifier)))) body: (statement_block))) ``` -------------------------------- ### TypeScript Object Instantiation with Type Arguments Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt Illustrates creating a new object instance with explicit type arguments in TypeScript. This is common when working with generic collections or classes that require specific types to be provided at instantiation time. The example shows `new Array()`. ```typescript const lines = new Array() ``` ```tree-sitter-typescript (program (lexical_declaration (variable_declarator (identifier) (new_expression (identifier) (type_arguments (type_identifier)) (arguments))))) ``` -------------------------------- ### Instantiation Expressions for Generic Types Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt Demonstrates how to create instances of generic types in TypeScript, specifying the type arguments at the point of instantiation. This allows for type-safe generic collections and classes. ```tree-sitter grammar (program (lexical_declaration (variable_declarator (identifier) (instantiation_expression (identifier) (type_arguments (type_identifier))))) (lexical_declaration (variable_declarator (identifier) (instantiation_expression (identifier) (type_arguments (predefined_type))))) (lexical_declaration (variable_declarator (identifier) (instantiation_expression (identifier) (type_arguments (predefined_type) (type_identifier)))))) ``` -------------------------------- ### Ambiguity: Function Signature vs. Declaration (Simple) Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt Presents ambiguity between a function signature and a function declaration. The first case shows a simple function declaration. The subsequent examples demonstrate variations in parameters and return types, including object types with index signatures. ```typescript function foo() {} function foo(bar) function foo(bar): baz; function foo(bar) function foo(): () => { [key: foo]: bar } function foo(): () => { [key: foo]: bar } {} ``` -------------------------------- ### Generic Function Calls Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt Shows the grammar structure for calling a generic function with type arguments. This is common in TypeScript for creating reusable functions that operate on various types. ```tree-sitter grammar (program (expression_statement (call_expression (identifier) (type_arguments (type_identifier)) (arguments (identifier))))) ``` -------------------------------- ### TypeScript Literal Type Examples Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Illustrates TypeScript's literal types, which allow specifying exact values for types, including numbers, strings, and booleans. ```typescript let x: 2 let x: 2 | -3 | +4 let x: "string" let x: false ``` ```tree-sitter-typescript (program (lexical_declaration (variable_declarator (identifier) (type_annotation (literal_type (number))))) (lexical_declaration (variable_declarator (identifier) (type_annotation (union_type (union_type (literal_type (number)) (literal_type (unary_expression (number)))) (literal_type (unary_expression (number))))))) (lexical_declaration (variable_declarator (identifier) (type_annotation (literal_type (string (string_fragment)))))) (lexical_declaration (variable_declarator (identifier) (type_annotation (literal_type (false)))))) ``` -------------------------------- ### Arrow Function with Async Parameter Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt Demonstrates an arrow function where the parameter is named 'async'. This highlights how identifiers can shadow keywords in certain contexts. The function simply returns its input parameter. ```typescript const x = async => async; ``` -------------------------------- ### TypeScript 'satisfies' Expressions Grammar Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt This snippet details the tree-sitter grammar for 'satisfies' expressions in TypeScript, used to assert that an expression conforms to a specific type. It includes examples with string literals and object types. ```tree-sitter grammar (program (expression_statement (satisfies_expression (identifier) (template_literal_type (string_fragment)))) (expression_statement (satisfies_expression (identifier) (intersection_type (object_type) (object_type (index_signature (identifier) (type_identifier) (type_annotation (type_identifier))))))) (expression_statement (satisfies_expression (identifier) (intersection_type (intersection_type (object_type) (object_type (index_signature (identifier) (type_identifier) (type_annotation (type_identifier))))) (object_type (index_signature (identifier) (type_identifier) (type_annotation (type_identifier)))))))) ``` -------------------------------- ### Flow Union Types Syntax Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Illustrates Flow union types, which allow a value to be one of several types. Includes examples with predefined types and string literals. ```flow type U = number | string; type Z = | "foo" | "bar"; type Z = | "foo"; ``` ```tree-sitter-typescript (program (type_alias_declaration (type_identifier) (union_type (predefined_type) (predefined_type))) (type_alias_declaration (type_identifier) (union_type (union_type (literal_type (string (string_fragment)))) (literal_type (string (string_fragment))))) (type_alias_declaration (type_identifier) (union_type (literal_type (string (string_fragment)))))) ``` -------------------------------- ### Macro for Adding Parsers Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/CMakeLists.txt Defines a CMake macro `add_parser` that generates the parser.c file using the tree-sitter CLI, creates a library for the parser, sets include directories and compile definitions, configures target properties like standard and position-independent code, and sets up installation rules for header files, pkgconfig files, and libraries. ```cmake macro(add_parser name) 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-${name} "${CMAKE_CURRENT_SOURCE_DIR}/src/parser.c" "${CMAKE_CURRENT_SOURCE_DIR}/src/scanner.c") target_include_directories(tree-sitter-${name} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") target_compile_definitions(tree-sitter-${name} PRIVATE $<$:TREE_SITTER_REUSE_ALLOCATOR> $<$:TREE_SITTER_DEBUG>) set_target_properties(tree-sitter-${name} PROPERTIES C_STANDARD 11 POSITION_INDEPENDENT_CODE ON SOVERSION "${TREE_SITTER_ABI_VERSION}.${PROJECT_VERSION_MAJOR}" DEFINE_SYMBOL "") configure_file("${CMAKE_SOURCE_DIR}/bindings/c/tree-sitter-${name}.pc.in" "${CMAKE_CURRENT_BINARY_DIR}/tree-sitter-${name}.pc" @ONLY) install(FILES "${CMAKE_SOURCE_DIR}/bindings/c/tree-sitter-${name}.h" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/tree_sitter") install(FILES "${CMAKE_CURRENT_BINARY_DIR}/tree-sitter-${name}.pc" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig") install(TARGETS tree-sitter-${name} LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") endmacro() ``` -------------------------------- ### TypeScript Variable Declaration Grammar Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt This snippet demonstrates the tree-sitter grammar for declaring variables in TypeScript, including a special case for a variable named 'module'. It shows both declaration and usage. ```tree-sitter grammar (program (variable_declaration (variable_declarator (identifier))) (expression_statement (identifier))) ``` -------------------------------- ### Class Method Using Super Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt Illustrates the usage of the 'super' keyword in a TypeScript class. It shows 'super' being called in the constructor and 'super.toString()' within another method to invoke parent class methods. Type annotations are included for parameters. ```typescript class A extends B { constructor(x: number, y: number) { super(x); } public toString() { return super.toString() + " y=" + this.y; } } ``` -------------------------------- ### TypeScript Multi-line Variable Declarations Grammar Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt This snippet illustrates the tree-sitter grammar for multi-line variable declarations in TypeScript, allowing for declarations to span across multiple lines for improved readability. ```tree-sitter grammar (program (variable_declaration (variable_declarator (identifier) (identifier)) (variable_declarator (identifier) (identifier)) (variable_declarator (identifier) (identifier)))) ``` -------------------------------- ### TypeScript 'less than' Operator Grammar Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt This snippet shows the tree-sitter grammar for the 'less than' operator (<) in TypeScript, commonly used in conditional statements and loops for comparisons. ```tree-sitter grammar (program (expression_statement (binary_expression (identifier) (member_expression (identifier) (property_identifier)))) (expression_statement (binary_expression (identifier) (member_expression (identifier) (property_identifier)))) (expression_statement (binary_expression (identifier) (member_expression (identifier) (property_identifier))))) ``` -------------------------------- ### TypeScript Function Calls with Array and Tuple Type Arguments Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt Demonstrates advanced function call syntax in TypeScript, specifically using type arguments that are arrays and tuples. It includes calling a method on an object with tuple type arguments and a direct function call with array type arguments, potentially involving nested types or modules. ```typescript a.b<[C]>(); a(); ``` ```tree-sitter-typescript (program (expression_statement (call_expression function: (member_expression object: (identifier) property: (property_identifier)) type_arguments: (type_arguments (tuple_type (type_identifier))) arguments: (arguments))) (expression_statement (call_expression function: (identifier) type_arguments: (type_arguments (array_type (nested_type_identifier module: (identifier) name: (type_identifier)))) arguments: (arguments)))) ``` -------------------------------- ### Ambiguity: Function Signature vs. Declaration (Comments) Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt Illustrates the ambiguity between function signatures and declarations when comments and newlines are involved. It shows how a comment can precede a signature or a declaration, and how a signature can be followed by a function call or a declaration body. ```typescript function foo() // above is a signature foo(); function bar() // above is a function declaration {} function foo() : number; ``` -------------------------------- ### Ternary Conditional Expression Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt Shows the structure of a ternary conditional expression, which provides a concise way to write simple conditional assignments or return values. It includes a condition, a value if true, and a value if false. ```tree-sitter grammar (program (expression_statement (ternary_expression (identifier) (function_expression (formal_parameters) (statement_block (return_statement (true)))) (identifier)))) ``` -------------------------------- ### TypeScript Classes with Decorators Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/declarations.txt Demonstrates TypeScript classes utilizing decorators on class declarations, static properties, and method parameters. This example highlights the parsing of various decorator applications, including simple identifiers, call expressions with arguments, and decorators on parameters. ```tree-sitter grammar (program (class_declaration (decorator (identifier)) (decorator (identifier)) (type_identifier) (class_body (public_field_definition (decorator (identifier)) (number) (type_annotation (predefined_type))) (public_field_definition (decorator (call_expression (member_expression (identifier) (property_identifier)) (arguments (identifier)))) (accessibility_modifier) (number) (type_annotation (predefined_type)) (string (string_fragment))) (public_field_definition (decorator (identifier)) (string (string_fragment)) (type_annotation (type_identifier)) (string (string_fragment))) (decorator (identifier)) (method_definition (property_identifier) (formal_parameters (required_parameter (decorator (identifier)) (identifier) (type_annotation (predefined_type))) (optional_parameter (decorator (identifier)) (identifier) (type_annotation (predefined_type)))) (statement_block))))) @baz @bam class Foo { @foo static 2: string; @bar.buzz(grue) public static 2: string = 'string'; @readonly readonly 'hello'?: int = 'string'; @readonly fooBar(@required param: any, @optional param2?: any) { } } ``` -------------------------------- ### TypeScript Decorator with Parenthesized Expression Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/declarations.txt Example of a method within a class decorated using a parenthesized expression, such as 'super.decorate'. Decorators are a TypeScript feature for metaprogramming. ```typescript class C { @(super.decorate) method2() { } } ``` -------------------------------- ### Flow Exact Object Type Syntax Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Demonstrates Flow's exact object types, which enforce that an object has only the specified properties and no others. This example defines a BrowserStats object. ```flow type BrowserStats = {| url: string, ms: number |} ``` ```tree-sitter-typescript (program (type_alias_declaration (type_identifier) (object_type (property_signature (property_identifier) (type_annotation (predefined_type))) (property_signature (property_identifier) (type_annotation (predefined_type)))))) ``` -------------------------------- ### Flow Intersection Type Syntax Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Shows the Flow intersection type syntax, where a value must satisfy all specified types. This example combines number and string types. ```flow type BrowserStats$ResourceTiming = number & string; ``` ```tree-sitter-typescript (program (type_alias_declaration (type_identifier) (intersection_type (predefined_type) (predefined_type)))) ``` -------------------------------- ### Type Arguments in JSX Elements and Fragments Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt Illustrates how type arguments can be used within JSX elements and self-closing elements, as well as the grammar for fragments. This is specific to TSX and allows for type checking of JSX components. ```tsx >hi; >; <>fragment; ``` ```tree-sitter grammar (program (expression_statement (jsx_element (jsx_opening_element (identifier) (type_arguments (type_identifier))) (jsx_text) (jsx_closing_element (identifier)))) (expression_statement (jsx_self_closing_element (identifier) (type_arguments (type_identifier)))) (expression_statement (jsx_element (jsx_opening_element) (jsx_text) (jsx_closing_element)))) ``` -------------------------------- ### TypeScript Lookup Types Syntax Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Demonstrates the syntax for lookup types in TypeScript, used to access properties of an object type. Examples include `Foo[bar]` and `Foo['bar' | 'baz']`, with their corresponding tree-sitter grammar representations. ```typescript type K1 = Foo[bar] type K1 = Foo['bar' | 'baz'] ``` ```tree-sitter-grammar (program (type_alias_declaration (type_identifier) (lookup_type (type_identifier) (type_identifier))) (type_alias_declaration (type_identifier) (lookup_type (type_identifier) (union_type (literal_type (string (string_fragment))) (literal_type (string (string_fragment))))))) ``` -------------------------------- ### TypeScript 'as' Expressions Grammar Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt This snippet shows the tree-sitter grammar for 'as' expressions in TypeScript, which are used for type assertions. It covers simple string literal types and complex intersection types. ```tree-sitter grammar (program (expression_statement (as_expression (identifier) (template_literal_type (string_fragment)))) (expression_statement (as_expression (identifier) (intersection_type (object_type) (object_type (index_signature (identifier) (type_identifier) (type_annotation (type_identifier))))))) (expression_statement (as_expression (identifier) (intersection_type (intersection_type (object_type) (object_type (index_signature (identifier) (type_identifier) (type_annotation (type_identifier))))) (object_type (index_signature (identifier) (type_identifier) (type_annotation (type_identifier)))))))) ``` -------------------------------- ### TypeScript Nested Type Arguments Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Shows examples of deeply nested generic type arguments in TypeScript, used for complex data structures like Promises wrapping nested Maps. ```typescript interface X { x(): Promise>; } var y: Map>>> ``` ```tree-sitter-typescript (program (interface_declaration (type_identifier) (interface_body (method_signature (property_identifier) (formal_parameters) (type_annotation (generic_type (type_identifier) (type_arguments (generic_type (type_identifier) (type_arguments (type_identifier)))))))))) (variable_declaration (variable_declarator (identifier) (type_annotation (generic_type (type_identifier) (type_arguments (predefined_type) (generic_type (type_identifier) (type_arguments (generic_type (type_identifier) (type_arguments (type_identifier) (generic_type (type_identifier) (type_arguments (type_identifier) (type_identifier)))))))))))))) ``` -------------------------------- ### TypeScript Function Calls with Optional Chaining and Type Arguments Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt Shows TypeScript syntax for optional chaining combined with type arguments in a function call. This pattern is used to safely call a function on a potentially null or undefined object, while also specifying generic type parameters for the call. ```typescript A?.(); ``` ```tree-sitter-typescript (program (expression_statement (call_expression (identifier) (type_arguments (type_identifier)) (arguments)))) ``` -------------------------------- ### TypeScript Type Predicate Functions Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Demonstrates the TypeScript syntax for type predicate functions, which check if a variable conforms to a specific type. The examples show the function signature and body for type guards. ```typescript function isFish(pet: Fish): pet is Fish { } function isFish(object: Fish): object is Fish { } ``` -------------------------------- ### Type Assertions in TypeScript Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt Captures the syntax for type assertions in TypeScript, where a developer explicitly tells the compiler to treat a value as a specific type. This is often used when the compiler cannot infer the correct type. ```typescript b; >e.f; ``` ```tree-sitter grammar (program (expression_statement (type_assertion (type_arguments (type_identifier)) (identifier))) (expression_statement (type_assertion (type_arguments (generic_type (type_identifier) (type_arguments (type_identifier)))) (member_expression (identifier) (property_identifier))))) ``` -------------------------------- ### Object Literals with Boolean and Number Values Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt Demonstrates parsing of object literals containing key-value pairs where values are either booleans (true) or numbers. This is a fundamental structure for representing data objects in TypeScript. ```tree-sitter grammar (program (expression_statement (object (pair key: (property_identifier) value: (true)) (pair key: (property_identifier) value: (true)) (pair key: (property_identifier) value: (true)))) (expression_statement (object (pair key: (property_identifier) value: (number)) (pair key: (property_identifier) value: (number)) (pair key: (property_identifier) value: (number))))) ``` -------------------------------- ### TypeScript 'typeof' Expressions Grammar Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt This snippet illustrates the tree-sitter grammar for 'typeof' expressions in TypeScript, used to determine the type of a variable or expression. It covers comparisons with string literals. ```tree-sitter grammar (program (expression_statement (binary_expression (unary_expression (class (class_body))) (string (string_fragment)))) (expression_statement (binary_expression (binary_expression (unary_expression (identifier)) (string (string_fragment))) (binary_expression (unary_expression (member_expression (identifier) (property_identifier))) (string (string_fragment)))))) ``` -------------------------------- ### TypeScript Index Type Queries Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/declarations.txt Demonstrates the Tree-sitter grammar for 'keyof' operator in TypeScript, used to create a union type of the property names of an object type. This example extracts keys from a Pick utility type. ```typescript export type Extracted = keyof Pick ``` -------------------------------- ### Exported Default Function Signature Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt Shows an exported default function signature in TypeScript. This defines the function's name, parameters, and return type without providing an implementation body. It's useful for declarations and interfaces. ```typescript export default function foo(): bar ``` -------------------------------- ### TypeScript Mapped Types with 'as' Clause Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Illustrates TypeScript mapped types where the 'as' clause is used to transform or create new keys. This includes examples with template literal types for key renaming and unions for multiple key patterns. ```typescript type A = { [B in keyof C & string as `get${Capitalize

}`]: () => A[B] }; type A = { [B in keyof C & string as `${P}1` | `${P}2`]: A[B] } ``` -------------------------------- ### Parse TypeScript Function Signature with Tree-sitter Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/functions.txt This grammar rule defines how to parse a TypeScript function signature. It captures the function identifier, its formal parameters, and the return type annotation. This is useful for static analysis tools that need to understand function definitions. ```tree-sitter grammar (function_signature (identifier) (formal_parameters) (type_annotation (predefined_type)))) ``` -------------------------------- ### TypeScript Assertion Function Types Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Defines the syntax for TypeScript assertion functions, which are used to narrow down the type of a variable. It includes examples for general assertions and type-specific assertions (type predicates). ```typescript declare const f: (x: any) => asserts x; declare const g: (x: any) => asserts x is number; ``` -------------------------------- ### TypeScript Objects with Reserved Word Keys Grammar Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt This snippet illustrates the tree-sitter grammar for parsing TypeScript objects where reserved words are used as keys. This is valid in TypeScript when using computed property names or specific object literal syntaxes. ```tree-sitter grammar { public: true, private: true, readonly: true }; ``` -------------------------------- ### TypeScript Conditional Types Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Provides examples of TypeScript conditional types, which allow for defining types based on a condition. This includes basic conditional types, overloaded function types used in conditionals, and inferring types within conditionals. ```typescript type T = X extends Y ? Z : Y type T = X extends ?Y ? ?X : Y type F = ((t: T) => X extends Y ? X : Y) extends ((t: T) => X extends Y ? Y : X) ? X : Y type F = (t: T) => X extends Y ? X : Y extends (t: T) => X extends Y ? Y : X ? X : Y type T = T extends X ? Y : X type T = X extends (infer X)[] ? X : never; type T = T extends { x: infer X } ? X : never; type T = T extends { x: infer X extends number } ? X : never; ``` -------------------------------- ### TypeScript Assertion Functions (Value Check) Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Shows the syntax for assertion functions in TypeScript that check a value. The example `function f(x: any): asserts x {}` demonstrates how the `asserts` keyword is used to indicate a type predicate that narrows down the type of a variable. ```typescript function f(x: any): asserts x { } ``` ```tree-sitter-grammar (program (function_declaration (identifier) (formal_parameters (required_parameter (identifier) (type_annotation (predefined_type)))) (asserts_annotation (asserts (identifier))) (statement_block))) ``` -------------------------------- ### CMake Project Configuration Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/CMakeLists.txt Sets up the minimum CMake version, project name, version, description, and homepage URL. It also specifies the programming languages used (C) and configures options for shared libraries and allocator reuse. ```cmake cmake_minimum_required(VERSION 3.13) project(tree-sitter-typescript VERSION "0.23.2" DESCRIPTION "TypeScript and TSX grammars for tree-sitter" HOMEPAGE_URL "https://github.com/tree-sitter/tree-sitter-typescript" 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 14 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") include(GNUInstallDirs) ``` -------------------------------- ### Parse TypeScript and TSX with Go tree-sitter Source: https://context7.com/tree-sitter/tree-sitter-typescript/llms.txt This Go code snippet demonstrates how to use the `go-tree-sitter` library with the `tree-sitter-typescript` grammar. It shows the initialization of the parser for both TypeScript and TSX, parsing sample code, and basic tree traversal. Dependencies include `go-tree-sitter` and `tree-sitter-typescript`. It takes byte slices of code as input and outputs the root node type, child count, and error status. ```go package main import ( "context" "fmt" sitter "github.com/tree-sitter/go-tree-sitter" tree_sitter_typescript "github.com/tree-sitter/tree-sitter-typescript" ) func main() { // Parse TypeScript code typescript := sitter.NewLanguage(tree_sitter_typescript.LanguageTypescript()) parser := sitter.NewParser() parser.SetLanguage(typescript) sourceCode := []byte(` enum Direction { North, South, East, West } interface Point { x: number; y: number; } function move(point: Point, direction: Direction, distance: number): Point { switch (direction) { case Direction.North: return { ...point, y: point.y + distance }; case Direction.South: return { ...point, y: point.y - distance }; case Direction.East: return { ...point, x: point.x + distance }; case Direction.West: return { ...point, x: point.x - distance }; } } `) tree := parser.Parse(sourceCode, nil) defer tree.Close() rootNode := tree.RootNode() fmt.Printf("Root node type: %s\n", rootNode.Type()) fmt.Printf("Number of children: %d\n", rootNode.ChildCount()) fmt.Printf("Has errors: %v\n", rootNode.HasError()) // Walk the tree cursor := sitter.NewTreeCursor(rootNode) defer cursor.Close() visitNode(cursor, 0) // Parse TSX code tsx := sitter.NewLanguage(tree_sitter_typescript.LanguageTSX()) parser.SetLanguage(tsx) tsxCode := []byte(` interface HeaderProps { title: string; subtitle?: string; } const Header: React.FC = ({ title, subtitle }) => { return (

{title}

{subtitle &&

{subtitle}

}
); }; `) tsxTree := parser.Parse(tsxCode, nil) defer tsxTree.Close() fmt.Printf("\nTSX Root node type: %s\n", tsxTree.RootNode().Type()) fmt.Printf("TSX Has errors: %v\n", tsxTree.RootNode().HasError()) } func visitNode(cursor *sitter.TreeCursor, depth int) { node := cursor.CurrentNode() indent := "" for i := 0; i < depth; i++ { indent += " " } fmt.Printf("%s%s\n", indent, node.Type()) if cursor.GoToFirstChild() { visitNode(cursor, depth+1) cursor.GoToParent() } for cursor.GoToNextSibling() { visitNode(cursor, depth) } } ``` -------------------------------- ### TypeScript String Manipulation with Template Literals Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Provides examples of advanced string manipulation using TypeScript's template literal types. This includes inferring parts of a string, applying conditional logic based on string content, and constructing new string types dynamically. These examples often involve recursive type definitions or complex conditional checks. ```typescript type StringToNumber = S extends `${infer N extends number}` ? N : never; type Trim = S extends `${infer R}` ? Trim : S; type PrefixSuffix = S extends `${infer Prefix}${infer Suffix}` ? `${P}${Prefix}${Suffix}${Suf}` : never; ``` -------------------------------- ### Parse TypeScript and TSX with tree-sitter in Rust Source: https://context7.com/tree-sitter/tree-sitter-typescript/llms.txt Demonstrates parsing both TypeScript and TSX code using the tree-sitter-typescript Rust crate. It shows how to initialize the parser, load language definitions (LANGUAGE_TYPESCRIPT, LANGUAGE_TSX), parse source code, and utilize syntax highlighting queries. Dependencies include the `tree-sitter` and `tree-sitter-typescript` crates. ```rust use tree_sitter::{Parser, Query, QueryCursor}; use tree_sitter_typescript::{LANGUAGE_TYPESCRIPT, LANGUAGE_TSX, HIGHLIGHTS_QUERY, TYPESCRIPT_NODE_TYPES}; fn main() { // Parse TypeScript code let mut parser = Parser::new(); let language = LANGUAGE_TYPESCRIPT.into(); parser.set_language(&language) .expect("Error loading TypeScript parser"); let source_code = r#" function fibonacci(n: number): number { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } type Result = { ok: true; value: T } | { ok: false; error: E }; async function fetchData(url: string): Promise> { try { const response = await fetch(url); const data = await response.json(); return { ok: true, value: data }; } catch (error) { return { ok: false, error: error as Error }; } } "#; let tree = parser.parse(source_code, None).unwrap(); let root_node = tree.root_node(); assert!(!root_node.has_error()); println!("Parsed successfully: {}", root_node.kind()); println!("Byte range: {}..{}", root_node.start_byte(), root_node.end_byte()); // Use syntax highlighting query let query = Query::new(&language, HIGHLIGHTS_QUERY) .expect("Error creating query"); let mut cursor = QueryCursor::new(); let captures = cursor.captures(&query, root_node, source_code.as_bytes()); for (match_, _) in captures { for capture in match_.captures { let name = &query.capture_names()[capture.index as usize]; let text = &source_code[capture.node.byte_range()]; println!( "{}: {}", name, text); } } // Parse TSX code parser.set_language(&LANGUAGE_TSX.into()) .expect("Error loading TSX parser"); let tsx_code = r#" const TodoList: React.FC<{ items: string[] }> = ({ items }) => (
    {items.map((item, index) => (
  • {item}
  • ))}
); "#; let tsx_tree = parser.parse(tsx_code, None).unwrap(); assert!(!tsx_tree.root_node().has_error()); println!("TSX parsed successfully"); } ``` -------------------------------- ### Use Tree-sitter Queries for Syntax Highlighting in Node.js Source: https://context7.com/tree-sitter/tree-sitter-typescript/llms.txt Shows how to use Tree-sitter's query system in Node.js to extract syntax information for tasks like highlighting. It loads a TypeScript language configuration, reads a query file (e.g., highlights.scm), parses code, and then iterates through the query captures to identify code elements and their locations. ```javascript // Node.js - Using queries for syntax highlighting const Parser = require('tree-sitter'); const { typescript } = require('tree-sitter-typescript'); const fs = require('fs'); const parser = new Parser(); parser.setLanguage(typescript); // The query files are in the queries/ directory const highlightsQuery = fs.readFileSync('./queries/highlights.scm', 'utf8'); const query = typescript.language.query(highlightsQuery); const code = ` function calculate(x: number, y: number): number { const result = x + y; return result; } `; const tree = parser.parse(code); const captures = query.captures(tree.rootNode); captures.forEach(capture => { const { name, node } = capture; const text = code.slice(node.startIndex, node.endIndex); console.log(`${name}: "${text}" at ${node.startPosition.row}:${node.startPosition.column}`); }); // Example output: // function: "function" at 1:0 // function.name: "calculate" at 1:9 // variable.parameter: "x" at 1:19 // type: "number" at 1:22 // variable.parameter: "y" at 1:30 // type: "number" at 1:33 // keyword: "const" at 2:2 // variable: "result" at 2:8 // keyword: "return" at 3:2 ``` -------------------------------- ### Parse TypeScript and TSX in Swift using Tree-sitter Source: https://context7.com/tree-sitter/tree-sitter-typescript/llms.txt Demonstrates how to use the TreeSitterTypeScript and TreeSitterTSX targets within the SwiftTreeSitter framework to parse TypeScript and TSX code. It initializes a parser, sets the appropriate language, parses source code, and asserts properties of the resulting syntax tree. ```swift import XCTest import SwiftTreeSitter import TreeSitterTypeScript import TreeSitterTSX class TypeScriptParsingTests: XCTestCase { func testParseTypeScript() throws { let parser = Parser() let language = Language(language: tree_sitter_typescript()) try parser.setLanguage(language) let sourceCode = """ interface Product { id: string; name: string; price: number; inStock: boolean; } class ShoppingCart { private items: Map = new Map(); addItem(product: Product, quantity: number = 1): void { const currentQty = this.items.get(product.id) ?? 0; this.items.set(product.id, currentQty + quantity); } getTotalItems(): number { return Array.from(this.items.values()) .reduce((sum, qty) => sum + qty, 0); } } const cart = new ShoppingCart(); """ let tree = parser.parse(sourceCode) XCTAssertNotNil(tree) let rootNode = tree!.rootNode XCTAssertEqual(rootNode.nodeType, "program") XCTAssertFalse(rootNode.hasError) XCTAssertTrue(rootNode.childCount > 0) print("Parsed TypeScript successfully") print("Root node: \(rootNode.nodeType)") print("Children count: \(rootNode.childCount)") } func testParseTSX() throws { let parser = Parser() let language = Language(language: tree_sitter_tsx()) try parser.setLanguage(language) let tsxCode = """ import { useState, useEffect } from 'react'; interface UserCardProps { userId: number; onUserLoad?: (user: User) => void; } const UserCard: React.FC = ({ userId, onUserLoad }) => { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { fetch(`/api/users/${userId}`) .then(res => res.json()) .then(data => { setUser(data); setLoading(false); onUserLoad?.(data); }); }, [userId]); if (loading) { return
Loading...
; } return (

{user?.name}

{user?.email}

); }; export default UserCard; """ let tree = parser.parse(tsxCode) XCTAssertNotNil(tree) let rootNode = tree!.rootNode XCTAssertEqual(rootNode.nodeType, "program") XCTAssertFalse(rootNode.hasError) print("Parsed TSX successfully") } } ``` -------------------------------- ### Flow Type Parameter Constraint Syntax Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Demonstrates Flow's syntax for constraining type parameters in generic types. This example constrains a type parameter T to extend Element. ```flow type HandlerFunction = void ``` ```tree-sitter-typescript (program (type_alias_declaration (type_identifier) (type_parameters (type_parameter (type_identifier) (constraint (type_identifier)))) (predefined_type))) ``` -------------------------------- ### TypeScript Constructor Type Declaration Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Demonstrates the syntax for a constructor type in TypeScript, including generic type parameters and multiple parameters. The grammar snippet shows the tree-sitter nodes for type parameters, formal parameters, and the return type identifier. ```typescript let x: new < T1, T2 > ( p1, p2 ) => R; ``` ```tree-sitter-grammar (program (lexical_declaration (variable_declarator (identifier) (type_annotation (constructor_type (type_parameters (type_parameter (type_identifier)) (type_parameter (type_identifier))) (formal_parameters (required_parameter (identifier)) (required_parameter (identifier))) (type_identifier)))))) ``` -------------------------------- ### Subdirectory Inclusion and Testing Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/CMakeLists.txt Includes the 'typescript' and 'tsx' subdirectories, which likely contain their respective grammar definitions and build configurations. Also defines a custom target 'ts-test' to run tests using the tree-sitter CLI. ```cmake add_subdirectory(typescript tree-sitter-typescript) add_subdirectory(tsx tree-sitter-tsx) add_custom_target(ts-test "${TREE_SITTER_CLI}" test WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" COMMENT "tree-sitter test") ``` -------------------------------- ### Require TypeScript and TSX Grammars for Tree-sitter Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/README.md Demonstrates how to import and access the TypeScript and TSX grammars provided by the 'tree-sitter-typescript' library. These grammars are essential for parsing TypeScript and TSX code with the tree-sitter parsing library. ```javascript require("tree-sitter-typescript").typescript; // TypeScript grammar require("tree-sitter-typescript").tsx; // TSX grammar ``` -------------------------------- ### TypeScript Class Methods with Keyword Names Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/declarations.txt Demonstrates how Tree-sitter handles method declarations in TypeScript classes where method names might be keywords. This includes methods with accessibility modifiers and type annotations. ```typescript class Foo { private async() {}; get(): Result {}; private set(plugin) {}; } ``` ```tree-sitter-typescript (program (class_declaration (type_identifier) (class_body (method_definition (accessibility_modifier) (property_identifier) (formal_parameters) (statement_block)) (method_definition (property_identifier) (formal_parameters) (type_annotation (type_identifier)) (statement_block)) (method_definition (accessibility_modifier) (property_identifier) (formal_parameters (required_parameter (identifier))) (statement_block))))) ``` -------------------------------- ### TypeScript Function Type Syntax Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/types.txt Illustrates the TypeScript syntax for defining function types, including parameter names and their respective types, along with the return type. ```typescript let score: (string: string, query: string) => number ``` ```tree-sitter-typescript (program (lexical_declaration (variable_declarator (identifier) (type_annotation (function_type (formal_parameters (required_parameter (identifier) (type_annotation (predefined_type))) (required_parameter (identifier) (type_annotation (predefined_type)))) (predefined_type)))))) ``` -------------------------------- ### TypeScript Array with Empty Elements Grammar Source: https://github.com/tree-sitter/tree-sitter-typescript/blob/master/test/corpus/expressions.txt This snippet shows the tree-sitter grammar for parsing arrays in TypeScript that contain empty elements. It represents an array with interspersed identifiers and empty slots. ```tree-sitter grammar (program (expression_statement (array (identifier) (identifier) (identifier)))) ```