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

feat: overdraft function #14

Merged
merged 7 commits into from
Dec 6, 2024
Merged

Conversation

ascandone
Copy link
Contributor

@ascandone ascandone commented Oct 28, 2024

Added an overdraft() function which returns the absolute value of the negative balance of the given account and currency; 0 if overdraft is non negative (see tests as reference)

This is a new numscript functionality which is not implemented in the current machine implementation; thus the functionality is under the experimental-overdraft-function feature flag

Copy link

codecov bot commented Oct 28, 2024

Codecov Report

Attention: Patch coverage is 82.89474% with 26 lines in your changes missing coverage. Please review.

Project coverage is 63.24%. Comparing base (4463674) to head (6d64890).
Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
internal/interpreter/interpreter.go 76.59% 7 Missing and 4 partials ⚠️
internal/cmd/run.go 0.00% 8 Missing ⚠️
internal/parser/antlr/numscript_parser.go 94.56% 5 Missing ⚠️
internal/interpreter/interpreter_error.go 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #14      +/-   ##
==========================================
+ Coverage   63.22%   63.24%   +0.01%     
==========================================
  Files          29       29              
  Lines        6390     6456      +66     
==========================================
+ Hits         4040     4083      +43     
- Misses       2171     2191      +20     
- Partials      179      182       +3     

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

@ascandone
Copy link
Contributor Author

ascandone commented Oct 28, 2024

EDIT: fixed

It turns out I couldn't call this function overdraft because that is already a token.
So we would need to use something like overdraft_amount instead (or workaround this issue, which I'm not sure is a good idea)

Base automatically changed from dev to main October 29, 2024 08:59
@ascandone ascandone changed the title draft implementation feat: overdraft function Oct 30, 2024
@ascandone ascandone force-pushed the feat/experiment-overdraft-function branch from c26bdb0 to d619d6e Compare November 21, 2024 02:35
@ascandone ascandone marked this pull request as ready for review November 21, 2024 12:11
@ascandone ascandone force-pushed the feat/experiment-overdraft-function branch from d619d6e to c5dcc88 Compare November 26, 2024 12:48
@ascandone ascandone requested review from altitude and gfyrag November 26, 2024 15:50
@ascandone ascandone force-pushed the feat/experiment-overdraft-function branch from 8f1fd3a to be5b6d9 Compare November 27, 2024 14:47
@ascandone ascandone force-pushed the feat/experiment-overdraft-function branch from 8f26655 to 6d64890 Compare December 6, 2024 10:30
Copy link

coderabbitai bot commented Dec 6, 2024

Walkthrough

The changes in this pull request primarily enhance the Numscript grammar and its associated functionality. Key modifications include the introduction of a new variable fnName in the functionCall rule, allowing for specific tokens like OVERDRAFT. Additionally, a new overdraft feature is implemented in the interpreter, including a dedicated function and error handling for experimental features. The command-line interface is updated to manage this feature with a flag. Various updates to the parser and testing framework ensure compatibility and correctness with the new features.

Changes

File Change Summary
Numscript.g4 Updated functionCall rule to include fnName as `OVERDRAFT
internal/analysis/check.go Added constant FnVarOriginOverdraft and a corresponding entry in Builtins for overdraft functionality.
internal/cmd/run.go Introduced overdraftFeatureFlag for managing overdraft feature in CLI. Updated getRunCmd to include a command flag for enabling/disabling overdraft.
internal/interpreter/interpreter.go Added overdraft function for handling overdraft calculations. Updated handleOrigin method and RunProgram to incorporate overdraft feature flag. Refactored balance function into getBalance.
internal/interpreter/interpreter_error.go Introduced new error type ExperimentalFeature for handling experimental feature errors.
internal/interpreter/interpreter_test.go Added testWithFeatureFlag function for testing with feature flags. Included new test cases for overdraft functionality.
internal/parser/antlr/Numscript.interp Updated token literal and symbolic names. Modified ATN structure for enhanced parsing capabilities.
internal/parser/antlr/numscript_parser.go Added fnName field to FunctionCallContext. Enhanced variable declaration context and source context methods. Improved error handling and refactored parser structure.
internal/parser/parser.go Updated parseFnCall function to retrieve function names using GetFnName(). Adjusted FnCall struct handling for consistency with new parser context methods.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant Interpreter
    participant OverdraftFeature
    participant Parser

    User->>CLI: Invoke command with overdraft flag
    CLI->>Interpreter: Run program with feature flags
    Interpreter->>OverdraftFeature: Check if overdraft feature is enabled
    OverdraftFeature->>Parser: Parse function call with overdraft
    Parser-->>Interpreter: Return parsed function call
    Interpreter-->>CLI: Return results
Loading

🐇 "In the land of Numscript, changes abound,
With overdrafts and tokens, new rules are found.
A feature flag here, a function call there,
Parsing with joy, we hop without care!
So let’s celebrate with a leap and a bound,
For in our code garden, new wonders are found!" 🥕


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

🧹 Outside diff range and nitpick comments (3)
internal/interpreter/interpreter.go (1)

180-183: Consider defining 'FeatureFlag' as a distinct type

Currently, FeatureFlag is defined as a type alias for string using type FeatureFlag = string. If you intend to create a new distinct type, consider defining it as type FeatureFlag string without the =. This can provide stronger type safety and prevent inadvertent assignments of plain strings.

internal/interpreter/interpreter_test.go (1)

99-112: Consider passing an empty map instead of nil for featureFlags

In the RunProgram call (lines 103-112), passing nil for featureFlags could risk a nil map dereference if future code changes access the map without checking for nil. Consider initializing featureFlags as an empty map to enhance robustness.

internal/analysis/check.go (1)

79-83: LGTM with minor documentation enhancement

The function signature and implementation look good. Consider enhancing the documentation to explicitly mention that this is an experimental feature.

-		Docs:   "get absolute amount of the overdraft of an account. Returns zero if balance is not negative",
+		Docs:   "[experimental] get absolute amount of the overdraft of an account. Returns zero if balance is not negative",
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4463674 and 6d64890.

📒 Files selected for processing (9)
  • Numscript.g4 (1 hunks)
  • internal/analysis/check.go (2 hunks)
  • internal/cmd/run.go (3 hunks)
  • internal/interpreter/interpreter.go (7 hunks)
  • internal/interpreter/interpreter_error.go (1 hunks)
  • internal/interpreter/interpreter_test.go (2 hunks)
  • internal/parser/antlr/Numscript.interp (1 hunks)
  • internal/parser/antlr/numscript_parser.go (8 hunks)
  • internal/parser/parser.go (2 hunks)
🔇 Additional comments (16)
internal/parser/antlr/Numscript.interp (1)

104-104: No issues found with the token and ATN modifications

The changes to the Numscript.interp file involve updates to the tokens and ATN structure, which are consistent with the grammar enhancements. No issues detected.

internal/interpreter/interpreter.go (6)

143-149: Handling 'overdraft' origin is properly implemented

The code correctly adds a case for FnVarOriginOverdraft in the handleOrigin method, calling the overdraft function and returning the result appropriately.


203-206: Feature flag for overdraft function is correctly implemented

The code checks for the ExperimentalOverdraftFunctionFeatureFlag in featureFlags and sets the OverdraftFunctionFeatureFlag field appropriately in the programState.


264-264: Added 'OverdraftFunctionFeatureFlag' field to 'programState'

The boolean field OverdraftFunctionFeatureFlag is added to track the enabled state of the overdraft function feature flag within the interpreter state.


798-813: Added 'getBalance' utility function for code reuse

The getBalance function encapsulates the logic for fetching and caching account balances, promoting code reuse and improving maintainability.


829-832: Refactored 'balance' function to use 'getBalance' utility

The balance function now utilizes the getBalance utility function, reducing code duplication and enhancing readability.


851-887: Implemented 'overdraft' function with proper feature flag check

The overdraft function correctly checks the OverdraftFunctionFeatureFlag before executing. It parses the account and asset arguments, retrieves the balance using getBalance, and returns the absolute value of the negative balance as the overdraft amount. The logic appropriately handles positive, zero, and negative balances.

internal/interpreter/interpreter_test.go (2)

85-86: Refactored 'test' function to use 'testWithFeatureFlag' for consistency

The test function now calls testWithFeatureFlag with an empty feature flag, promoting code reuse and ensuring consistent test handling whether feature flags are used or not.


3303-3412: Added comprehensive tests for 'overdraft' function

The test cases TestOverdraftFunctionWhenNegative, TestOverdraftFunctionWhenZero, and TestOverdraftFunctionWhenPositive effectively verify the overdraft function's behavior under various balance conditions. The use of testWithFeatureFlag appropriately checks feature flag enforcement.

Numscript.g4 (1)

63-64: Updated 'functionCall' rule to include 'OVERDRAFT' as a valid function name

The grammar modification allows OVERDRAFT to be recognized as a function name, enabling the parser to correctly handle overdraft function calls.

internal/interpreter/interpreter_error.go (1)

187-195: LGTM: Well-structured error type for experimental features

The new ExperimentalFeature error type is well-implemented, following the established pattern of other error types in the file. The error message clearly communicates the need for a feature flag.

internal/cmd/run.go (3)

29-29: LGTM: Clear feature flag declaration

The feature flag variable follows the package's naming conventions and has clear intent.


120-124: LGTM: Proper feature flag handling

The feature flags map is correctly initialized and populated when the overdraft feature is enabled.


202-204: LGTM: Well-documented flag registration

The feature flag is properly registered with a clear description and safe default value (false).

internal/parser/parser.go (1)

Line range hint 511-524: LGTM: Robust function name parsing

The updated parseFnCall implementation correctly handles the new grammar structure, properly extracting function names from either OVERDRAFT tokens or identifiers while maintaining proper nil checks and error handling.

internal/analysis/check.go (1)

79-83: Add feature flag validation

Since this is an experimental feature (as mentioned in PR objectives), consider adding validation in the type checking phase to ensure the function is only used when the feature flag is enabled.

Let's verify if similar feature flag validations exist in the codebase:

internal/parser/antlr/numscript_parser.go Show resolved Hide resolved
internal/analysis/check.go Show resolved Hide resolved
@ascandone ascandone merged commit 9bf4d35 into main Dec 6, 2024
6 checks passed
@ascandone ascandone deleted the feat/experiment-overdraft-function branch December 6, 2024 15:16
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