Skip to content

Conversation

@seborama
Copy link
Owner

@seborama seborama commented May 4, 2025

Summary by CodeRabbit

  • New Features
    • Added dedicated types for user-defined object properties and methods, supporting dynamic access and invocation with argument evaluation.
  • Refactor
    • Consolidated object method invocation into a unified approach with a new method for runtime evaluation.
    • Simplified internal type structures by removing redundant constructs and updating naming conventions for consistency.
    • Streamlined expression evaluation logic by replacing manual method resolution with direct calls to evaluation methods.
  • Bug Fixes
    • Enhanced error handling and result propagation for undefined values during object property and method access.
  • Documentation
    • Corrected and clarified comments related to object accessor handling and naming conventions.

@coderabbitai
Copy link

coderabbitai bot commented May 4, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This set of changes refactors the handling of object method and property access within the codebase. The previous approach, which used separate ObjectMethod and ObjectProperty types to represent user-defined object methods and properties, is replaced by consolidating method invocation logic into a single DotFunction type that embeds the Function type. The DotFunction type now includes a Calculate method for dynamic method resolution and invocation. The test files and tree builder logic are updated to use DotFunction instead of the previous generic or separated types. Comments and type references are adjusted throughout for consistency with the new design.

Changes

File(s) Change Summary
object.go Refactored DotFunction to embed Function and added a Calculate method; removed ObjectMethod, ObjectProperty, and related logic; updated Member interface.
object_method.go, object_property.go Added new files defining ObjectMethod and ObjectProperty types, their constructors, and calculation logic for user-defined objects.
tree.go Removed objectAccessorDotFunctionFn; updated control flow to call DotFunction.Calculate directly; updated string formatting logic.
tree_builder.go Updated to use DotFunction instead of Dot[Function]; renamed local variable for clarity.
gal_test.go, tree_builder_test.go Updated tests to use DotFunction instead of Dot[Function] for expected parse trees.
tree_config.go Updated comment to reference DotFunction instead of Dot[Function] for consistency.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Tree
    participant DotFunction
    participant Object (Go object)
    participant Config

    User->>Tree: Evaluate expression with chained method calls
    Tree->>DotFunction: Call Calculate(val, cfg)
    DotFunction->>Object: Retrieve method by name via reflection
    Object-->>DotFunction: Return method function (if found)
    DotFunction->>DotFunction: Set BodyFn to retrieved method
    DotFunction->>Config: Evaluate function with context
    Config-->>DotFunction: Return result
    DotFunction-->>Tree: Return result or Undefined
    Tree-->>User: Return final evaluation result
Loading

Possibly related PRs

  • seborama/gal#23: The main PR refactors and consolidates object method invocation by embedding Function into DotFunction and removing the separate ObjectMethod type and its calculation logic, whereas the retrieved PR introduces and adds explicit support for a distinct ObjectMethod type and its handling in the expression tree; thus, the main PR's changes directly replace and remove the functionality introduced by the retrieved PR.
  • seborama/gal#29: The main PR refactors and consolidates the handling of object method calls by embedding Function into DotFunction and removing the previously separate ObjectMethod and ObjectProperty types, whereas the retrieved PR introduces the initial support for general object methods via a new ObjectMethod type and its calculation logic; thus, the main PR supersedes and replaces the approach introduced in the retrieved PR, making their changes directly related at the code level.
  • seborama/gal#28: The main PR refactors DotFunction to embed Function and adds a Calculate method to it, consolidating method invocation logic, while the retrieved PR removes kind() methods and adds Calculate methods to various types including Function, ObjectMethod, and ObjectProperty, indicating both PRs share the same design shift toward polymorphic Calculate methods replacing kind()-based dispatch and are directly related in their changes to function and object method evaluation.

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.

🔧 golangci-lint (1.64.8)

Error: can't load config: can't set severity rule option: no default severity defined
Failed executing command with error: can't load config: can't set severity rule option: no default severity defined


📜 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 d854c4f and e35fa0d.

📒 Files selected for processing (3)
  • object.go (3 hunks)
  • object_method.go (1 hunks)
  • object_property.go (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

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

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

♻️ Duplicate comments (1)
tree_builder_test.go (1)

188-211: (same as above) The repeated replacements are consistent and correct.

🧹 Nitpick comments (8)
tree.go (2)

144-146: DotFunction.Calculate diverges from the other Calculate signatures – verify nil-receiver handling

All other entry types pass (val, op, cfg) to their Calculate method, but DotFunction receives only (val, cfg). The special-case is fine, yet:

  1. Call-sites (here and possibly elsewhere) must guarantee that val is never nil when the accessor is evaluated, otherwise the method will have to detect and report “missing receiver” itself.
  2. Long-term maintainability would benefit from a common interface (Calculate(entry, Operator, *treeConfig)) for all calculable nodes.

Please double-check that DotFunction.Calculate gracefully handles val == nil and document the expectation if it must not be nil.


271-273: Misleading log label: still prints “ObjectAccessor[Function]”

The string output now refers to typedE.String() but the label ObjectAccessor[Function] survived the previous generic naming (Dot[Function]). To keep debugging output accurate and avoid confusion with the new dedicated type, rename the label:

-			res += fmt.Sprintf("%sObjectAccessor[Function] %s\n", indent, typedE.String())
+			res += fmt.Sprintf("%sDotFunction %s\n", indent, typedE.String())

Minor, yet it pays off when tracing complex evaluation logs.

tree_config.go (1)

94-95: Out-of-date comment reference

The comment mentions Dot[Variable] / DotFunction; while correct, the previous part of the sentence still talks about using a Variable or a Function first. Consider amending the whole sentence for clarity:

“…then a DotVariable or DotFunction

Pure documentation tweak, but helps future readers.

object_method.go (2)

16-22: Constructor arg name is misleading – use methodName instead of propertyName.
The second parameter refers to a method but is named propertyName, which will confuse readers and IDE ref-tools.

-func NewObjectMethod(objectName, propertyName string, args ...Tree) ObjectMethod {
+func NewObjectMethod(objectName, methodName string, args ...Tree) ObjectMethod {
 	return ObjectMethod{
-		ObjectName: objectName,
-		MethodName: propertyName,
+		ObjectName: objectName,
+		MethodName: methodName,
 		Args:       args,
 	}
 }

45-47: Minor: include arguments in String for easier debugging.

Right now the string form is aCar.CurrentSpeed; adding argument info helps when several overloads exist:

return fmt.Sprintf("%s.%s(%d arg(s))", om.ObjectName, om.MethodName, len(om.Args))
object.go (1)

22-27: Unchecked type assertion may return misleading “syntax error”.

val.(Value) is attempted after the earlier ok := val.(Value); if val is not a Value, the function already returns an Undefined but the panic path is still reachable at line 40 when calculate is called.

Reuse the already-asserted receiver variable to avoid the second assertion:

-	val = calculate(val.(Value), op, rhsVal)
+	val = calculate(receiver.(Value), op, rhsVal)
tree_builder_test.go (1)

221-229: Readable but consider named field for clarity.

Although legal, using an unnamed literal may puzzle newcomers. A tiny readability tweak:

gal.DotFunction{
    Function: gal.NewFunction( ... ),
},
object_property.go (1)

23-37: Consider adding proper error handling for type assertions.

The linter directive to ignore error checking for type assertions has a humorous comment, but this approach could lead to runtime panics. While this may be acceptable for now, proper error handling would improve robustness.

-//nolint:errcheck // life's too short to check for type assertion success here
-func (o ObjectProperty) Calculate(val entry, op Operator, cfg *treeConfig) entry {
+func (o ObjectProperty) Calculate(val entry, op Operator, cfg *treeConfig) entry {
 	rhsVal := cfg.ObjectProperty(o)
 	if u, ok := rhsVal.(Undefined); ok {
 		return u
 	}

 	if val == nil {
 		return rhsVal
 	}

-	val = calculate(val.(Value), op, rhsVal)
+	lhsVal, ok := val.(Value)
+	if !ok {
+		return NewUndefinedWithReasonf("error: left-hand side value not a valid Value type when accessing %s", o)
+	}
+	val = calculate(lhsVal, op, rhsVal)

 	return val
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 196c4f9 and d854c4f.

📒 Files selected for processing (8)
  • gal_test.go (1 hunks)
  • object.go (3 hunks)
  • object_method.go (1 hunks)
  • object_property.go (1 hunks)
  • tree.go (2 hunks)
  • tree_builder.go (1 hunks)
  • tree_builder_test.go (3 hunks)
  • tree_config.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
tree_builder.go (2)
function.go (1)
  • Function (18-23)
object.go (1)
  • DotFunction (12-12)
object_method.go (5)
tree.go (1)
  • Tree (10-10)
operator.go (1)
  • Operator (3-3)
function.go (2)
  • NewFunction (25-31)
  • Eval (281-293)
tree_config.go (3)
  • WithFunctions (142-146)
  • WithVariables (134-138)
  • WithObjects (152-156)
value.go (1)
  • Value (7-13)
tree.go (1)
object.go (1)
  • DotFunction (12-12)
object.go (5)
function.go (2)
  • Function (18-23)
  • Eval (281-293)
value_undefined.go (4)
  • NewUndefinedWithReasonf (24-28)
  • Undefined (16-18)
  • Undefined (91-93)
  • Undefined (95-97)
value.go (1)
  • Value (7-13)
tree_config.go (3)
  • WithFunctions (142-146)
  • WithVariables (134-138)
  • WithObjects (152-156)
variable.go (1)
  • Variable (3-5)
🔇 Additional comments (5)
object.go (2)

14-19: Early “internal error” blocks legitimate reuse of DotFunction.

DotFunction.Calculate refuses to run when BodyFn is pre-set, yet you set it later in the same method (line 39).
If a previously evaluated DotFunction is reused (e.g. in another branch) this guard will wrongly fail.

Consider only erroring when BodyFn belongs to a built-in function (detectable via cfg.functions) or simply drop this check.


51-51: Generics cleanup looks good.

Limiting Member to just Variable simplifies the generic Dot API without breaking current use-cases.

tree_builder_test.go (1)

178-187: Test update matches the new API – good catch.

Replacing the generic Dot[Function] by DotFunction keeps the test aligned with the refactor and compiles cleanly with anonymous-field struct literals.

gal_test.go (1)

551-568: Type change from generic to concrete looks good.

The updated code correctly uses the new DotFunction type which embeds Function instead of the previous generic Dot[Function] type. This aligns with the refactoring that consolidates method invocation logic into a single type.

object_property.go (1)

7-14: Good structure for object property access.

The ObjectProperty type is well-designed for representing object property access. The TODO comment raises an interesting point about potential unification with the pattern used for Function.Receiver - consider exploring this in a future update.

@seborama seborama enabled auto-merge May 4, 2025 08:11
@seborama seborama merged commit b680bcf into main May 4, 2025
2 of 3 checks passed
@seborama seborama deleted the DotFunction branch May 4, 2025 08:11
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