Skip to content
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

Add reference tracking and circular reference detection #8

Merged
merged 2 commits into from
Jan 17, 2025

Conversation

hackerwins
Copy link
Member

@hackerwins hackerwins commented Jan 17, 2025

What this PR does / why we need it:

Add reference tracking and circular reference detection

Which issue(s) this PR fixes:

Addresses yorkie-team/yorkie#971

Summary by CodeRabbit

  • New Features

    • Enhanced type validation with more detailed symbol and reference tracking.
    • Improved semantic validation for type definitions.
  • Tests

    • Activated tests for unused type definitions and circular references.
    • Improved test coverage for schema validation.
  • Bug Fixes

    • Added more robust checks for undefined types and circular references.

Copy link

coderabbitai bot commented Jan 17, 2025

Walkthrough

The changes focus on enhancing the type validation mechanism in the Yorkie schema validation system. The src/validator.ts file has been refactored to use more detailed data structures for tracking symbols and type references. The symbolTable is now a Map that stores additional metadata like line and column information. A new TypeReference type has been introduced to capture more context about type references. The validation logic has been updated to work with these new data structures, improving the semantic validation process.

Changes

File Change Summary
src/validator.ts - Added TypeSymbol and TypeReference types
- Converted symbolTable from Set to Map
- Replaced typeReferences with referenceMap
- Updated enterTypeAliasDeclaration and enterTypeReference methods
- Modified validation logic in validate function
test/schema.test.ts - Activated previously skipped test cases
- Updated test descriptions for unused type definitions and circular references

Sequence Diagram

sequenceDiagram
    participant Validator
    participant TypeCollectorListener
    participant SymbolTable
    participant ReferenceMap

    Validator->>TypeCollectorListener: Parse Schema
    TypeCollectorListener->>SymbolTable: Store Symbol Metadata
    TypeCollectorListener->>ReferenceMap: Track Type References
    TypeCollectorListener->>Validator: Validate Schema
    Validator->>ReferenceMap: Check Type Definitions
    Validator->>SymbolTable: Verify Symbol Integrity
Loading

Assessment against linked issues

Objective Addressed Explanation
Schema Validation Device (A) [#971]
Validate Document Changes [#971]
Semantic Analysis of Schemas [#971]

Poem

🐰 In the realm of types and lines so neat,
Symbols dance with references sweet.
Validation's magic, now precise and clear,
No circular paths shall bring us fear.
Schema's guardian, with wisdom bright! 🔍

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5627a9f and 6a2922d.

📒 Files selected for processing (2)
  • src/validator.ts (3 hunks)
  • test/schema.test.ts (2 hunks)
🔇 Additional comments (3)
src/validator.ts (1)

158-175: ⚠️ Potential issue

Potential infinite loop in circular reference detection

The while loop for detecting circular references could lead to an infinite loop if current is never updated to undefined or 'Document'. Ensure that all possible paths eventually break the loop.

Verify that all type references will eventually reach a base case. Consider adding a maximum iteration limit or additional checks if necessary.

To confirm that the loop terminates correctly, you can add logging or use debugging tools during development.

test/schema.test.ts (2)

Line range hint 248-256: Updated test to check for circular references

The test previously named 'should detect type cycle' has been updated to 'should detect circular references'. This improves clarity. Verify that the test accurately detects circular references using the new validation logic.

Run the test to ensure it passes:

✅ Verification successful

Test properly validates circular type references

The test case correctly creates a circular reference scenario (Hello ↔ World) that matches the validation logic's cycle detection algorithm. The rename from 'type cycle' to 'circular references' improves clarity and aligns with the error messages produced by the validator.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

# Run the specific test case
npm test -- -t 'should detect circular references'

Length of output: 152


Script:

#!/bin/bash
# Find the complete test implementation
ast-grep --pattern 'it($_, () => {
  const schema = `
    type Hello = {
      field1: string;
      field2: World;
    };
    
    type World = {
      field1: string;$$$
  });'

# Search for validation logic related to circular references
rg -l "circular.*reference" --type ts

Length of output: 257


Script:

#!/bin/bash
# Get the complete test case with context
rg -B 2 -A 10 "should detect circular references" test/schema.test.ts

# Check the validation logic
rg -B 2 -A 10 "circular.*reference" src/validator.ts

Length of output: 779


Line range hint 239-246: Activated test for unused type definitions

The test 'should restrict unused type definition' is now active. Ensure that the validation logic correctly identifies and reports unused type definitions.

Run the test to confirm it behaves as expected:

✅ Verification successful

Validation for unused type definitions is properly implemented

The test case correctly verifies that the schema validator detects and reports unused type definitions. The validator implementation confirms this by checking if all defined types are reachable from the root 'Document' type.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

# Run the specific test case
npm test -- -t 'should restrict unused type definition'

Length of output: 162


Script:

#!/bin/bash
# Find validate function implementation
ast-grep --pattern 'function validate($_) {
  $$$
}'

# Find validate related files
rg -l "validate.*schema" --type ts

# Look for similar test patterns in the test file
cat test/schema.test.ts

Length of output: 6431


Script:

#!/bin/bash
# Find validator implementation
cat src/validator.ts

# Search for unused type validation logic
rg -A 5 "unused.*type" --type ts

Length of output: 5792

src/validator.ts Show resolved Hide resolved
src/validator.ts Outdated Show resolved Hide resolved
src/validator.ts Outdated Show resolved Hide resolved
src/validator.ts Outdated Show resolved Hide resolved
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

♻️ Duplicate comments (1)
src/validator.ts (1)

36-37: ⚠️ Potential issue

Add null check for parent property

The nullable parent property could lead to runtime errors when accessed with non-null assertion in enterTypeReference.

Consider one of these solutions:

  1. Initialize parent appropriately
  2. Add null check before usage
  3. Implement exitTypeAliasDeclaration to reset parent
🧹 Nitpick comments (4)
src/validator.ts (4)

41-47: Consider adding validation for duplicate type declarations

The symbolTable.set() call will silently overwrite any existing type declaration with the same name.

Add duplicate type declaration check:

 enterTypeAliasDeclaration(ctx: TypeAliasDeclarationContext) {
   const typeName = ctx.Identifier().text;
   const { line, charPositionInLine } = ctx.Identifier().symbol;
+  if (this.symbolTable.has(typeName)) {
+    this.errors.push({
+      message: `Duplicate type declaration '${typeName}'`,
+      line,
+      column: charPositionInLine,
+    });
+  }
   this.symbolTable.set(typeName, {
     name: typeName,
     line: line,
     column: charPositionInLine,
   });
   this.parent = typeName;
 }

145-145: Address TODO comment about performance optimization

The current implementation has O(V + E) complexity where V is the number of types and E is the number of references.

Consider these optimizations:

  1. Cache the results of cycle detection
  2. Use topological sorting for a single-pass solution
  3. Implement parallel validation for independent type hierarchies

Would you like me to provide a detailed implementation for any of these approaches?


156-175: Enhance circular reference error message with cycle path

The current error message only shows the start and end of the cycle. Including the complete path would make debugging easier.

 if (visited.has(current)) {
+  const cycle = Array.from(visited).join(' -> ');
   listener.errors.push({
-    message: `Circular reference detected: ${current} -> ${symbol.name}`,
+    message: `Circular reference detected: ${cycle} -> ${current}`,
     line: symbol.line,
     column: symbol.column,
   });
   break;
 }

177-184: Improve error message for types not in document

The error message could be more specific about the requirement for types to extend from 'Document'.

 if (!current || current !== 'Document') {
   listener.errors.push({
-    message: `Type '${symbol.name}' is not in the document.`,
+    message: `Type '${symbol.name}' must extend from 'Document' either directly or through inheritance.`,
     line: symbol.line,
     column: symbol.column,
   });
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6a2922d and d7c3f1d.

📒 Files selected for processing (1)
  • src/validator.ts (3 hunks)
🔇 Additional comments (2)
src/validator.ts (2)

19-23: Rename TypeSymbol to avoid conflict with built-in Symbol type

The custom TypeSymbol type might cause confusion with JavaScript's built-in Symbol type.

Apply this diff:

-type TypeSymbol = {
+type SchemaTypeSymbol = {
   name: string;
   line: number;
   column: number;
 };

108-111: LGTM! Improved error range calculation

The changes correctly calculate the error range for multi-character tokens, improving error reporting accuracy.

@hackerwins hackerwins merged commit 0a9905d into main Jan 17, 2025
2 checks passed
@hackerwins hackerwins deleted the circular-reference branch January 17, 2025 04:46
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