Skip to content

preview/ast-grep #65

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

preview/ast-grep #65

wants to merge 1 commit into from

Conversation

alexcoderabbitai
Copy link

@alexcoderabbitai alexcoderabbitai commented Jul 16, 2025

image

Summary by CodeRabbit

  • New Features

    • Introduced greeting utilities, including functions for personalized messages and a React component for displaying greetings.
    • Added string search utilities with both synchronous and asynchronous options.
    • Added a function demonstrating asynchronous state handling in a React context.
  • Chores

    • Added configuration files for code review and linting, including rules enforcing console usage restrictions, naming conventions for constants, and simplification of type definitions in React state hooks.

Copy link

coderabbitai bot commented Jul 16, 2025

Walkthrough

This update introduces new configuration and linting rules for JavaScript and TypeScript codebases, focusing on variable naming and console usage. It also adds new utility functions, a React component, and a TypeScript async function for demonstration. The configuration enables early access features and integrates custom AST-grep rules and packages.

Changes

File(s) Summary
.coderabbit.yaml Added configuration for schema validation, review instructions, AST-grep tool integration, and custom package inclusion.
greet.js Introduced greeting functions, a React component (HelloWorld), and multiple string search utilities (sync & async).
jsx_ast_grep_failure.ts Added an async function demonstrating use of React's useState and concurrent promise handling with console logging.
rules/no-console-except-error.yml Added lint rule disallowing console.log, console.debug, console.warn everywhere; allows console.error only in catch blocks.
rules/replace-unnecessary-type-definition-use-state.yml Added lint rule to remove unnecessary <string> type argument from useState calls in TypeScript.
rules/ts-const.yaml Added lint rule enforcing uppercase naming for top-level const variables in TypeScript.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant greet.js
  participant Console
  participant HelloWorld (React)
  
  User->>greet.js: call greet(name, surname)
  greet.js->>Console: print greeting message

  User->>greet.js: call welcome(name, surname)
  greet.js->>Console: print welcome message

  User->>HelloWorld (React): render <HelloWorld greeting, greeted, ...>
  HelloWorld (React)->>Console: (optional) print based on props
Loading
sequenceDiagram
  participant Developer
  participant AST-grep Linter
  participant Source Files

  Developer->>AST-grep Linter: run lint rules
  AST-grep Linter->>Source Files: scan for console usage and const naming
  AST-grep Linter-->>Developer: report violations or suggest fixes
Loading

Poem

🐇
A hop, a skip, some rules anew,
No sneaky logs will now get through!
Consts in uppercase, shining bright—
Linting keeps our code just right.
With greetings, welcomes, and React in tow,
This rabbit cheers: let good code grow!

Impact Analysis

New greeting utilities and HelloWorld React component

ℹ️ Low 🔗 Impacts API 🔄 Impacts behavior

Adds a new module exporting console-based greeting functions (greet, welcome), a HelloWorld React component with customizable props and visitor count, and three string search utilities (findInString, findInStringAsync, findInStringTreated). All additions are non-breaking and purely additive.

Review prop defaults, styling, and event handling in the HelloWorld component; evaluate use of randomness for visitor numbers and consider deterministic alternative. Verify logging approaches and error handling in the string search functions.

Test console output of greet and welcome; render HelloWorld with various prop combinations including silent mode and onMouseOver handler; validate substring detection and exception logging in all findInString* functions.

🔍 Related Files
  • greet.js

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 YAMLlint (1.37.1)
.coderabbit.yaml

[Errno 2] No such file or directory: '.coderabbit.yaml'

rules/no-console-except-error.yml

[Errno 2] No such file or directory: 'rules/no-console-except-error.yml'

rules/replace-unnecessary-type-definition-use-state.yml

[Errno 2] No such file or directory: 'rules/replace-unnecessary-type-definition-use-state.yml'

  • 1 others
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch preview/ast-grep

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests 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.

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: 9

🔭 Outside diff range comments (1)
.coderabbit.yaml (1)

1-14: Missing ast-grep rule directories in configuration

The directories referenced under ast-grep.rule_dirs do not exist in the repo, so your custom rules won’t be loaded:

  • “rules/”
  • “test-missing-dir/”

Also ensure your custom package is installed or reachable:

  • test-peter-rabbit/test-ast-grep-custom-package

Please update your .coderabbit.yaml or repo structure accordingly:

• Create the missing directories and add your AST-Grep rules there
• Or remove/adjust the paths in ast-grep.rule_dirs
• Confirm that the package test-peter-rabbit/test-ast-grep-custom-package is available (e.g., installed or in your project’s path)

[coderabbit.yaml lines 7–11]

🧹 Nitpick comments (1)
rules/replace-unnecessary-type-definition-use-state.yml (1)

1-8: Effective rule for removing unnecessary TypeScript type annotations.

The rule correctly identifies and fixes unnecessary explicit <string> type parameters in useState calls, allowing TypeScript to infer the type from the initial value.

Consider extending this rule to handle other common unnecessary type annotations:

 rule:
   any:
     - pattern: useState<string>($A)
+    - pattern: useState<number>($A)
+    - pattern: useState<boolean>($A)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ef04b8d and 30b478f.

📒 Files selected for processing (6)
  • .coderabbit.yaml (1 hunks)
  • greet.js (1 hunks)
  • jsx_ast_grep_failure.ts (1 hunks)
  • rules/no-console-except-error.yml (1 hunks)
  • rules/replace-unnecessary-type-definition-use-state.yml (1 hunks)
  • rules/ts-const.yaml (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,ts}

Instructions used from:

Sources:
⚙️ CodeRabbit Configuration File

🪛 ast-grep (0.38.6)
jsx_ast_grep_failure.ts

[hint] 11-11:
Context: await (new Promise(() => {console.log("logging this long task")}))
Suggested replacement: (new Promise(() => {console.log("logging this long task")}))

(no-await-in-promise-all-custom)

🪛 Biome (1.9.4)
greet.js

[error] 75-75: Illegal return statement outside of a function

(parse)


[error] 75-76: Expected a statement but instead found '}'.

Expected a statement here.

(parse)

🔇 Additional comments (5)
rules/no-console-except-error.yml (1)

1-14: Well-structured ast-grep rule for console usage restrictions.

The rule correctly implements the intended behavior:

  • Restricts console.log, console.debug, and console.warn everywhere
  • Allows console.error only inside catch clauses
  • Uses appropriate pattern matching with constraints and negation logic

The implementation follows ast-grep best practices with clear pattern definitions and proper constraint usage.

rules/ts-const.yaml (1)

3-16: Well-designed rule for enforcing uppercase constants.

The rule correctly:

  • Matches both typed and untyped const declarations
  • Uses regex to identify non-uppercase variable names
  • Restricts checking to top-level program scope
  • Provides clear warning messages

The regex pattern .*[^A-Z_].* effectively catches any name containing non-uppercase characters or characters other than underscores.

greet.js (3)

58-63: PropTypes definition looks good.

The PropTypes are properly defined and cover all the props used in the component.


98-104: Correct console usage in catch block.

The function correctly uses console.error in the catch block, which is allowed by the AST-grep linting rules.


6-8: Console.log usage violates linting rules.

The console.log statement violates the AST-grep linting rule that disallows console.log, console.debug, and console.warn except for console.error inside catch clauses.

Consider replacing with console.error if this is for error logging, or remove the console statement if it's for debugging purposes:

-	console.log(`Hello, ${name} ${surname}!`)
+	console.error(`Hello, ${name} ${surname}!`)

Likely an incorrect or invalid review comment.

@@ -0,0 +1,15 @@
id: ts-const
language: Typescript
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix language specification capitalization.

The language should be lowercase "typescript" to match ast-grep's language specifications.

-language: Typescript
+language: typescript
📝 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.

Suggested change
language: Typescript
language: typescript
🤖 Prompt for AI Agents
In rules/ts-const.yaml at line 2, change the language specification from
"Typescript" to lowercase "typescript" to comply with ast-grep's expected
language format.

@@ -0,0 +1,22 @@
import { useState } from 'react'

const greeting: string = "Hello, world!";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Constant variable name violates coding guidelines.

According to the coding guidelines, all constant variables in JS/TS files must be defined using UPPER CASE letters.

-const greeting: string = "Hello, world!";
+const GREETING: string = "Hello, world!";
📝 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.

Suggested change
const greeting: string = "Hello, world!";
const GREETING: string = "Hello, world!";
🤖 Prompt for AI Agents
In jsx_ast_grep_failure.ts at line 3, the constant variable name 'greeting'
violates the coding guideline requiring constant variables to be in UPPER CASE.
Rename the variable to 'GREETING' to comply with the naming convention.

Comment on lines +7 to +9
const [state, setState] = useState<string>("test string")

const [state2, setState2] = useState<string>("test string")
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unnecessary TypeScript type annotations.

The explicit <string> type parameters are unnecessary since TypeScript can infer the type from the initial value. This violates the replace-unnecessary-type-definition-use-state rule.

-    const [state, setState] = useState<string>("test string")
+    const [state, setState] = useState("test string")

-    const [state2, setState2] = useState<string>("test string")
+    const [state2, setState2] = useState("test string")
📝 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.

Suggested change
const [state, setState] = useState<string>("test string")
const [state2, setState2] = useState<string>("test string")
const [state, setState] = useState("test string")
const [state2, setState2] = useState("test string")
🤖 Prompt for AI Agents
In jsx_ast_grep_failure.ts around lines 7 to 9, remove the explicit <string>
type annotations from the useState calls because TypeScript can infer the type
from the initial string value. Simply call useState with the initial string
without specifying the generic type parameter to comply with the
replace-unnecessary-type-definition-use-state rule.

Comment on lines +11 to +14
const [first, second] = await Promise.all([
await (new Promise(() => {console.log("logging this long task")})),
new Promise(() => {console.log("logging another long task")}),
])
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix Promise.all usage and console.log violations.

Multiple issues with this code:

  1. console.log usage violates the no-console-except-error rule
  2. Double await on the first promise is incorrect
  3. Promises don't resolve/reject, causing them to hang indefinitely
-    const [first, second] = await Promise.all([
-        await (new Promise(() => {console.log("logging this long task")})),
-        new Promise(() => {console.log("logging another long task")}),
-    ])
+    const [first, second] = await Promise.all([
+        new Promise((resolve) => {
+            // Removed console.log to comply with no-console-except-error rule
+            resolve("first task completed");
+        }),
+        new Promise((resolve) => {
+            // Removed console.log to comply with no-console-except-error rule
+            resolve("second task completed");
+        }),
+    ])
📝 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.

Suggested change
const [first, second] = await Promise.all([
await (new Promise(() => {console.log("logging this long task")})),
new Promise(() => {console.log("logging another long task")}),
])
const [first, second] = await Promise.all([
new Promise((resolve) => {
// Removed console.log to comply with no-console-except-error rule
resolve("first task completed");
}),
new Promise((resolve) => {
// Removed console.log to comply with no-console-except-error rule
resolve("second task completed");
}),
])
🧰 Tools
🪛 ast-grep (0.38.6)

[hint] 11-11:
Context: await (new Promise(() => {console.log("logging this long task")}))
Suggested replacement: (new Promise(() => {console.log("logging this long task")}))

(no-await-in-promise-all-custom)

🤖 Prompt for AI Agents
In jsx_ast_grep_failure.ts around lines 11 to 14, fix the Promise.all usage by
removing the redundant double await on the first promise and ensure both
promises properly resolve or reject to avoid hanging. Replace console.log calls
with an allowed logging method or remove them to comply with the
no-console-except-error rule.

Comment on lines +71 to +76
export function findInString(text, string, logFn = console.error) {
logFn("text", text)
return text.includes(string)
}
return text.includes(string)
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix duplicate code causing parse errors.

There are duplicate lines 75-76 that repeat the return statement and closing brace, causing parse errors as flagged by static analysis.

Remove the duplicate lines:

 export function findInString(text, string, logFn = console.error) {
 	logFn("text", text)
 	return text.includes(string)
 }
-	return text.includes(string)
-}
📝 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.

Suggested change
export function findInString(text, string, logFn = console.error) {
logFn("text", text)
return text.includes(string)
}
return text.includes(string)
}
export function findInString(text, string, logFn = console.error) {
logFn("text", text)
return text.includes(string)
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 75-75: Illegal return statement outside of a function

(parse)


[error] 75-76: Expected a statement but instead found '}'.

Expected a statement here.

(parse)

🤖 Prompt for AI Agents
In greet.js around lines 71 to 76, there is a duplicate return statement and
closing brace causing parse errors. Remove the repeated lines at 75 and 76 so
that the function has only one return statement and one closing brace to fix the
syntax error.

Comment on lines +15 to +17
export function welcome(name, surname) {
console.log(`Welcome, ${name} ${surname}!`)
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Console.log usage violates linting rules.

The console.log statement violates the AST-grep linting rule that disallows console.log, console.debug, and console.warn except for console.error inside catch clauses.

Consider replacing with console.error if this is for error logging, or remove the console statement if it's for debugging purposes:

-	console.log(`Welcome, ${name} ${surname}!`)
+	console.error(`Welcome, ${name} ${surname}!`)
📝 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.

Suggested change
export function welcome(name, surname) {
console.log(`Welcome, ${name} ${surname}!`)
}
export function welcome(name, surname) {
console.error(`Welcome, ${name} ${surname}!`)
}
🤖 Prompt for AI Agents
In greet.js around lines 15 to 17, the use of console.log violates linting rules
that disallow console.log outside of catch clauses. To fix this, either remove
the console.log statement if it is for debugging or replace it with
console.error only if it is intended for error logging inside a catch block.
Adjust the code accordingly to comply with the linting restrictions.

Comment on lines +28 to +31
if (!greeting) {
console.log("No greeting")
return null
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Console.log usage violates linting rules.

The console.log statement violates the AST-grep linting rule that disallows console.log, console.debug, and console.warn except for console.error inside catch clauses.

Consider replacing with console.error:

-		console.log("No greeting")
+		console.error("No greeting")
📝 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.

Suggested change
if (!greeting) {
console.log("No greeting")
return null
}
if (!greeting) {
- console.log("No greeting")
+ console.error("No greeting")
return null
}
🤖 Prompt for AI Agents
In greet.js around lines 28 to 31, the use of console.log violates linting rules
that only allow console.error inside catch clauses. Replace the console.log("No
greeting") statement with console.error("No greeting") to comply with the
linting rules.

Comment on lines +84 to +90
export async function findInStringAsync(text, string) {
try {
return text.includes(string)
} catch (error) {
console.log("error", error)
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Console.log in catch block violates linting rules.

The console.log statement in the catch block violates the AST-grep linting rule. Only console.error is allowed in catch blocks.

Replace with console.error:

 	} catch (error) {
-		console.log("error", error)
+		console.error("error", 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.

Suggested change
export async function findInStringAsync(text, string) {
try {
return text.includes(string)
} catch (error) {
console.log("error", error)
}
}
export async function findInStringAsync(text, string) {
try {
return text.includes(string)
} catch (error) {
console.error("error", error)
}
}
🤖 Prompt for AI Agents
In greet.js around lines 84 to 90, replace the console.log statement in the
catch block with console.error to comply with linting rules that only allow
console.error in catch blocks. This means changing console.log("error", error)
to console.error("error", error).

Comment on lines +33 to +36
// TODO: Don't use random in render
const num = Math.floor(Math.random() * 1e7)
.toString()
.replace(/.d+/gi, "")
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix regex pattern and address TODO comment.

Two issues need attention:

  1. The regex pattern /.d+/gi is incorrect - it should be /\d+/gi to match digits
  2. The TODO comment highlights a valid concern about using Math.random() in render, which can cause unnecessary re-renders

Apply this diff to fix the regex:

-		.replace(/.d+/gi, "")
+		.replace(/\d+/gi, "")

Would you like me to suggest an alternative approach to generate the visitor number that doesn't use random in render?

📝 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.

Suggested change
// TODO: Don't use random in render
const num = Math.floor(Math.random() * 1e7)
.toString()
.replace(/.d+/gi, "")
// TODO: Don't use random in render
const num = Math.floor(Math.random() * 1e7)
.toString()
.replace(/\d+/gi, "")
🤖 Prompt for AI Agents
In greet.js around lines 33 to 36, fix the regex pattern by replacing `/.d+/gi`
with `/\d+/gi` to correctly match digits. Additionally, address the TODO by
removing the use of Math.random() inside the render function to prevent
unnecessary re-renders; instead, generate the visitor number outside the render
or use a stable unique identifier approach.

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.

1 participant