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

Implemented underscore syntax in numbers #29

Merged
merged 2 commits into from
Dec 24, 2024

Conversation

ascandone
Copy link
Contributor

No description provided.

Copy link

coderabbitai bot commented Dec 20, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces support for numeric literals with underscores in the Numscript language. The grammar definition in Numscript.g4 is modified to allow underscores within number tokens, and the lexer’s internal representation is updated accordingly. Additionally, the parsing mechanism is enhanced to remove underscores when converting numbers to integers. New test cases are added to verify the functionality of parsing numbers with underscores and to ensure error handling for invalid formats.

Changes

File Change Summary
Numscript.g4 Updated NUMBER token pattern to allow underscores: MINUS? [0-9]+ ('_' [0-9]+)*
internal/parser/antlr/NumscriptLexer.interp Updated internal ATN representation (value changed from 326 to 337)
internal/parser/antlr/numscript_lexer.go Modified serializedATN and lexer initialization to support new number format
internal/parser/parser.go Added logic to remove underscores when parsing number literals
internal/parser/parser_test.go Added TestNumberSyntaxUnderscore and TestForbidInvalidNumberUnderscores test cases

Sequence Diagram

sequenceDiagram
    participant Lexer
    participant Parser
    participant Test
    
    Lexer->>Parser: Tokenize number with underscores
    Parser->>Parser: Remove underscores
    Parser->>Parser: Convert to integer
    Test->>Parser: Verify parsing
Loading

Poem

🐰 Hop, hop, through numbers bright,
Underscores dancing left and right,
A thousand becomes one-thousand clear,
With syntax that brings numeric cheer!
CodeRabbit's magic makes parsing light! 🔢

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


📜 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 cefcd19 and ed73aa3.

📒 Files selected for processing (4)
  • Numscript.g4 (1 hunks)
  • internal/parser/antlr/NumscriptLexer.interp (1 hunks)
  • internal/parser/antlr/numscript_lexer.go (2 hunks)
  • internal/parser/parser_test.go (1 hunks)

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.

@ascandone ascandone requested review from altitude and gfyrag December 20, 2024 17:31
@@ -43,6 +43,14 @@ func TestVariable(t *testing.T) {
snaps.MatchSnapshot(t, p.Value)
}

func TestNumberSyntaxUnderscore(t *testing.T) {
p := parser.Parse(`
set_tx_meta("k1", 1_2_34_567)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Here's the syntax

Start: parser.Position{Character:18, Line:1},
End: parser.Position{Character:28, Line:1},
},
Number: 1234567,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Here's the resulting syntax tree

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 (1)
internal/parser/parser_test.go (1)

46-52: Augment test coverage for underscore usage.

The new test verifying “1_2_34_567” is a good starting point. Consider adding more edge-case tests (e.g., numbers with trailing underscores, multiple consecutive underscores, negative numbers with underscores) to ensure robust parsing of underscore-formatted numeric literals.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9bf4d35 and cefcd19.

⛔ Files ignored due to path filters (1)
  • internal/parser/__snapshots__/parser_test.snap is excluded by !**/*.snap, !**/*.snap
📒 Files selected for processing (5)
  • Numscript.g4 (1 hunks)
  • internal/parser/antlr/NumscriptLexer.interp (1 hunks)
  • internal/parser/antlr/numscript_lexer.go (2 hunks)
  • internal/parser/parser.go (1 hunks)
  • internal/parser/parser_test.go (1 hunks)
🔇 Additional comments (4)
internal/parser/antlr/numscript_lexer.go (1)

Line range hint 69-218: Auto-generated lexer updates for underscore syntax support.

These changes in the serialized ATN (from 326 to 328) reflect the updated grammar allowing underscores in numeric literals. Because this file is ANTLR-generated, no manual intervention is needed here. Just ensure that all underscore-related numeric cases (e.g., trailing underscores, multiple underscores, negative values) are covered by tests.

Numscript.g4 (1)

40-40: 🛠️ Refactor suggestion

Consider restricting underscores usage further.

This grammar rule “NUMBER: MINUS? [0-9][0-9_];” now allows trailing and consecutive underscores (e.g., "123_" or "1__2"). If that’s not intended, consider tightening the pattern (e.g., requiring underscores only between digits like "[0-9]+(_[0-9]+)") or adding validation logic post-parse to reject malformed numeric literals.

internal/parser/antlr/NumscriptLexer.interp (1)

128-128: Auto-generated lexer interpretation changes.

This shift from “326” to “328” confirms alignment with the updated grammar for underscores in numeric literals. No manual revision is required here.

internal/parser/parser.go (1)

588-588: LGTM! Basic underscore support implemented.

The implementation correctly removes underscores from number literals before parsing, enabling support for more readable number formats like 1_000_000.

@@ -585,6 +585,7 @@ func parseSendStatement(statementCtx *parser.SendStatementContext) *SendStatemen

func parseNumberLiteral(numNode antlr.TerminalNode) *NumberLiteral {
amtStr := numNode.GetText()
amtStr = strings.ReplaceAll(amtStr, "_", "")
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider validating underscore placement.

The current implementation accepts any underscore placement, including invalid patterns like __123, _123, 123_, or 1__2. Consider adding validation to ensure underscores follow common programming language conventions:

  • No leading or trailing underscores
  • No consecutive underscores
  • Only between digits

Here's a suggested implementation using regex validation:

 func parseNumberLiteral(numNode antlr.TerminalNode) *NumberLiteral {
 	amtStr := numNode.GetText()
+	// Validate underscore placement: only single underscores between digits
+	if strings.Contains(amtStr, "_") {
+		if matched, _ := regexp.MatchString(`^-?\d+(_\d+)*$`, amtStr); !matched {
+			panic("Invalid number format: " + amtStr + ". Underscores must be between digits.")
+		}
+	}
 	amtStr = strings.ReplaceAll(amtStr, "_", "")

Committable suggestion skipped: line range outside the PR's diff.

Copy link

codecov bot commented Dec 20, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 63.27%. Comparing base (9bf4d35) to head (ed73aa3).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #29      +/-   ##
==========================================
+ Coverage   63.24%   63.27%   +0.03%     
==========================================
  Files          29       29              
  Lines        6456     6462       +6     
==========================================
+ Hits         4083     4089       +6     
  Misses       2191     2191              
  Partials      182      182              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@ascandone ascandone merged commit ae202e9 into main Dec 24, 2024
3 of 4 checks passed
@ascandone ascandone deleted the feat/underscore-syntax-for-number-literals branch December 24, 2024 10:31
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