Skip to content

✨ PHP #61

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 5 commits into from
Apr 10, 2025
Merged

✨ PHP #61

merged 5 commits into from
Apr 10, 2025

Conversation

NatoBoram
Copy link
Collaborator

@NatoBoram NatoBoram commented Apr 3, 2025

This is a weirder one.

The tree-sitter-php package has its src folder in php and php_only instead of at its root. copySrcIfNeeded, however, is hard-coded to copy tree-sitter-*/src, which doesn't exist.

function copySrcIfNeeded(config: SetupConfig) {
const { dirname, treeSitterPackage } = config
const existing = path.join(dirname, 'src')
const src = path.join(dirname, 'node_modules', treeSitterPackage, 'src')
if (fs.existsSync(existing)) {
log('src exists, skipping copy')
return
}
log('copying tree-sitter src')
fs.cpSync(src, 'src', { recursive: true })
}

This PR adds a src parameter to SetupConfig to enable the nursery to find the appropriate src folder in case it deviates from src.

https://github.com/coderabbitai/langs/blob/e8e4b4a097a1650711922e66ec60d8d84cde0b81/scripts/nursery/index.ts#L48-L60

The next issue is that the usual "build": "tree-sitter build -o parser.so" script expects the src to not reference anything outside of itself, which is an issue for scanner.c.

https://github.com/tree-sitter/tree-sitter-php/blob/576a56fa7f8b68c91524cdd211eb2ffc43e7bb11/php/src/scanner.c#L1

I changed it to tree-sitter build -o parser.so ./node_modules/tree-sitter-php/php, but then it's not using the src folder we just copied and then I have no idea why there's even a src folder in the first place if we can directly use node_modules/tree-sitter-php/php/src without issues. I notice that src is published, but beyond that, I don't know how it's actually used.

This issue affects these languages:

Since I don't know if this is a good implementation, I'll wait until this one is resolved / merged before adding support for those languages.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new PHP language support package.
    • Added detailed installation and usage instructions in the README.
    • Enhanced configuration flexibility for managing language source paths.
    • Added new type definitions and constants for language registration.
    • Exported a new object containing properties related to the PHP parser.
    • Included a post-installation setup for the PHP package.
  • Tests

    • Incorporated a basic test to validate PHP syntax parsing.

Copy link

coderabbitai bot commented Apr 3, 2025

Walkthrough

The pull request introduces a new PHP language package (@ast-grep/lang-php) with comprehensive support. It adds documentation, type definitions, parser configuration exports, and testing setups. Additionally, it includes package configuration and a post-install script to facilitate proper installation and usage. A minor update to the nursery script adds an optional source path property to improve source directory handling.

Changes

File(s) Change Summary
packages/php/README.md Added a README detailing installation commands and usage instructions for the PHP package.
packages/php/index.d.ts, packages/php/index.js Introduced the LanguageRegistration type and corresponding exports; defines parser configuration such as libraryPath, extensions, languageSymbol, etc.
packages/php/nursery.js Added a new testing setup using @ast-grep/nursery to test PHP syntax parsing with a simple test case.
packages/php/package.json Introduced package configuration, including dependencies, scripts, publish settings, and metadata for the @ast-grep/lang-php package.
packages/php/postinstall.js Added a post-install script that runs language-specific post-installation tasks via the @ast-grep/setup-lang package.
scripts/nursery/index.ts Added an optional src property to the SetupConfig interface and updated the source copy logic in copySrcIfNeeded to use this new property value.

Possibly related PRs

  • ✨ Lua #56: The changes in the main PR and the retrieved PR are related as both introduce a new LanguageRegistration type and a registration constant in their respective language support packages, specifically for PHP and Lua.
  • ✨ Haskell #50: The changes in the main PR for the PHP package and the retrieved PR for the Haskell package both introduce a new LanguageRegistration type and a registration constant, indicating a direct relationship at the code level.
  • feat: C# language #41: The changes in the main PR and the retrieved PR are related as both introduce a new LanguageRegistration type and a postinstall.js file, indicating similar structural modifications for different language packages.

Suggested reviewers

  • HerringtonDarkholme

Poem

In fields of code I happily roam,
New PHP traits now call this place home.
Syntax and structure, in a joyful parade,
Through tests and installs, my hops are well-played.
A carrot of code—bright, crisp, and neat!
Hop on, dear dev, with a rhythm so sweet! 🥕🐇


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9c914c8 and c06191e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • .changeset/wet-nights-cover.md (1 hunks)
  • packages/php/README.md (1 hunks)
  • packages/php/index.d.ts (1 hunks)
  • packages/php/index.js (1 hunks)
  • packages/php/nursery.js (1 hunks)
  • packages/php/package.json (1 hunks)
  • packages/php/postinstall.js (1 hunks)
  • scripts/nursery/index.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/php/index.d.ts
  • .changeset/wet-nights-cover.md
  • packages/php/nursery.js
  • packages/php/postinstall.js
  • scripts/nursery/index.ts
  • packages/php/package.json
  • packages/php/README.md
  • packages/php/index.js

🪧 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 plan to trigger planning for file edits and PR creation.
  • @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: 1

🧹 Nitpick comments (4)
packages/php/nursery.js (1)

12-17: Consider adding more comprehensive test cases

While the current test is functional, it's using a very simple PHP string ('123'). Consider adding more complex PHP code examples that test various language features to ensure comprehensive parser coverage.

For example:

testRunner: parse => {
-  const sg = parse('123')
-  const root = sg.root()
-  const node = root.find('123')
-  assert.equal(node.kind(), 'text')
+  // Test simple value
+  const simpleTest = parse('123')
+  const simpleNode = simpleTest.root().find('123')
+  assert.equal(simpleNode.kind(), 'text')
+  
+  // Test PHP syntax
+  const phpTest = parse('<?php $var = "test"; echo $var; ?>')
+  const phpRoot = phpTest.root()
+  assert(phpRoot.findAll('echo').length > 0, 'Should parse echo statement')
+  assert(phpRoot.findAll('variable_name').length > 0, 'Should parse variable names')
},
packages/php/README.md (1)

16-24: Enhance usage example with realistic PHP code

The usage example is clear, but could be improved by showing a more realistic PHP code snippet and demonstrating more operations on the parsed result.

Consider enhancing the example like this:

```js
import php from '@ast-grep/lang-php'
import { registerDynamicLanguage, parse } from '@ast-grep/napi'

registerDynamicLanguage({ php })

-const sg = parse('php', `your code`)
-sg.root().kind()
+const sg = parse('php', `<?php
+  $greeting = "Hello, World!";
+  echo $greeting;
+?>`)
+
+// Get the root node and its kind
+const root = sg.root();
+console.log("Root node kind:", root.kind());
+
+// Find all variable declarations
+const variables = root.findAll('variable_name');
+console.log("Found", variables.length, "variables");
+
+// Find all echo statements
+const echoStatements = root.findAll('echo');
+console.log("Found", echoStatements.length, "echo statements");
packages/php/index.js (1)

1-9: Consider adding more PHP file extensions for comprehensive coverage.

The implementation looks correct and well-structured. However, PHP also supports other file extensions like .phtml, .php4, .php5, .php7, and .phps. For more comprehensive language support, consider adding these to the extensions array.

-  extensions: ['php'],
+  extensions: ['php', 'phtml', 'php4', 'php5', 'php7', 'phps'],
scripts/nursery/index.ts (1)

51-52: Consider using nullish coalescing operator.

The implementation works correctly, but using the nullish coalescing operator (??) would be more semantically appropriate than logical OR (||) for setting default values when handling undefined/null parameters.

-  const src = config.src || 'src'
+  const src = config.src ?? 'src'
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 002639c and e8e4b4a.

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

1-4:

❓ Verification inconclusive

Consider adding the src parameter to match PR objectives

According to the PR objectives, a key change is adding a src parameter to SetupConfig to handle the non-standard location of source files in the tree-sitter-php package. However, this parameter isn't being passed to the postinstall function here.

Consider adding the src parameter to specify the correct source directory path (php/src or php_only/src).


🏁 Script executed:

#!/bin/bash
# Checking if the postinstall function from @ast-grep/setup-lang accepts a src parameter
grep -r "postinstall.*src" --include="*.js" .

Length of output: 47


Post-install configuration: Add the src parameter for tree-sitter-php

The current code in packages/php/postinstall.js only passes the dirname property to the postinstall function. Based on the PR objectives—where handling a non-standard source directory is a key objective—it appears that a src parameter should also be provided to correctly point to the location of the source files (e.g., php/src or an appropriate alternative).

  • Action Required:
    • Confirm that the postinstall function from @ast-grep/setup-lang accepts a src parameter.
    • Update the call in packages/php/postinstall.js to include the appropriate src property. For example:
      const { postinstall } = require('@ast-grep/setup-lang')
      postinstall({
        dirname: __dirname,
        src: 'php/src' // Adjust this path if the correct directory differs
      })
  • Next Steps:
    Please review the documentation or implementation of @ast-grep/setup-lang to verify that this change is necessary and adjust the source path as needed.
packages/php/index.d.ts (1)

1-10: Type definition looks good

The LanguageRegistration type is well-defined with the appropriate required and optional properties needed for language registration. The default export matches the usage pattern demonstrated in the README.

packages/php/nursery.js (1)

6-18: Implementation correctly addresses the source path issue

The src parameter is set to path.join('php', 'src'), which properly addresses the non-standard location of source files in the tree-sitter-php package as mentioned in the PR objectives.

packages/php/README.md (1)

5-12: Installation instructions are clear and complete

The installation instructions correctly specify all required dependencies and note the potential need for the tree-sitter CLI if prebuilt binaries aren't available.

scripts/nursery/index.ts (1)

25-28: Good documentation of the new parameter.

The JSDoc comments clearly explain the purpose of the new parameter and provide helpful examples of packages that might need this functionality.

packages/php/package.json (2)

7-7: Note about the build script configuration.

The build script correctly points to the PHP directory in tree-sitter-php package, addressing the main issue described in the PR objectives. This approach directly uses the source from node_modules rather than using the copied src directory, which appears to be intentional as mentioned in your PR description.


13-20: Files configuration looks complete.

The files array includes all necessary components for proper package functionality, including the main JavaScript file, type definitions, installation scripts, and prebuilds.

@NatoBoram NatoBoram force-pushed the feature/php branch 2 times, most recently from 20f96a4 to 53a9216 Compare April 4, 2025 21:41
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: 0

🧹 Nitpick comments (2)
packages/php/package.json (2)

1-5: Metadata Fields Need Completion

The basic metadata is defined correctly. However, the "description" field is currently empty and the "author" field is blank. Consider adding a brief package description and proper author information to improve discoverability and documentation on npm.


21-23: Optional: Enhance Package Description

While the "keywords" and "license" fields are provided, the lack of an "author" and a non-existent "description" may make the package less informative for users. Consider providing these details to clarify the package’s purpose and origin.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e8e4b4a and 53a9216.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • .changeset/wet-nights-cover.md (1 hunks)
  • packages/php/README.md (1 hunks)
  • packages/php/index.d.ts (1 hunks)
  • packages/php/index.js (1 hunks)
  • packages/php/nursery.js (1 hunks)
  • packages/php/package.json (1 hunks)
  • packages/php/postinstall.js (1 hunks)
  • scripts/nursery/index.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/wet-nights-cover.md
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/php/nursery.js
  • packages/php/README.md
  • packages/php/postinstall.js
  • packages/php/index.d.ts
  • scripts/nursery/index.ts
  • packages/php/index.js
🔇 Additional comments (5)
packages/php/package.json (5)

6-12: Review Build & Script Commands

The scripts section is generally well-structured. In particular, note the build command:

"build": "tree-sitter build -o parser.so ./node_modules/tree-sitter-php/php"

According to the PR objectives, there is some uncertainty about the usage of a separately copied src folder versus directly referencing the node_modules/tree-sitter-php/php directory. Please confirm that this hard-coded path is intentional. If the new src folder is meant to be used, the build command might need adjustment.


13-20: Files Array Validation and Inclusion

The "files" array includes "src" and "prebuilds", which is appropriate for packaging. Please verify that including the "src" folder is necessary and does not conflict with the build command’s reference to the PHP directory directly under node_modules.


24-34: Dependencies and Peer Dependencies

The dependency configuration appears solid. The runtime dependency on @ast-grep/setup-lang and the peer dependency on tree-sitter-cli (along with its optional metadata) follow best practices. Ensure that version "0.24.6" for tree-sitter-cli and its inclusion in both peerDependencies and devDependencies are fully verified with your build and deployment environments.


35-39: Development Dependencies Check

The devDependencies list includes @ast-grep/nursery, tree-sitter-cli, and tree-sitter-php. Make sure that the workspace:* reference for @ast-grep/nursery resolves correctly in your CI and that the pinned versions for tree-sitter-cli and tree-sitter-php are compatible with the rest of your tooling.


40-46: Publish and PNPM Configuration Validation

The "publishConfig" and "pnpm" sections are well defined. The publishConfig ensures the package is publicly accessible, and the PNPM configuration restricts published content to only the built dependencies. Just verify that these settings align with your deployment workflow.

@NatoBoram NatoBoram force-pushed the feature/php branch 4 times, most recently from 9c914c8 to 4a3ec25 Compare April 6, 2025 04:30
@HerringtonDarkholme HerringtonDarkholme merged commit 597f386 into ast-grep:main Apr 10, 2025
3 checks passed
@NatoBoram NatoBoram deleted the feature/php branch April 10, 2025 17:51
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