### Setup Git Hooks with prek Source: https://ast-grep.github.io/contributing/development.html Installs git hook scripts for type checking, formatting, and clippy using the prek tool. Run this after installing rustup. ```bash prek install ``` -------------------------------- ### Verify installation Source: https://ast-grep.github.io/guide/quick-start.html Check the help menu to ensure the CLI is installed correctly. ```shell ast-grep --help # if you are not on Linux sg --help ``` -------------------------------- ### Install ast-grep Python library Source: https://ast-grep.github.io/guide/api-usage/py-api.html Use pip to install the library from PyPI. ```bash pip install ast-grep-py ``` -------------------------------- ### Example YAML Configuration Source: https://ast-grep.github.io/catalog/yaml An example of a YAML configuration file that might be checked by the detect-host-port rule. ```yaml db: username: root password: root server: host: 127.0.0.1 port: 8001 ``` -------------------------------- ### Install @ast-grep/napi with npm Source: https://ast-grep.github.io/llms-full.txt Install the ast-grep Node.js package using npm. ```bash npm install --save @ast-grep/napi ``` -------------------------------- ### Common Workflow Example Source: https://ast-grep.github.io/llms-full.txt A step-by-step example demonstrating the common workflow for using ast-grep's Python API. ```python from ast_grep_py import SgRoot root = SgRoot("print('hello world')", "python") # 1. parse node = root.root() # 2. get root print_stmt = node.find(pattern="print($A)") # 3. find print_stmt.get_match('A').text() # 4. collect information # Expected output: 'hello world' ``` -------------------------------- ### Install @ast-grep/napi with pnpm Source: https://ast-grep.github.io/llms-full.txt Install the ast-grep Node.js package using pnpm. ```bash pnpm add @ast-grep/napi ``` -------------------------------- ### Install ast-grep.el via straight.el Source: https://ast-grep.github.io/guide/tools/editors.html Install the ast-grep Emacs package using straight.el. ```elisp (straight-use-package '(ast-grep :type git :host github :repo "SunskyXH/ast-grep.el")) ``` -------------------------------- ### Install ast-grep Source: https://ast-grep.github.io/guide/quick-start.html Commands to install the ast-grep CLI tool using different package managers. ```shell # install via homebrew brew install ast-grep ``` ```shell # install via MacPorts sudo port install ast-grep ``` ```shell # try ast-grep in nix-shell nix-shell -p ast-grep ``` ```shell # install via cargo cargo install ast-grep --locked ``` ```shell # install via npm npm i @ast-grep/cli -g # note, for pnpm, you may need manually approve postinstall script # pnpm approve-builds ``` ```shell # install via pip pip install ast-grep-cli ``` -------------------------------- ### Full Example: Parse, Find, and Extract Source: https://ast-grep.github.io/guide/api-usage/js-api.html A complete example demonstrating parsing JavaScript, finding a console.log statement, and extracting its argument. ```javascript import { parse, Lang } from '@ast-grep/napi'; let source = `console.log("hello world")` const ast = parse(Lang.JavaScript, source) // 1. parse the source const root = ast.root() // 2. get the root const node = root.find('console.log($A)') // 3. find the node node.getMatch('A').text() // 4. collect the info // "hello world" ``` -------------------------------- ### Install flamegraph Source: https://ast-grep.github.io/blog/optimize-ast-grep.html Install the flamegraph profiling tool using cargo. ```bash cargo install flamegraph ``` -------------------------------- ### Install ast-grep Source: https://ast-grep.github.io/blog/migrate-bevy.html Install the ast-grep binary using cargo or brew. This tool is essential for searching and replacing code based on abstract syntax trees. ```shell cargo install ast-grep ``` ```shell brew install ast-grep ``` -------------------------------- ### Install ast-grep Napi Package Source: https://ast-grep.github.io/guide/api-usage/js-api.html Install the ast-grep napi package using npm or pnpm. ```bash npm install --save @ast-grep/napi ``` ```bash pnpm add @ast-grep/napi ``` -------------------------------- ### Install Tree-sitter CLI Source: https://ast-grep.github.io/advanced/custom-language.html Use npm to install the Tree-sitter command line tool globally. ```bash npm install -g tree-sitter-cli ``` -------------------------------- ### MobX Component Example Source: https://ast-grep.github.io/llms-full.txt Example of a MobX observer component before and after refactoring. ```js export const Example = observer(() => { return
Hello World
}) ``` ```js export const Example = observer(() => { // [!code --] return
Hello World
// [!code --] }) // [!code --] const BaseExample = () => { // [!code ++] return
Hello World
// [!code ++] } // [!code ++] export const Example = observer(BaseExample) // [!code ++] ``` -------------------------------- ### Install Rust Toolchain Source: https://ast-grep.github.io/contributing/development.html Installs the stable Rust toolchain using rustup. This is a prerequisite for building ast-grep. ```bash rustup install stable ``` -------------------------------- ### Example GraphQL in JavaScript Source: https://ast-grep.github.io/advanced/language-injection.html A sample JavaScript file using the graphql tag. ```js import React from "react" import { graphql } from "react-relay" const artistsQuery = graphql` query ArtistQuery($artistID: String!) { artist(id: $artistID) { name ...ArtistDescription_artist } } ` ``` -------------------------------- ### Python Lambda Rewrite Example Source: https://ast-grep.github.io/llms-full.txt Example of source code and the resulting output after applying the lambda-to-def rule. ```python b = lambda: 123 ``` ```python def b(): return 123 ``` -------------------------------- ### Ast-grep Get Match Examples Source: https://ast-grep.github.io/llms-full.txt Illustrates using getMatch for single meta variables and getMultipleMatches for multi meta variables, showing their return types and behavior. ```typescript const src = ` console.log('hello') logger('hello', 'world', '!') ` const root = parse(Lang.JavaScript, src).root() const node = root.find('console.log($A)') const arg = node.getMatch("A") // returns SgNode('hello') arg !== null // true, node is found arg.text() // returns 'hello' // returns [] because $A and $$$A are different node.getMultipleMatches('A') const logs = root.find('logger($$$ARGS)') // returns [SgNode('hello'), SgNode(','), SgNode('world'), SgNode(','), SgNode('!')] logs.getMultipleMatches("ARGS") logs.getMatch("A") // returns null ``` -------------------------------- ### Python Lambda Rewrite Example Source: https://ast-grep.github.io/guide/rewrite-code.html Input and output code examples demonstrating how ast-grep preserves indentation during a rewrite. ```python b = lambda: 123 ``` ```python def b(): return 123 ``` ```python if True: c = lambda: 456 def c(): return 456 ``` -------------------------------- ### Console Usage Example Source: https://ast-grep.github.io/llms-full.txt Demonstrates allowed and disallowed console usage patterns. ```typescript console.debug('') try { console.log('hello') } catch (e) { console.error(e) // OK } ``` ```typescript console.debug('') // [!code --] try { console.log('hello') // [!code --] } catch (e) { console.error(e) // OK } ``` -------------------------------- ### Install ast-grep Node.js Binding Source: https://ast-grep.github.io/ Install the Node.js binding for ast-grep to use its functionality programmatically within JavaScript projects. ```bash npm install @ast-grep/napi ``` -------------------------------- ### Working Meta Variable Examples Source: https://ast-grep.github.io/advanced/pattern-parse.html Provides examples of valid meta variable syntax in ast-grep patterns, such as single identifiers, member expressions, and function calls with arguments. ```plaintext $A $A.$B $A.method($B) ``` -------------------------------- ### Python OpenAI SDK Migration Example Source: https://ast-grep.github.io/llms-full.txt Example code demonstrating the migration of an older OpenAI SDK usage to the newer version, including changes to imports, API key initialization, and method calls. ```python import os import openai from flask import Flask, jsonify app = Flask(__name__) openai.api_key = os.getenv("OPENAI_API_KEY") @app.route("/chat", methods=("POST")) def index(): animal = request.form["animal"] response = openai.Completion.create( model="text-davinci-003", prompt=generate_prompt(animal), temperature=0.6, ) return jsonify(response.choices) ``` -------------------------------- ### Configure nvim-lspconfig for ast-grep Source: https://ast-grep.github.io/guide/tools/editors.html Setup ast-grep as an LSP server in Neovim using nvim-lspconfig. ```lua require('lspconfig').ast_grep.setup({ -- these are the default options, you only need to specify -- options you'd like to change from the default cmd = { 'ast-grep', 'lsp' }, filetypes = { "c", "cpp", "rust", "go", "java", "python", "javascript", "typescript", "html", "css", "kotlin", "dart", "lua" }, root_dir = require('lspconfig.util').root_pattern('sgconfig.yaml', 'sgconfig.yml') }) ``` -------------------------------- ### Path Traversal Examples (Ruby) Source: https://ast-grep.github.io/llms-full.txt Provides concrete Ruby code examples demonstrating patterns that could lead to Path Traversal vulnerabilities, matching the rule defined in YAML. ```ruby # Pattern 1: Rails.root.join with variable Rails.root.join('uploads', params[:filename]) Rails.root.join('data', user_input, 'file.txt') # Pattern 2: File.join with variable File.join('/var/www', params[:path]) File.join(base_path, user_id, filename) # Pattern 3: send_file with variable send_file params[:file] send_file user.document_path ``` -------------------------------- ### Test File Example for ast-grep Rule Source: https://ast-grep.github.io/llms-full.txt An example of a test file for the 'no-await-in-loop' rule, listing valid and invalid code snippets to test the rule's effectiveness. ```yaml id: no-await-in-loop valid: - for (let a of b) { console.log(a) } # .... more valid test cases invalid: - async function foo() { for (var bar of baz) await bar; } # .... more invalid test cases ``` -------------------------------- ### JavaScript Console Log Example Source: https://ast-grep.github.io/llms-full.txt Example JavaScript code demonstrating statements that might be targeted by a selector. ```js console.log("Hello") console.log("World"); ``` -------------------------------- ### Migrate add_system_to_stage to add_system Source: https://ast-grep.github.io/blog/migrate-bevy.html Example of migrating add_system_to_stage to the new add_system API. ```rust // Before: app.add_system_to_stage(CoreStage::PostUpdate, my_system) // After: app.add_system(my_system.in_base_set(CoreSet::PostUpdate)) ``` -------------------------------- ### Non-matching examples for meta variables Source: https://ast-grep.github.io/guide/pattern-syntax.html Examples of code that do not match the console.log($GREETING) pattern due to comments, strings, or argument count mismatches. ```javascript // console.log(123) in comment is not matched 'console.log(123) in string' // is not matched as well console.log() // mismatch argument console.log(a, b) // too many arguments ``` -------------------------------- ### Optional Type Hint Example Source: https://ast-grep.github.io/llms-full.txt Shows the transformation of type hints in function signatures. ```python def a(arg: Optional[int]): pass ``` ```python def a(arg: Optional[int]): pass # [!code --] def a(arg: int | None): pass # [!code ++] ``` -------------------------------- ### JavaScript Diff Example Source: https://ast-grep.github.io/llms-full.txt Shows a code change using diff syntax. ```js var a = 123 // [!code --] let a = 123 // [!code ++] ``` -------------------------------- ### ast-grep lsp Source: https://ast-grep.github.io/llms-full.txt Start a language server for editor integration and diagnostics reporting. ```APIDOC ## `ast-grep lsp` ### Description Start a language server to [report diagnostics](/guide/scan-project.html) in your project. This is useful for editor integration. See [editor integration](/guide/tools/editors.html) for more details. ### Usage ```shell ast-grep lsp ``` ``` -------------------------------- ### Ast-grep Node Range Example Source: https://ast-grep.github.io/llms-full.txt Shows how to use the range() method to get the start and end positions (line, column, index) of a node. ```typescript const rng = node.range() const pos = rng.start // or rng.end, both are `Pos` objects pos.line // 0, line starts with 0 pos.column // 0, column starts with 0 rng.end.index // 17, index starts with 0 ``` -------------------------------- ### Go Test Function Example Source: https://ast-grep.github.io/catalog/go/find-func-declaration-with-prefix.html An example of a Go test function that would be matched by the YAML rule above, demonstrating a function name starting with 'Test'. ```go package abs import "testing" func TestAbs(t *testing.T) { got := Abs(-1) if got != 1 { t.Errorf("Abs(-1) = %d; want 1", got) } } ``` -------------------------------- ### Initialize ast-grep project Source: https://ast-grep.github.io/guide/scan-project.html Interactive output from running the ast-grep new command to scaffold a project. ```markdown No sgconfig.yml found. Creating a new ast-grep project... > Where do you want to have your rules? rules > Do you want to create rule tests? Yes > Where do you want to have your tests? rule-tests > Do you want to create folder for utility rules? Yes > Where do you want to have your utilities? utils Your new ast-grep project has been created! ``` -------------------------------- ### Example of await in Promise.all Source: https://ast-grep.github.io/catalog/typescript/no-await-in-promise-all.html Code demonstrating the pattern that triggers the no-await-in-promise-all rule. ```typescript const [foo, bar] = await Promise.all([ await getFoo(), getBar(), (async () => { await getBaz()})(), ]) ``` -------------------------------- ### JavaScript Function Declaration Example Source: https://ast-grep.github.io/llms-full.txt An example of JavaScript code demonstrating a React component that uses custom hooks, which typically start with 'use'. This code is used to test the pattern matching rule. ```javascript function ReactComponent() { const data = notHook() const [foo, setFoo] = useState('') } ``` -------------------------------- ### Ast-grep Node Text Example Source: https://ast-grep.github.io/llms-full.txt Demonstrates how to get the full text content of a node using the text() method. ```typescript const ast = parse(Lang.JavaScript, "console.log('hello world')") root = ast.root() root.text() // will return "console.log('hello world')" ``` -------------------------------- ### Example code for type hinting Source: https://ast-grep.github.io/catalog/python/refactor-pytest-fixtures.html Sample Python code demonstrating fixture usage before adding type hints. ```python @pytest.fixture def foo() -> int: return 5 @pytest.fixture(scope="function") def some_fixture(foo) -> str: return str(foo) def regular_function(foo) -> None: ... def test_code(foo) -> None: assert foo == 5 ``` -------------------------------- ### Example of Functions Mimicking React Hooks Source: https://ast-grep.github.io/catalog/tsx/unnecessary-react-hook.html These TypeScript examples demonstrate functions that are named like React hooks (e.g., starting with 'use') but do not contain any actual hook calls. Such functions can often be refactored into plain JavaScript functions. ```tsx function useIAmNotHookActually(args) { console.log('Called in React but I dont need to be a hook') return args.length } const useIAmNotHookToo = (...args) => { console.log('Called in React but I dont need to be a hook') return args.length } function useTrueHook() { useEffect(() => { console.log('Real hook') }) } ``` -------------------------------- ### Get Node Range Source: https://ast-grep.github.io/llms-full.txt The `range` method returns the start and end positions of a node in the source code. Each position includes line, column, and index. ```python rng = node.range() pos = rng.start # or rng.end, both are `Pos` objects pos.line # 0, line starts with 0 pos.column # 0, column starts with 0 rng.end.index # 17, index starts with 0 ``` -------------------------------- ### Inspect Project Directory and Configuration Source: https://ast-grep.github.io/guide/project/project-config.html Use the `--inspect summary` flag with `ast-grep scan` to view the identified project directory and the configuration file path being used. ```bash ast-grep scan --inspect summary ``` -------------------------------- ### Rust String Character Offset Example Source: https://ast-grep.github.io/catalog/rust/boshen-footgun.html Demonstrates the difference between character and byte offsets when iterating over a Rust string using `char_indices()`. Note that the character 'e' starts at byte offset 3. ```rs let yes = "y̆es"; let mut char_indices = yes.char_indices(); assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆') assert_eq!(Some((1, '\u{0306}')), char_indices.next()); // note the 3 here - the last character took up two bytes assert_eq!(Some((3, 'e')), char_indices.next()); assert_eq!(Some((4, 's')), char_indices.next()); ``` -------------------------------- ### Nested Type Example Source: https://ast-grep.github.io/catalog/python An example of a complex nested type annotation. ```python results: Optional[Union[List[Union[str, dict]], str]] ``` -------------------------------- ### Initialize grug-far with ast-grep engine Source: https://ast-grep.github.io/guide/tools/editors.html Launch grug-far using the ast-grep search engine. ```vim :lua require('grug-far').grug_far({ engine = 'astgrep' }) ``` -------------------------------- ### Project folder structure Source: https://ast-grep.github.io/guide/scan-project.html The resulting directory layout after initializing an ast-grep project. ```bash my-awesome-project |- rules # where rules go |- rule-tests # test cases for rules |- utils # global utility rules for reusing |- sgconfig.yml # root configuration file ``` -------------------------------- ### Barrel Import Example Source: https://ast-grep.github.io/advanced/find-n-patch.html Example of a barrel import statement that consolidates multiple exports. ```js import {a, b, c} from './barrel'; ``` -------------------------------- ### Example code for fixture renaming Source: https://ast-grep.github.io/catalog/python/refactor-pytest-fixtures.html Sample Python code demonstrating fixture usage before renaming. ```python @pytest.fixture def foo() -> int: return 5 @pytest.fixture(scope="function") def some_fixture(foo: int) -> str: return str(foo) def regular_function(foo) -> None: ... def test_code(foo: int) -> None: assert foo == 5 ``` -------------------------------- ### XState v5 Migrated Code Example (Diff) Source: https://ast-grep.github.io/catalog/typescript/migrate-xstate-v5.html This JavaScript snippet shows the equivalent code after migration to XState v5, using `createMachine`, `createActor`, and `provide`. ```javascript import { Machine, interpret } from 'xstate'; import { createMachine, createActor } from 'xstate'; const machine = Machine({ /*...*/}); const machine = createMachine({ /*...*/}); const specificMachine = machine.withConfig({ const specificMachine = machine.provide({ actions: { /* ... */ }, guards: { /* ... */ }, services: { /* ... */ }, actors: { /* ... */ }, }); const actor = interpret(specificMachine, { const actor = createActor(specificMachine, { /* actor options */ }); ``` -------------------------------- ### Example of async to sync conversion Source: https://ast-grep.github.io/llms-full.txt Input code and the resulting diff after removing async and await keywords. ```python async def main3(): await somecall(1, 5) ``` ```python async def main3(): # [!code --] await somecall(1, 5) # [!code --] def main3(): # [!code ++] somecall(1, 5) # [!code ++] ``` -------------------------------- ### Snapshot Diff Example Source: https://ast-grep.github.io/llms-full.txt An example of a snapshot diff highlighting changes in red and green, prompting for acceptance. ```diff [Wrong] no-await-in-loop snapshot is different from baseline. Diff: labels: - source: await bar style: Primary - start: 2 + start: 28 end: 37 - source: do { await bar; } while (baz); style: Secondary For Code: async function foo() { do { await bar; } while (baz); } Accept new snapshot? (Yes[y], No[n], Accept All[a], Quit[q]) ``` -------------------------------- ### Biome DSL Example with Mixed Paradigms Source: https://ast-grep.github.io/blog/yaml-vs-dsl.html Demonstrates a mix of declarative, logic, and imperative paradigms in Biome's DSL. Note the use of `$method(<:$message)` for pattern matching and `where` clauses for logic. ```javascript `$method($message)` where { $method <: `console.log`, if ($message <: r"Hello, .*!") { $linter = "hello world" } else { $linter = "not hello" }, register_diagnostic( span = $method, message = $linter ) } ``` -------------------------------- ### Redundant useState Type Example Source: https://ast-grep.github.io/catalog/tsx/redundant-usestate-type.html An example of a component using an unnecessary string type annotation for useState. ```ts function Component() { const [name, setName] = useState('React') } ``` -------------------------------- ### Correct ConfigureSet Usage Source: https://ast-grep.github.io/blog/migrate-bevy.html Manual fix for configure_set calls to resolve system ordering conflicts. ```diff --- a/src/lib.rs +++ b/src/lib.rs @@ -225,7 +225,7 @@ impl Plugin for BigBrainPlugin { - app.configure_set(BigBrainStage::Scorers.after(First)); + app.configure_set(BigBrainStage::Scorers.in_base_set(First)); @@ -242,12 +242,12 @@ impl Plugin for BigBrainPlugin { - app.configure_set(BigBrainStage::Actions.after(PreUpdate)); + app.configure_set(BigBrainStage::Actions.in_base_set(PreUpdate)); ``` -------------------------------- ### Ant Design Vue Upgrade Example Source: https://ast-grep.github.io/catalog/html Input HTML template demonstrating the attribute replacement. ```html ``` -------------------------------- ### Define TypeScript AST Node Example Source: https://ast-grep.github.io/blog/typed-napi.html A concrete example of a function declaration node definition within a TypeMap. ```typescript type TypeScript = { // AST node type definition function_declaration: { type: "function_declaration", // kind named: true, // is named fields: { body: { types: [ { type: "statement_block", named: true } ] }, } }, ... } ``` -------------------------------- ### Ast-grep Refinement Example Source: https://ast-grep.github.io/llms-full.txt Provides an example of using the matches() method to refine a found node based on a more specific pattern. ```typescript const node = root.find('console.log($A)') node.matches('console.$METHOD($B)') // true ``` -------------------------------- ### XState v4 Code Example Source: https://ast-grep.github.io/catalog/typescript/migrate-xstate-v5.html This JavaScript snippet demonstrates the usage of `Machine` and `interpret` from XState v4, along with `withConfig` for configuration. ```javascript import { Machine, interpret } from 'xstate'; const machine = Machine({ /*...*/}); const specificMachine = machine.withConfig({ actions: { /* ... */ }, guards: { /* ... */ }, services: { /* ... */ }, }); const actor = interpret(specificMachine, { /* actor options */ }); ``` -------------------------------- ### Rust Proper Unsafe Function Example Source: https://ast-grep.github.io/catalog/rust/redundant-unsafe-function.html An example of a correctly implemented unsafe Rust function that includes an `unsafe` block for its operations. ```rust // Should NOT match - unsafe function with unsafe block unsafe fn proper_unsafe() -> *const i32 { unsafe { let ptr = 0x1234 as *const i32; ptr } } ``` -------------------------------- ### Example Golang code for function call matching Source: https://ast-grep.github.io/catalog/go/match-function-call.html A sample Golang function call that can be matched using the defined rule. ```go func main() { fmt.Println("OK") } ``` -------------------------------- ### C++ Format String Vulnerability Examples Source: https://ast-grep.github.io/catalog/cpp Examples demonstrating code vulnerable to format string exploits and the corrected, safe versions. ```cpp // Error fprintf(stderr, out); sprintf(&buffer[2], obj->Text); sprintf(buf1, Text_String(TXT_WAITING_FOR_CONNECTIONS)); // OK fprintf(stderr, "%s", out); sprintf(&buffer[2], "%s", obj->Text); sprintf(buf1, "%s", Text_String(TXT_WAITING_FOR_CONNECTIONS)); ``` -------------------------------- ### Example: Chai 'should' to 'expect' Migration Source: https://ast-grep.github.io/catalog/typescript Demonstrates the migration of Chai 'should' style assertions to 'expect' style for both `instanceof` and generic property checks. ```javascript it('should produce an instance of chokidar.FSWatcher', () => { watcher.should.be.an.instanceof(chokidar.FSWatcher); }); it('should expose public API methods', () => { watcher.on.should.be.a('function'); watcher.emit.should.be.a('function'); watcher.add.should.be.a('function'); watcher.close.should.be.a('function'); watcher.getWatched.should.be.a('function'); }); ``` -------------------------------- ### TypeScript Diff Example Source: https://ast-grep.github.io/catalog/typescript/no-console-except-catch.html This TypeScript code snippet is presented as a diff, illustrating the same `console` usage as the example. It highlights the disallowed and allowed `console` calls. ```typescript console.debug('') try { console.log('hello') } catch (e) { console.error(e) // OK } ``` -------------------------------- ### Python Dictionary Rewrite Example Source: https://ast-grep.github.io/llms-full.txt This example demonstrates a Python rewrite rule to transform a dictionary assignment. It's useful for refactoring dictionary creations or modifications. ```yaml rewriters: - id: dict-rewrite rule: kind: keyword_argument all: - has: field: name pattern: $KEY - has: field: value pattern: $VAL fix: "'$KEY': $VAL'" # find the target node rule: pattern: dict($$ARGUMENTS) # apply rewriters to sub node transform: LITERAL: rewrite: rewriters: [dict-rewrite] source: $$ARGUMENTS # combine and replace fix: '{ $LITERAL }' ``` -------------------------------- ### TypeScript Function Declaration Example Source: https://ast-grep.github.io/llms-full.txt An example of TypeScript code for a function declaration. This is provided to illustrate differences in ASTs between similar languages like JavaScript and TypeScript. ```typescript function test(a) {} ``` -------------------------------- ### Automate System Registration Migration Source: https://ast-grep.github.io/blog/migrate-bevy.html Use ast-grep to replace deprecated system-to-stage registration with the new in-base-set pattern. ```bash -p '$APP.add_system_to_stage($STAGE, $SYS)' \ -r '$APP.add_system($SYS.in_base_set($STAGE))' -i ``` -------------------------------- ### Running Rules with ast-grep CLI Source: https://ast-grep.github.io/llms-full.txt Demonstrates how to execute ast-grep rules using the CLI, either by referencing a rule file or defining the rule inline. ```APIDOC ## Run the Rule There are several ways to run the rule. We will illustrate several ast-grep features here. ### `ast-grep scan --rule` The `scan` subcommand of ast-grep CLI can run one rule at a time. To do so, you need to save the rule above in a file on the disk, say `no-await-in-promise-all.yml`. Then you can run the following command to scan your codebase. In the example below, we are scanning a `test.ts` file. ```bash ast-grep scan --rule no-await-in-promise-all.yml test.ts ``` ### `ast-grep scan --inline-rules` You can also run the rule directly from the command line without saving the rule to a file. The `--inline-rules` option is useful for ad-hoc search or calling ast-grep from another program. ```bash ast-grep scan --inline-rules ' id: no-await-in-promise-all language: TypeScript rule: pattern: Promise.all($A) has: pattern: await $_ stopBy: end ' test.ts ``` ### Online Playground ast-grep provides an online [playground](https://ast-grep.github.io/playground.html#eyJtb2RlIjoiQ29uZmlnIiwibGFuZyI6ImphdmFzY3JpcHQiLCJxdWVyeSI6IlByb21pc2UuYWxsKCRBKSIsInJld3JpdGUiOiIiLCJjb25maWciOiJpZDogbm8tYXdhaXQtaW4tcHJvbWlzZS1hbGxcbmxhbmd1YWdlOiBUeXBlU2NyaXB0XG5ydWxlOlxuICBwYXR0ZXJuOiBQcm9taXNlLmFsbCgkQSlcbiAgaGFzOlxuICAgIHBhdHRlcm46IGF3YWl0ICRfXG4gICAgc3RvcEJ5OiBlbmQiLCJzb3VyY2UiOiJQcm9taXNlLmFsbChbXG4gIGF3YWl0IFByb21pc2UucmVzb2x2ZSgxMjMpXG5dKSJ9) to test your rule. You can paste the rule configuration into the playground and see the matched code. The playground also has a share button that generates a link to share the rule with others. ``` -------------------------------- ### Java Unused Variable Example Source: https://ast-grep.github.io/llms-full.txt Example demonstrating an unused Java variable. The comment `// [!code --]` indicates the line that would be removed or modified by a refactoring tool. ```java String unused = "unused"; // [!code --] String used = "used"; System.out.println(used); ``` -------------------------------- ### Migrated XState v5 Code Example (Diff) Source: https://ast-grep.github.io/catalog/typescript This snippet illustrates the changes applied by the ast-grep rules, showing the migrated code with `createMachine`, `createActor`, `provide`, and `actors`. ```javascript import { Machine, interpret } from 'xstate'; // [!code --] import { createMachine, createActor } from 'xstate'; // [!code ++] const machine = Machine({ /*...*/}); // [!code --] const machine = createMachine({ /*...*/}); // [!code ++] const specificMachine = machine.withConfig({ // [!code --] const specificMachine = machine.provide({ // [!code ++] actions: { /* ... */ }, guards: { /* ... */ }, services: { /* ... */ }, // [!code --] actors: { /* ... */ }, // [!code ++] }); const actor = interpret(specificMachine, { // [!code --] const actor = createActor(specificMachine, { // [!code ++] /* actor options */ }); ``` -------------------------------- ### Example of JSX Short Circuit Source: https://ast-grep.github.io/catalog/tsx/avoid-jsx-short-circuit.html This example demonstrates the problematic usage of the `&&` operator in JSX. When `list.length` is 0, React will render `0` instead of conditionally rendering the mapped list. ```tsx
{ list.length && list.map(i =>

) }

``` -------------------------------- ### Match Node by Character Span Source: https://ast-grep.github.io/llms-full.txt This rule matches a node based on its character span, defined by `start` and `end` positions. The range is 0-based, with the start inclusive and the end exclusive. ```yaml range: start: { line: 0, column: 0 } end: { line: 0, column: 13 } ``` -------------------------------- ### Migrate XState withConfig to provide Source: https://ast-grep.github.io/catalog/typescript/migrate-xstate-v5.html This rule identifies the usage of `withConfig` on a machine object and suggests replacing it with `provide`. ```yaml id: migrate-to-provide rule: { pattern: $MACHINE.withConfig } fix: $MACHINE.provide ``` -------------------------------- ### Example: Missing Component Decorator Source: https://ast-grep.github.io/catalog/typescript This TypeScript code demonstrates a class 'NotComponent' that uses an Angular lifecycle method 'ngOnInit' without the '@Component()' decorator, and a correct example 'Klass' with the decorator. ```typescript class NotComponent { ngOnInit() {} } @Component() class Klass { ngOnInit() {} } ``` -------------------------------- ### Initialize SgRoot and get root node Source: https://ast-grep.github.io/guide/api-usage/py-api.html Parse a source string into a syntax tree and access the root node. ```python root = SgRoot("print('hello world')", "python") # 1. parse node = root.root() # 2. get root ``` -------------------------------- ### Example JSX with Styled Components Source: https://ast-grep.github.io/advanced/language-injection.html A sample JavaScript file containing CSS-in-JS styled components. ```js import styled from 'styled-components'; const Button = styled.button` background: red; color: white; padding: 10px 20px; border-radius: 3px; ` export default function App() { return } ``` -------------------------------- ### Python Type Transformation Example Source: https://ast-grep.github.io/llms-full.txt This example shows the input and output for the recursive type rewriting configuration. It transforms a complex nested type involving `Optional` and `Union` into a more modern and readable format using the `|` operator. ```python results: Optional[Union[List[Union[str, dict]], str]] ``` ```python results: List[str | dict] | str | None ```