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

SchemeVar newtype #257

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

SchemeVar newtype #257

wants to merge 2 commits into from

Conversation

gelisam
Copy link
Owner

@gelisam gelisam commented Nov 1, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new type SchemeVar for improved type handling.
    • Added a new operator (!) for enhanced key-value retrieval in the Store type.
    • Implemented toAscList function for sorted key-value pairs in the Store.
  • Bug Fixes

    • Enhanced error handling for ambiguous bindings and type resolution.
  • Documentation

    • Updated variable names for clarity in the Pretty module.
  • Refactor

    • Improved type variable management and instantiation processes across multiple modules.
    • Enhanced flexibility in type argument preparation and macro definitions.

Copy link

coderabbitai bot commented Nov 1, 2024

Walkthrough

The changes across multiple modules enhance type handling and expand functionality within the expander system. Key modifications include the introduction of a new type SchemeVar, adjustments to function signatures to accommodate this new type, and refinements in error handling and type instantiation processes. The Expander module's functions have been updated for better flexibility with type variables, while the Pretty module has undergone renaming for consistency. New methods for the Store type improve its usability, and a new instance for Natural extends the HasKey functionality.

Changes

File Change Summary
src/Expander.hs Updated function signatures for initializeKernel, getExports, getImports, expandOneExpression, and expandOnePattern to accommodate new type variables and improve type handling.
src/Expander/Monad.hs Changed ETypeVar constructor's second parameter from Natural to SchemeVar, affecting type variable representation.
src/Expander/Primitives.hs Modified prepareTypeVar to accept SchemeVar instead of Natural, updated datatype and defineMacros for better type argument handling.
src/Expander/TC.hs Altered inst function to accept Store SchemeVar Ty, modified specialize, generalizeType, and instCtor for improved type management.
src/Pretty.hs Renamed typeVarNames to schemeVarNames, added schemeVarName function for better pretty-printing of types.
src/Type.hs Introduced SchemeVar as a newtype wrapper around Natural, updated TSchemaVar constructor and tSchemaVar method accordingly.
src/Util/Key.hs Added new instance of HasKey for Natural, implementing getKey and fromKey methods.
src/Util/Store.hs Introduced new operator (!) for direct value access by key and added toAscList function for sorted key-value retrieval.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Expander
    participant Store

    User->>Expander: Initialize Kernel
    Expander->>Store: Create SchemeVars
    Expander->>Expander: Expand Expressions
    Expander->>Store: Retrieve Values with (!)
    Store-->>Expander: Return Value
    Expander-->>User: Return Result
Loading

🐰 "In the land of types, where schemes do play,
A new SchemeVar hops in, brightening the day.
With Expander so clever, and Store now so neat,
We dance with our types, oh, what a treat!
Errors are fewer, and printing's a breeze,
In this joyful code garden, we code with ease!" 🐇


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1bd181a and 0c741b9.

📒 Files selected for processing (1)
  • src/Expander.hs (4 hunks)
🔇 Additional comments (7)
src/Expander.hs (7)

542-543: Corrected kind variables in pure-IO

The function pure-IO now correctly specifies a single kind KStar for the type variable a, matching the usage in the function signature.


547-552: Updated bind-IO with appropriate type variables

The function bind-IO now introduces distinct type variables a and b, each with kind KStar. This ensures proper type generalization and function correctness.


592-593: Introduced Maybe datatype with type variable

The Maybe data type is correctly defined with type variable a of kind KStar, and constructors nothing and just, aligning with standard conventions.


594-600: Defined List datatype with recursive structure

The List data type is properly defined with type variable a, and constructors nil and ::, correctly representing a recursive list structure.


603-610: Maintained synchronization between constructors and patterns

The inclusion of the comment reminds developers to add corresponding patterns in close-syntax when adding new constructors to Syntax-Contents, preventing potential errors.


1228-1230: Proper instantiation of type arguments in expression expansion

The type arguments argTys are correctly generated and mapped to schema variables starting from firstSchemeVar, ensuring accurate type instantiation in expression expansion.


1243-1245: Accurate type arguments generation for pattern expansion

The code appropriately generates tyArgs and constructs tyStore for pattern matching, ensuring consistency in type variable usage.


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

🧹 Outside diff range and nitpick comments (4)
src/Util/Store.hs (1)

89-91: LGTM: Consider adding a Haddock comment.

The implementation is correct and efficient, using IM.toAscList and maintaining consistency with toList. Consider adding a Haddock comment to document that the list is sorted by keys.

-- | Returns a list of key/value pairs in ascending key order.
toAscList :: HasKey p => Store p v -> [(p,v)]
src/Type.hs (2)

39-44: LGTM! Consider adding documentation.

The SchemeVar newtype and its instances are well-designed. The derived instances provide all necessary functionality for type variables in a type system.

Consider adding Haddock documentation to explain:

  • The purpose and invariants of SchemeVar
  • Why firstSchemeVar starts at 0
  • Whether there are any constraints on valid SchemeVar values

Line range hint 39-125: Well-structured type system enhancement.

The introduction of SchemeVar and its systematic integration throughout the type system is a good architectural improvement that:

  1. Enhances type safety by preventing accidental mixing of scheme variable IDs with raw natural numbers
  2. Makes the code more maintainable by making scheme variable usage explicit
  3. Provides a foundation for potential future extensions to the type system

The changes follow the "make invalid states unrepresentable" principle of type-driven design.

src/Expander/Monad.hs (1)

Line range hint 4-4: Add tests for the expander functionality.

While the codebase demonstrates excellent practices in terms of documentation, error handling, and state management, there's a TODO comment indicating missing tests. Given the complexity of the expander system and the recent type variable representation changes, comprehensive tests would be valuable.

Would you like me to help create a test suite for this functionality?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 750d792 and 1bd181a.

📒 Files selected for processing (8)
  • src/Expander.hs (4 hunks)
  • src/Expander/Monad.hs (1 hunks)
  • src/Expander/Primitives.hs (2 hunks)
  • src/Expander/TC.hs (4 hunks)
  • src/Pretty.hs (4 hunks)
  • src/Type.hs (3 hunks)
  • src/Util/Key.hs (1 hunks)
  • src/Util/Store.hs (3 hunks)
🔇 Additional comments (16)
src/Util/Key.hs (2)

7-7: LGTM!

The import of Numeric.Natural is necessary for the new HasKey instance.


17-19: Implementation looks correct, but let's verify key usage patterns.

The implementation is sound for typical key-value store usage where keys are expected to be small, non-negative integers.

Let's verify our assumptions about key usage patterns:

✅ Verification successful

The previous results show that getKey/fromKey are primarily used in data structures (Store, Set) and for unique identifiers, but let's verify the complete context of Natural usage to ensure our assumptions about the safety of conversions are correct.


Implementation is safe for its intended use

The verification shows that Natural is used in controlled contexts:

  • As binding levels and scheme variables in the type system
  • For phase numbers in the module system
  • For fixed-length list checking and type arity
  • No evidence of large numeric operations or unsafe bounds

The HasKey Natural implementation using fromIntegral is appropriate because:

  1. Natural values are used for small, controlled counters (phases, binding levels)
  2. No instances of arithmetic that could lead to large numbers
  3. All conversions are within the safe range of Int for the observed use cases
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for patterns of key generation and usage to ensure they align with our assumptions
# about small, non-negative integers

# Look for key generation patterns
echo "Checking key generation patterns..."
rg -A 3 "getKey|fromKey" --type haskell

# Look for Natural key usage
echo "Checking Natural key usage patterns..."
rg -A 3 "Natural.*->.*Store|Store.*->.*Natural" --type haskell

Length of output: 7328


Script:

#!/bin/bash
# Let's check for Natural type usage in the codebase to understand the context better
echo "Checking Natural type usage..."
rg "Natural" --type haskell -B 2 -A 2

# Let's also check for any numeric bounds or range checks
echo "Checking for numeric bounds/range checks..."
rg "(maxBound|minBound|>=|<=|>|<).*Natural" --type haskell -B 2 -A 2

# Look for any imports of Natural to understand its source
echo "Checking Natural imports..."
rg "import.*Natural" --type haskell

Length of output: 6756

src/Util/Store.hs (1)

18-18: LGTM: Export list updated correctly.

The new functions are properly exported and maintain alphabetical ordering.

Also applies to: 22-22

src/Type.hs (2)

56-56: LGTM! Type-safe update to TSchemaVar.

The change from Natural to SchemeVar improves type safety by preventing accidental mixing of scheme variable IDs with other natural numbers.


125-125: Verify all TyLike instances are updated.

The signature change from Natural to SchemeVar is correct and consistent with the new type system.

Let's verify all instances have been updated:

✅ Verification successful

All TyLike instances are correctly updated with SchemeVar

Both instances of TyLike (TyF a and Ty) have been properly updated to use the new SchemeVar type in their tSchemaVar method implementations. No other instances exist that would need updating.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining instances of TyLike that might need updating
ast-grep --pattern 'instance TyLike $_ $_'

Length of output: 1281

src/Pretty.hs (4)

314-314: LGTM: Variable reference updated correctly.

The change from typeVarNames to schemeVarNames is consistent with the renaming.


Line range hint 320-334: LGTM: Clear and descriptive variable naming.

The renaming from typeVarNames to schemeVarNames better reflects its purpose in the context of scheme variables. The implementation remains clean and efficient.


348-348: LGTM: Consistent use of new helper function.

The pretty-printing of TSchemaVar correctly uses the new schemeVarName helper function.


335-336: 🛠️ Refactor suggestion

Consider adding bounds checking.

The schemeVarName function could potentially crash if the index exceeds the list length. Consider adding bounds checking or using a safe indexing function.

-schemeVarName :: SchemeVar -> Text
-schemeVarName (SchemeVar n) = schemeVarNames !! fromIntegral n
+schemeVarName :: SchemeVar -> Text
+schemeVarName (SchemeVar n) = 
+  let idx = fromIntegral n
+  in if idx < length schemeVarNames
+     then schemeVarNames !! idx
+     else error $ "SchemeVar index " ++ show n ++ " out of bounds"
src/Expander/Monad.hs (1)

244-244: LGTM! Verify type variable handling across the codebase.

The change from Natural to SchemeVar for type variables improves type safety and semantic clarity. This aligns well with the PR objective of introducing the SchemeVar newtype.

Let's verify the consistency of this change across the codebase:

✅ Verification successful

Let me gather more context about the usage of SchemeVar to ensure complete verification.


Change from Natural to SchemeVar is consistently implemented

The verification shows that the transition from Natural to SchemeVar has been thoroughly and consistently implemented across the codebase:

  • SchemeVar is properly defined as a newtype wrapper over Natural in src/Type.hs
  • All type variable handling code has been updated to use SchemeVar:
    • Type constructor ETypeVar in src/Expander/Monad.hs
    • Type instantiation in src/Expander/TC.hs
    • Type variable preparation in src/Expander/Primitives.hs
    • Type generalization in src/Expander/TC.hs

No remaining usages of Natural in type variable contexts were found, confirming complete migration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining Natural usages in type variable contexts
# and verify SchemeVar adoption

# Search for potential Natural usage in type variable contexts
rg -p "Natural.*[Tt]ype[Vv]ar|[Tt]ype[Vv]ar.*Natural"

# Search for SchemeVar usage patterns to verify consistent adoption
rg -p "SchemeVar.*[Tt]ype[Vv]ar|[Tt]ype[Vv]ar.*SchemeVar"

Length of output: 272


Script:

#!/bin/bash
# Search for all SchemeVar definitions and usages
rg -p "SchemeVar" -A 3 -B 3

# Search for any remaining type variable related code
rg -p "[Tt]ype[Vv]ar" -A 3 -B 3

Length of output: 11803

src/Expander/Primitives.hs (1)

Line range hint 714-718: Confirmation: Function prepareTypeVar Correctly Updated to Use SchemeVar

The prepareTypeVar function's signature has been updated from accepting a Natural to a SchemeVar, which enhances type safety by encapsulating the Natural within a newtype. The implementation correctly handles the SchemeVar type, and the changes align with the overall refactoring effort.

src/Expander.hs (5)

547-552: bind-IO function definition is correct.

The bind-IO function is properly defined with the correct kinds, type variables, and implementation.


593-593: Addition of Maybe datatype is correct.

The Maybe datatype is correctly defined with kind [KStar] and constructors nothing and just.


595-600: Definition of List datatype is appropriate.

The List datatype is correctly defined with kind [KStar] and constructors nil and ::.


1228-1230: Type unification and instantiation logic is correctly implemented.

The unification of the type destination and datatype with type arguments, along with instantiation of argument types, is appropriate.


1243-1245: Pattern argument types are correctly instantiated.

The argument types for the pattern match are correctly instantiated using the type store.

src/Util/Store.hs Show resolved Hide resolved
src/Expander/TC.hs Show resolved Hide resolved
src/Expander/TC.hs Show resolved Hide resolved
src/Expander/TC.hs Show resolved Hide resolved
src/Expander/TC.hs Show resolved Hide resolved
src/Expander/Primitives.hs Show resolved Hide resolved
src/Expander.hs Show resolved Hide resolved
src/Expander.hs Outdated Show resolved Hide resolved
pure-IO :: forall a. a -> IO a
not
pure-IO :: forall a b. a -> IO a

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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