Skip to content

add yaml language support #73

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 22, 2025
Merged

Conversation

anoblet
Copy link
Contributor

@anoblet anoblet commented Apr 22, 2025

I get this notice at the end of the create script, I'm not sure if it's important...

Failed to find `tree-sitter` section in package.json, unable to migrate
Warning: You have not configured any parser directories!
Please run `tree-sitter init-config` and edit the resulting
configuration file to indicate where we should look for
language grammars.

Related: ast-grep/ast-grep#1436

Summary by CodeRabbit

  • New Features

    • Introduced the @ast-grep/lang-yaml package, providing YAML language support for AST-based code analysis tools.
    • Added configuration for YAML file handling, including supported extensions and integration with native parsing.
    • Included a post-installation script to streamline setup.
    • Implemented comprehensive tests validating YAML parsing and pattern matching.
  • Documentation

    • Added a README with installation and usage instructions for YAML language integration.
  • Chores

    • Added package metadata, build scripts, and dependency management for the new YAML language package.

Copy link

coderabbitai bot commented Apr 22, 2025

Warning

Rate limit exceeded

@anoblet has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 18 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between b39bcb1 and 43ab206.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • packages/yaml/README.md (1 hunks)
  • packages/yaml/index.d.ts (1 hunks)
  • packages/yaml/index.js (1 hunks)
  • packages/yaml/nursery.js (1 hunks)
  • packages/yaml/package.json (1 hunks)
  • packages/yaml/postinstall.js (1 hunks)

Walkthrough

This change introduces a new language integration package, @ast-grep/lang-yaml, for YAML support within the ast-grep ecosystem. It adds all necessary scaffolding, including a configuration module, TypeScript declarations, a nursery setup file, a postinstall script, a README with usage instructions, and a package.json specifying scripts, dependencies, and publishing information. The new package provides dynamic registration and parsing capabilities for YAML files, leveraging Tree-sitter grammars and ast-grep's N-API interface.

Changes

File(s) Change Summary
packages/yaml/README.md Added documentation with installation and usage instructions for the YAML language package.
packages/yaml/index.d.ts Introduced TypeScript declarations for language registration, exporting a LanguageRegistration type and object.
packages/yaml/index.js Added a module exporting YAML parser configuration (library path, extensions, language symbol, expando char).
packages/yaml/nursery.js Added a setup file for nursery integration, configuring YAML language and providing a test runner validating parsing and pattern matching.
packages/yaml/package.json Introduced package metadata, scripts, dependencies, and publishing configuration for @ast-grep/lang-yaml.
packages/yaml/postinstall.js Added a postinstall script invoking setup logic from @ast-grep/setup-lang.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LangYaml as @ast-grep/lang-yaml
    participant SetupLang as @ast-grep/setup-lang
    participant AstGrepNAPI as ast-grep N-API

    User->>LangYaml: Install package
    LangYaml->>SetupLang: Run postinstall script
    SetupLang-->>LangYaml: Setup language integration

    User->>LangYaml: Import registration config
    User->>AstGrepNAPI: Register YAML language dynamically
    AstGrepNAPI-->>User: Language registered

    User->>AstGrepNAPI: Parse YAML code
    AstGrepNAPI-->>User: Return syntax tree
Loading

Possibly related PRs

  • ✨ JavaScript #53: Adds JavaScript language support following the same integration pattern.
  • ✨ Lua #56: Adds Lua language support with similar structure and files.
  • ✨ HTML #51: Adds HTML language support with analogous language registration and nursery setup.

Suggested reviewers

  • HerringtonDarkholme

Poem

In the warren, YAML hops in with glee,
New syntax to parse, as easy as can be!
With scripts and configs, it’s ready to go,
Tree-sitter magic helps structure to show.
Now grep your ASTs, let YAML unfold—
A bunny’s delight in the code world untold! 🐇✨


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (9)
packages/yaml/.gitignore (1)

27-28: Extend ignore patterns for parser binaries.
Consider ignoring platform-specific parser binaries beyond parser.so, such as .dylib, .dll, or .node files, to prevent accidentally checking them into Git. For example:

 parser.so
+parser.dylib
+parser.dll
+parser.node
 type.d.ts
packages/yaml/README.md (1)

1-2: Capitalize the title consistently.
Consider updating the header to something like # AST‑Grep N‑API Language for YAML to follow standard capitalization and branding.

packages/yaml/index.js (2)

1-3: Consider using require('path') for broader compatibility.
Using require('node:path') works in modern Node.js, but require('path') is more universally supported across older Node.js versions:

-const path = require('node:path')
+const path = require('path')

6-6: Add spacing in the extensions array.
For readability, include a space after the comma:

-  extensions: ["yaml","yml"],
+  extensions: ["yaml", "yml"],
packages/yaml/index.d.ts (1)

1-7: Add JSDoc for clarity and maintainability.

Consider documenting each property in the LanguageRegistration type with JSDoc comments to make its purpose explicit for consumers of the typings.

packages/yaml/.github/workflows/release.yml (1)

6-13: Consider providing a descriptive default for dry-run.

Currently dry-run defaults to true, which is safe—but you may want to document in the README how to override it for real publishes.

packages/yaml/package.json (3)

2-4: Populate description and repository fields.

An empty description and missing repository entry reduce discoverability and make automated tooling less informative.


6-12: Expand scripts to include linting or validation.

Adding a lint or validate script (e.g., npm run lint or npm run test:ci) can catch syntax and style issues before publish.


25-32: Broaden peerDependency version range.

Pinning tree-sitter-cli to exactly 0.24.6 may prevent compatibility with patch releases. Consider using ^0.24.6 instead.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 27550fe and 4492a70.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • packages/yaml/.github/workflows/release.yml (1 hunks)
  • packages/yaml/.gitignore (1 hunks)
  • packages/yaml/README.md (1 hunks)
  • packages/yaml/index.d.ts (1 hunks)
  • packages/yaml/index.js (1 hunks)
  • packages/yaml/nursery.js (1 hunks)
  • packages/yaml/package.json (1 hunks)
  • packages/yaml/postinstall.js (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/yaml/nursery.js (2)
packages/yaml/postinstall.js (1)
  • require (1-1)
scripts/nursery/index.ts (1)
  • setup (38-46)
🔇 Additional comments (12)
packages/yaml/.gitignore (1)

29-30: Verify exclusion of the src directory.
Ignoring src may inadvertently hide source files if a src folder is part of your package. Ensure that any grammar or code generated into src is intentionally untracked, or adjust this rule if you need to version-control source code in src.

packages/yaml/postinstall.js (1)

1-4: Postinstall script setup is correct.
The postinstall import and invocation with dirname: __dirname correctly hooks into the package lifecycle to bootstrap the parser.

packages/yaml/nursery.js (2)

1-2: Import the nursery setup API.
Destructuring setup from @ast-grep/nursery and importing the local registration are correct and follow the established pattern.


4-8: Validate nursery configuration.
The configuration properties (dirname, name, treeSitterPackage, and languageRegistration) align with other language packages. Ensure that 'yaml' matches the expected language identifier throughout the ecosystem.

packages/yaml/README.md (2)

5-12: Installation instructions are clear.
The PNPM commands cover all dependencies, including the optional Tree‑sitter CLI.


16-24: Usage example is accurate.
Importing, registering the language, and parsing a YAML string is demonstrated clearly.

packages/yaml/index.js (1)

4-9: Exported language registration object is well-structured.
The libraryPath, extensions, languageSymbol, and expandoChar properties align with other ast-grep language packages and will integrate seamlessly.

packages/yaml/index.d.ts (1)

9-10: Verify the runtime shape matches the declaration.

Ensure that the default export in index.js conforms exactly to this interface (has all required fields and optional fields are handled).

packages/yaml/.github/workflows/release.yml (2)

1-5: Approve CI trigger configuration.

The manual workflow_dispatch is correctly set up for per‐package publishing.


16-22: Ensure the composite workflow reference is up to date.

Verify that ast-grep/langs/.github/workflows/release.yml@main reflects the latest release steps and that the repo’s main branch is stable for reuse in dependent workflows.

packages/yaml/package.json (2)

27-29: Lock down critical dependencies.

Verify that @ast-grep/[email protected] has no known vulnerabilities and that this exact version is intended.


43-52: Validate pnpm-onlyBuiltDependencies scope.

Confirm that restricting built dependencies to this package and tree-sitter-cli aligns with your monorepo’s install strategy and doesn’t inadvertently exclude needed packages.

@anoblet anoblet force-pushed the yaml branch 2 times, most recently from a17904f to 1a04f81 Compare April 22, 2025 17:46
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

♻️ Duplicate comments (1)
packages/yaml/nursery.js (1)

10-50: 🛠️ Refactor suggestion

Test coverage should be expanded to include more YAML features.

The current test suite provides basic verification of YAML parsing and pattern matching, which is a good start. However, to ensure robust YAML support, consider adding tests for more YAML features:

  1. Multi-document YAML (separated by ---)
  2. Anchors and aliases (&anchor, *alias)
  3. Quoted strings and multi-line strings
  4. Flow-style collections ([inline, arrays], {object: notation})
  5. Comments and how they're handled in the AST
  6. Error handling for malformed YAML

This aligns with the previous review request to add tests referencing the Rust implementation at crates/language/src/yaml.rs.

Here's a sample extension for testing flow-style collections:

// Add after line 49
    // Test flow-style collections
    const flowStyle = `
flows:
  array: [1, 2, 3]
  object: {key1: value1, key2: value2}
`
    const sg5 = parse(flowStyle)
    const root5 = sg5.root()
    const arrayNode = root5.find('array: $ARRAY')
    assert.equal(arrayNode.kind(), 'block_mapping_pair')
    assert.equal(arrayNode.find('$ARRAY').kind(), 'flow_sequence')
    
    const objectNode = root5.find('object: $OBJECT')
    assert.equal(objectNode.kind(), 'block_mapping_pair')
    assert.equal(objectNode.find('$OBJECT').kind(), 'flow_mapping')
🧹 Nitpick comments (2)
packages/yaml/nursery.js (2)

28-37: Nested structure test looks good but could be more thorough.

The test verifies that nested YAML structures can be matched using the $$$ multi-metavariable. Consider extending this test to also verify:

  1. The contents of the nested sequence
  2. Matching specific items within the sequence
  3. Multiple levels of nesting
// Add after line 36
    const sequenceNode = node4.find('$SEQ')
    assert.equal(sequenceNode.kind(), 'block_sequence')
    
    // Verify matching a specific item in the sequence
    const itemNode = root3.find('- item1')
    assert.equal(itemNode.kind(), 'block_sequence_item')
    assert.equal(itemNode.text().trim(), '- item1')

38-49: Replacement functionality test is implemented correctly.

The test verifies that node replacement works properly by checking if the replacement string includes the expected transformed content. Consider strengthening this assertion to check the exact replaced text rather than just using includes().

-    assert.equal(replaced.includes('value: key'), true)
+    // More precise assertion of the replaced content
+    const expectedReplacement = source.replace('key: value', 'value: key')
+    assert.equal(replaced, expectedReplacement)
🛑 Comments failed to post (1)
packages/yaml/nursery.js (1)

1-51: 🛠️ Refactor suggestion

Add error handling tests for malformed YAML.

To ensure the parser handles invalid inputs gracefully, consider adding tests for malformed YAML. This would verify that the error handling in the parser works as expected.

// Add before the closing brace on line 50
    // Test error handling for malformed YAML
    try {
      const malformedYaml = `
key: - not valid
  indentation: wrong
`
      parse(malformedYaml)
      assert.fail('Should throw an error for malformed YAML')
    } catch (error) {
      // Just verify that an error was thrown
      assert.ok(error)
    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const { setup } = require('@ast-grep/nursery')
const languageRegistration = require('./index')
const assert = require('node:assert')

setup({
  dirname: __dirname,
  name: 'yaml',
  treeSitterPackage: '@tree-sitter-grammars/tree-sitter-yaml',
  languageRegistration,
  testRunner: (parse) => {
    // Test simple value matching
    const sg1 = parse('123')
    const root1 = sg1.root()
    const node1 = root1.find('123')
    assert.equal(node1.kind(), 'integer_scalar')
    
    // Test pattern matching with key-value pairs
    const sg2 = parse('foo: 123')
    const root2 = sg2.root()
    const node2 = root2.find('foo: $BAR')
    assert.equal(node2.kind(), 'block_mapping_pair')
    assert.equal(node2.find('$BAR').text(), '123')
    
    // Test non-matching pattern
    const node3 = root2.find('bar: $BAR')
    assert.equal(node3, null)
    
    // Test nested structures
    const sg3 = parse(`
foo:
  - item1
  - item2
`)
    const root3 = sg3.root()
    const node4 = root3.find('foo: $$$')
    assert.equal(node4.kind(), 'block_mapping_pair')
    
    // Test replacement functionality
    const source = `
key: value
list:
  - item1
  - item2
`
    const sg4 = parse(source)
    const root4 = sg4.root()
    const node5 = root4.find('$KEY: value')
    const replaced = node5.replace('value: $KEY')
    assert.equal(replaced.includes('value: key'), true)

    // Test error handling for malformed YAML
    try {
      const malformedYaml = `
key: - not valid
  indentation: wrong
`
      parse(malformedYaml)
      assert.fail('Should throw an error for malformed YAML')
    } catch (error) {
      // Just verify that an error was thrown
      assert.ok(error)
    }
  }
})

@anoblet
Copy link
Contributor Author

anoblet commented Apr 22, 2025

I cleaned it up, and took a shot at writing tests.

@anoblet anoblet changed the title add yaml lang add yaml language support Apr 22, 2025
@HerringtonDarkholme
Copy link
Member

Thanks for the contribution! The YAML test failed would you like to fix that? Otherwise the PR looks neat.

@anoblet
Copy link
Contributor Author

anoblet commented Apr 22, 2025

Everything should be fixed!

@HerringtonDarkholme
Copy link
Member

Thanks!

@HerringtonDarkholme HerringtonDarkholme merged commit fea52a8 into ast-grep:main Apr 22, 2025
3 checks passed
@HerringtonDarkholme
Copy link
Member

package released

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants