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 (preliminary) support for dicts structure #17

Merged
merged 14 commits into from
Nov 20, 2024
Merged

Add (preliminary) support for dicts structure #17

merged 14 commits into from
Nov 20, 2024

Conversation

ccamel
Copy link
Member

@ccamel ccamel commented Nov 15, 2024

This PR introduces preliminary support for Dicts in prolog, a named structure representing key-value pairs. The implementation largely follows the specifications outlined in SWI-Prolog's documentation.

Feature overview

Here's some examples illustrating the feature.

?- A = point{x:1,y:2}.x.
A = 1

?- S = segment{to:point{y:20, x:10}, from:point{y:2, x:1}}.to.x.
S = 10

?- A = point{x:1,y:2}.get(x).
A = 1

?- Tag = point, X = Tag{y:2, x:6}.
Tag = point
X = point{x:6,y:2}

?- [point{x: A}, point{x: B}] = [point{x:1}, point{x:2}].
A = 1
B = 2

?- S = segment{to:point{y:20, x:10}, from:point{y:2, x:1}}.get(to/x).
S = 10

?- A = point{x:1, y:2}.put(_{x:3}).
A = point{x:3,y:2}

?- A = point{b:2, d:4, f:6}.put([a:1, c=3, e(5)]).
A = point{a:1,b:2,c:3,d:4,e:5,f:6}

Implementation strategy

Data structure

Dicts are currently represented as a compound term (Compound) using the functor dict.

  • The first argument is the Tag.
  • Subsequent arguments form an array of key-value pairs, sorted by key.
  • Keys are atoms, and values are Prolog terms.

Rationale:
This representation is simple, easy to implement, and benefits from Prolog's pattern matching and unification mechanics due to its compatibility with compound terms.

Parsing

Dict

The parser is adjusted to support reading dictionaries. The representation format mirrors SWI-Prolog:

Tag{Key1:Value1, Key2:Value2, ...}

Functional notation for Dicts

Dictionaries can be accessed using functional notation (infix). For example, to retrieve the value associated with the key Key in the dictionary Dict, you can write Dict.Key.

To enable this, in case there is no current op-declaration for an operator . and the dot does not serve as operand, the parser interprets the dot as an infix operator that maps to $dot/2. This operator acts as syntactic sugar for invoking the op/3 function to evaluate dictionary operations during the compilation of clauses.

Compilation

During clause compilation, a desugaring step translates terms containing $dot/2 into equivalent sub-goals with ./3.

Example:

?- S = segment{from:point{x:1, y:2}, to:point{x:10, y:20}}.from.x.
S = 1.

is translated into:

?- .(segment{from:point{x:1, y:2}, to:point{x:10, y:20}}, from, _V0),
   .(_V0, x, _V1),
   =(S, _V1).
S = 1.

with the generated bytecode:

get_var(0)
get_var(1)
get_var(2)
enter()
put_dict(5)
put_const(segment)
put_const(from)
put_dict(5)
put_const(point)
put_const(x)
put_const(1)
put_const(y)
put_const(2)
pop()
put_const(to)
put_dict(5)
put_const(point)
put_const(x)
put_const(10)
put_const(y)
put_const(20)
pop()
pop()
put_const(from)
put_var(0)
call(. /3)
put_var(0)
put_const(x)
put_var(1)
call(. /3)
put_var(2)
put_var(1)
call(= /2)
exit()

Implemented features

This PR implements the following features for Dicts:

  • Key-based value access using single or nested keys.
  • Access via the get(?KeyPath) function (t{a:x}.get(a), t{a:t{b:x}}.get(a/b)).
  • Value modification using the put(+New) function (point{x:1, y:2}.put(_{x:3}), point{x:1, y:2}.put([x=3])).

See unit tests for a complete overview.

Additional considerations

  • Dicts are currently implemented as compound terms, but this representation might evolve for performance reasons.
  • The parser modifications may cause compatibility issues with existing programs. While extensive unit tests cover a wide range of cases, edge cases may still arise.

Future Work

Planned improvements include:

  • Support for small integer keys (S = point{6:1, x:12}).
  • Predefined functions:
    • get(?KeyPath, +Default)
    • put(+KeyPath, +Value)
  • Support for user-defined functions.
  • Predicates for managing dicts (see: SWI-Prolog Dict Predicates):
    • is_dict(@Term)
    • is_dict(@Term, -Tag)
    • get_dict(+Key, +Dict, -Value, -NewDict, +NewValue)
    • dict_create(-Dict, +Tag, +Data)
    • dict_pairs(?Dict, ?Tag, ?Pairs)
    • dict_same_keys(?Dict1, ?Dict2)
    • put_dict(+New, +DictIn, -DictOut)
    • put_dict(+Key, +DictIn, +Value, -DictOut)
    • del_dict(+Key, +DictIn, ?Value, -DictOut)
    • +Select :< +From
    • select_dict(+Select, +From, -Rest)
    • +Dict1 >:< +Dict2

@ccamel ccamel self-assigned this Nov 15, 2024
Copy link

coderabbitai bot commented Nov 15, 2024

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Walkthrough

The pull request introduces several enhancements to the Prolog engine, including the addition of a new operator . in the bootstrap script, two new well-known atoms in the engine, and the implementation of a dictionary structure. It also adds methods for bytecode emission and enhances the parser to support dictionary-like structures and sub-goals. Furthermore, it updates the interpreter to handle dictionary operations and includes new tests to validate these functionalities. Overall, these changes expand the expressiveness and capabilities of the Prolog environment.

Changes

File Change Summary
bootstrap.pl Added operator op(100, yfx, .) to denote end of clause.
engine/atom.go Introduced new atoms: atomDict initialized with NewAtom("dict") and atomDictKey initialized with NewAtom("dict_key").
engine/clause.go Added method emit to clause struct for appending instructions to bytecode. Enhanced compileBodyArg to handle Dict types.
engine/dict.go Introduced dictionary implementation with Dict interface and methods for key-value operations, error handling, and utility functions.
engine/exception.go Added constants validTypeDict and validDomainDictKey for dictionary types and keys.
engine/parser.go Enhanced Parser struct with subGoals field. Added methods for applying sub-goals, desugaring operators, and parsing dictionaries.
engine/parser_test.go Modified TestParser_Term to reflect updated expectations for token parsing.
engine/vm.go Added method String() for instruction type and new opcode OpPutDict for handling dictionary terms in the virtual machine.
interpreter.go Registered new predicates get_dict, put_dict, and operator . in the interpreter.
interpreter_test.go Introduced TestDict function to validate dictionary handling in the interpreter, including construction, unification, and access of dictionaries.

Possibly related PRs

Suggested reviewers

  • amimart
  • bdeneux

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

codecov bot commented Nov 15, 2024

Codecov Report

Attention: Patch coverage is 94.89362% with 24 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
engine/parser.go 87.50% 10 Missing and 2 partials ⚠️
engine/dict.go 96.01% 10 Missing ⚠️
engine/clause.go 97.75% 2 Missing ⚠️

Impacted file tree graph

@@            Coverage Diff             @@
##             main      #17      +/-   ##
==========================================
- Coverage   98.29%   97.86%   -0.44%     
==========================================
  Files          23       24       +1     
  Lines        6582     7822    +1240     
==========================================
+ Hits         6470     7655    +1185     
- Misses         81      134      +53     
- Partials       31       33       +2     
Files with missing lines Coverage Δ
engine/atom.go 100.00% <ø> (ø)
engine/builtin.go 99.52% <100.00%> (-0.04%) ⬇️
engine/env.go 97.68% <100.00%> (-0.13%) ⬇️
engine/exception.go 100.00% <ø> (ø)
engine/vm.go 94.51% <100.00%> (-0.06%) ⬇️
interpreter.go 97.98% <100.00%> (+0.78%) ⬆️
engine/clause.go 99.04% <97.75%> (-0.96%) ⬇️
engine/dict.go 96.01% <96.01%> (ø)
engine/parser.go 97.92% <87.50%> (-1.59%) ⬇️

... and 14 files with indirect coverage changes


🚨 Try these New Features:

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

🧹 Outside diff range and nitpick comments (10)
bootstrap.pl (1)

24-24: Verify integration with core predicates.

The new . operator needs careful integration with existing core predicates. Please ensure:

  1. Term I/O predicates correctly handle dictionary terms
  2. Term comparison predicates work with dictionary access expressions
  3. Existing programs using dot in other contexts aren't affected

Consider adding test cases that verify:

  • Writing and reading dictionary terms
  • Term comparison with dictionary access
  • Interaction with other operators
  • Backward compatibility with existing dot usage
engine/vm.go (1)

53-59: Consider error handling and string formatting efficiency.

The current implementation can be improved in two ways:

  1. Error handling: The WriteTerm error is silently ignored
  2. Memory efficiency: Using strings.Builder for a single write is unnecessary

Consider this simpler and more robust implementation:

 func (i instruction) String() string {
-	var sb strings.Builder
 	if i.operand != nil {
-		_ = i.operand.WriteTerm(&sb, &defaultWriteOptions, nil)
+		var sb strings.Builder
+		if err := i.operand.WriteTerm(&sb, &defaultWriteOptions, nil); err != nil {
+			return fmt.Sprintf("%s(<error: %v>)", i.opcode, err)
+		}
+		return fmt.Sprintf("%s(%s)", i.opcode, sb.String())
 	}
-	return fmt.Sprintf("%s(%s)", i.opcode, sb.String())
+	return fmt.Sprintf("%s", i.opcode)
 }
engine/dict.go (2)

225-267: Increase test coverage for GetDict3 function

Static analysis indicates that several lines in GetDict3 are not covered by tests. This includes scenarios where keyPath is a variable, an atom, or a compound term.

Would you like assistance in creating additional unit tests to improve coverage and ensure all code paths are tested?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 225-238: engine/dict.go#L225-L238
Added lines #L225 - L238 were not covered by tests


[warning] 241-256: engine/dict.go#L241-L256
Added lines #L241 - L256 were not covered by tests


[warning] 260-262: engine/dict.go#L260-L262
Added lines #L260 - L262 were not covered by tests


93-126: Handle potential write errors in WriteTerm method

The WriteTerm method handles errors when writing to io.Writer, but could be structured more cleanly.

Consider simplifying error handling using a helper function or by grouping write operations to reduce repetitive code.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 93-97: engine/dict.go#L93-L97
Added lines #L93 - L97 were not covered by tests


[warning] 99-102: engine/dict.go#L99-L102
Added lines #L99 - L102 were not covered by tests


[warning] 104-108: engine/dict.go#L104-L108
Added lines #L104 - L108 were not covered by tests


[warning] 110-118: engine/dict.go#L110-L118
Added lines #L110 - L118 were not covered by tests


[warning] 121-125: engine/dict.go#L121-L125
Added lines #L121 - L125 were not covered by tests

engine/parser.go (4)

149-164: Consider adding comments to applySubGoals function for clarity.

The recursive handling of sub-goals, especially with conditional terms using atomIf, may benefit from inline comments explaining the logic and purpose for better maintainability.


412-426: Consider documenting the desugar function to explain operator transformations.

Adding comments to desugar will help future developers understand how certain operators are transformed during parsing, particularly the handling of atomDot.


830-885: Review error handling in dict function for better readability.

While the implementation correctly parses dictionaries, the error handling when parsing the tag could be streamlined. Reorganizing the error cases or adding comments can enhance clarity.


887-909: Add comments to keyValue function to improve maintainability.

Documenting the steps within keyValue will aid in understanding how keys and values are parsed, especially the handling of tokens and expected formats.

interpreter_test.go (2)

848-851: Rename error field to err to avoid confusion with the built-in error interface

The field name error in the result struct may cause confusion with the built-in error type in Go. It's a common practice to use err for variables or fields of type error to improve code clarity.

Apply this diff to rename the field:

 type result struct {
 	solutions map[string]TermString
-	error     error
+	err       error
 }

1091-1101: Use assert.ErrorIs or assert.ErrorContains instead of assert.EqualError for error comparisons

Comparing errors using assert.EqualError with exact error messages can make tests fragile if the error messages change. Consider using assert.ErrorIs to compare error types or assert.ErrorContains to check for substrings within the error message, enhancing test robustness.

For instance, modify the assertions as follows:

-assert.EqualError(t, err, tt.wantError.Error())
+assert.ErrorIs(t, err, tt.wantError)

Ensure that tt.wantError is the exact error type returned by the function. Alternatively, if comparing error messages, you can use:

-assert.EqualError(t, sols.Err(), tr.error.Error())
+assert.ErrorContains(t, sols.Err(), "instantiation_error")

This approach focuses on key parts of the error message, reducing brittleness due to minor changes in error text.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between be90013 and 386ab13bb550d09b6ac5339c8faf1c96668caa81.

⛔ Files ignored due to path filters (2)
  • .github/workflows/go.yml is excluded by !**/*.yml
  • go.mod is excluded by !**/*.mod
📒 Files selected for processing (10)
  • bootstrap.pl (1 hunks)
  • engine/atom.go (2 hunks)
  • engine/clause.go (4 hunks)
  • engine/dict.go (1 hunks)
  • engine/exception.go (4 hunks)
  • engine/parser.go (6 hunks)
  • engine/parser_test.go (1 hunks)
  • engine/vm.go (4 hunks)
  • interpreter.go (1 hunks)
  • interpreter_test.go (3 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
engine/clause.go

[warning] 173-178: engine/clause.go#L173-L178
Added lines #L173 - L178 were not covered by tests

engine/dict.go

[warning] 43-44: engine/dict.go#L43-L44
Added lines #L43 - L44 were not covered by tests


[warning] 55-56: engine/dict.go#L55-L56
Added lines #L55 - L56 were not covered by tests


[warning] 63-67: engine/dict.go#L63-L67
Added lines #L63 - L67 were not covered by tests


[warning] 69-71: engine/dict.go#L69-L71
Added lines #L69 - L71 were not covered by tests


[warning] 73-73: engine/dict.go#L73
Added line #L73 was not covered by tests


[warning] 77-78: engine/dict.go#L77-L78
Added lines #L77 - L78 were not covered by tests


[warning] 80-81: engine/dict.go#L80-L81
Added lines #L80 - L81 were not covered by tests


[warning] 86-87: engine/dict.go#L86-L87
Added lines #L86 - L87 were not covered by tests


[warning] 93-97: engine/dict.go#L93-L97
Added lines #L93 - L97 were not covered by tests


[warning] 99-102: engine/dict.go#L99-L102
Added lines #L99 - L102 were not covered by tests


[warning] 104-108: engine/dict.go#L104-L108
Added lines #L104 - L108 were not covered by tests


[warning] 110-118: engine/dict.go#L110-L118
Added lines #L110 - L118 were not covered by tests


[warning] 121-125: engine/dict.go#L121-L125
Added lines #L121 - L125 were not covered by tests


[warning] 129-130: engine/dict.go#L129-L130
Added lines #L129 - L130 were not covered by tests


[warning] 133-134: engine/dict.go#L133-L134
Added lines #L133 - L134 were not covered by tests


[warning] 137-138: engine/dict.go#L137-L138
Added lines #L137 - L138 were not covered by tests


[warning] 141-142: engine/dict.go#L141-L142
Added lines #L141 - L142 were not covered by tests


[warning] 145-146: engine/dict.go#L145-L146
Added lines #L145 - L146 were not covered by tests


[warning] 149-150: engine/dict.go#L149-L150
Added lines #L149 - L150 were not covered by tests


[warning] 153-157: engine/dict.go#L153-L157
Added lines #L153 - L157 were not covered by tests


[warning] 160-160: engine/dict.go#L160
Added line #L160 was not covered by tests


[warning] 163-168: engine/dict.go#L163-L168
Added lines #L163 - L168 were not covered by tests


[warning] 171-178: engine/dict.go#L171-L178
Added lines #L171 - L178 were not covered by tests


[warning] 187-210: engine/dict.go#L187-L210
Added lines #L187 - L210 were not covered by tests


[warning] 212-214: engine/dict.go#L212-L214
Added lines #L212 - L214 were not covered by tests


[warning] 216-217: engine/dict.go#L216-L217
Added lines #L216 - L217 were not covered by tests


[warning] 225-238: engine/dict.go#L225-L238
Added lines #L225 - L238 were not covered by tests


[warning] 241-256: engine/dict.go#L241-L256
Added lines #L241 - L256 were not covered by tests


[warning] 260-262: engine/dict.go#L260-L262
Added lines #L260 - L262 were not covered by tests

🔇 Additional comments (19)
bootstrap.pl (2)

24-24: LGTM! Operator declaration is well-placed.

The . operator declaration is correctly placed in the operators section and follows the precedence-based ordering pattern.


24-24: Verify operator precedence compatibility with SWI-Prolog.

The addition of the . operator with precedence 100 and type yfx appears to be for dictionary access (e.g., Dict.Key). While the implementation follows SWI-Prolog's approach, this diverges from ISO Prolog standards and could affect existing programs.

Let's verify the operator declaration matches SWI-Prolog's implementation:

✅ Verification successful

The operator declaration matches SWI-Prolog's implementation

The search results confirm that the . operator with precedence 100 and type yfx is correctly implemented for dictionary access. The test cases in interpreter_test.go specifically mark conflicts with Dict implementation for other operator types (xfy, xfx), indicating this implementation aligns with the intended dictionary support.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check SWI-Prolog's documentation and source for the dot operator declaration
# Expected: Should find matching operator declaration (op(100, yfx, .))

# Search for dot operator in documentation or source files
rg -i "op.*[^a-z]\\.[^a-z].*yfx|yfx.*[^a-z]\\.[^a-z].*op" 

# Search for any operator declarations with precedence 100
rg "op\(100,"

Length of output: 3920

engine/clause.go (4)

78-80: LGTM! Good refactoring.

The new emit method effectively centralizes bytecode emission logic, reducing code duplication across the codebase.


74-74: LGTM! Consistent with refactoring.

The change properly uses the new emit method for the crucial OpExit instruction.


95-95: LGTM! Consistent refactoring throughout.

The changes systematically replace direct bytecode appends with the new emit method across all compilation methods. The refactoring maintains the original logic while improving code maintainability.

Also applies to: 114-114, 117-117, 123-123, 133-133, 135-135, 137-141, 144-149, 151-155, 157-157, 164-164, 166-166, 168-172, 185-191, 193-197, 199-199


173-178: Add test coverage for Dict compilation.

While the Dict handling implementation looks correct, it currently lacks test coverage. Additionally, we should verify:

  1. Dict.Arity() returns the correct number of key-value pairs
  2. Dict.Arg(i) returns key-value pairs in sorted order by key (as specified in PR objectives)

Let's verify the Dict interface implementation:

✅ Verification successful

Let me gather more information about the Dict implementation and tests.


Let me check one more thing to understand how the Dict implementation maintains order.


Let me check one final thing about how the args are processed to ensure key ordering.


Dict implementation correctly handles arity and key ordering

The implementation is verified to be correct:

  • Dict.Arity() returns the correct number of key-value pairs through the underlying compound implementation
  • Dict.Arg(i) returns key-value pairs in sorted order by key, enforced by the processArgs function which:
    • Validates dictionary structure
    • Detects duplicate keys
    • Explicitly sorts keys using sort.Slice
    • Reconstructs args array with tag followed by sorted key-value pairs

The original review comment's concerns have been addressed by the implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check Dict interface implementation for arity and sorted key requirements

# Search for Dict interface/struct definition
echo "=== Dict Definition ==="
rg -A 10 "type Dict interface" || rg -A 10 "type Dict struct"

# Search for Dict.Arity implementation
echo -e "\n=== Dict.Arity Implementation ==="
ast-grep --pattern 'func ($d Dict) Arity() $_'

# Search for Dict.Arg implementation
echo -e "\n=== Dict.Arg Implementation ==="
ast-grep --pattern 'func ($d Dict) Arg($_) $_'

# Search for Dict-related tests
echo -e "\n=== Dict Tests ==="
rg -l "func Test.*Dict" 

Length of output: 762


Script:

#!/bin/bash
# Search for Dict struct implementations
echo "=== Dict Implementations ==="
rg -A 10 "type \w+Dict struct"

# Search for Arity() implementations in Dict-related files
echo -e "\n=== Arity Implementations ==="
rg -A 5 "func.*Arity\(\)"

# Search for Arg implementations in Dict-related files
echo -e "\n=== Arg Implementations ==="
rg -A 5 "func.*Arg\("

# Look at Dict-related tests
echo -e "\n=== Dict Test Content ==="
rg -A 10 "Test.*Dict" interpreter_test.go

Length of output: 6426


Script:

#!/bin/bash
# Look for Dict creation and implementation details
echo "=== Dict Creation and Implementation ==="
rg -A 20 "func NewDict" engine/dict.go

# Look at the full Dict test content
echo -e "\n=== Complete Dict Test Content ==="
cat interpreter_test.go | rg -A 50 "^func TestDict"

# Look for dict struct implementation
echo -e "\n=== Dict Struct Implementation ==="
rg -B 5 -A 15 "type dict struct" engine/dict.go

Length of output: 1909


Script:

#!/bin/bash
# Look for processArgs implementation
echo "=== processArgs Implementation ==="
rg -A 30 "func processArgs" engine/dict.go

# Look for any sorting logic in dict.go
echo -e "\n=== Sorting Logic ==="
rg -B 5 -A 10 "sort\." engine/dict.go

Length of output: 1216

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 173-178: engine/clause.go#L173-L178
Added lines #L173 - L178 were not covered by tests

interpreter.go (2)

68-72: Verify operator precedence and associativity

The registration of the . operator and dict predicates looks correct. However, we should verify that the operator precedence aligns with the SWI-Prolog specifications mentioned in the PR objectives.

Let's check the operator declaration in bootstrap.pl:

#!/bin/bash
# Description: Verify operator declaration in bootstrap.pl
# Expected: Should find op/3 directive for '.' operator with correct precedence

rg --type pl "op.*\." bootstrap.pl

Consider adding documentation

The new dict-related predicates would benefit from documentation comments explaining:

  • The expected format and behavior of the . operator
  • The argument types and modes for get_dict/3 and put_dict/3
  • Examples of usage

Architectural consideration for future extensibility

The current implementation introduces core dict functionality. As mentioned in the PR objectives, future work includes support for small integer keys and predefined functions. Consider:

  1. Grouping dict-related predicates in a dedicated section with a comment header
  2. Reserving space for upcoming dict operations

Suggested structure:

+	// Dictionary operations
 	i.Register3(engine.NewAtom("."), engine.Op3)
 	i.Register3(engine.NewAtom("get_dict"), engine.GetDict3)
 	i.Register3(engine.NewAtom("put_dict"), engine.PutDict3)
+	// TODO: Add support for:
+	// - Small integer keys
+	// - Predefined dict functions
+	// - Additional dict predicates

68-72: Verify integration with existing term handling

The dict implementation needs to integrate seamlessly with existing term handling predicates. Please verify:

  1. Dict unification behavior with =/2 and unify_with_occurs_check/2
  2. Dict type testing with compound/1
  3. Dict comparison with compare/3 and sort/2

Let's check the integration points:

✅ Verification successful

Based on the search results, I can now provide a final response:

Dict implementation properly integrates with core term handling

The codebase shows proper integration of dict terms with core functionality:

  • Unification: Dicts are handled as compounds with atomDict functor, allowing standard compound term unification to work automatically
  • Type testing: Dicts implement the Compound interface and are properly handled as compound terms
  • Comparison: Dict comparison is implemented via the standard compound comparison logic through CompareCompound

Key evidence:

  • Dict type implements Compound interface and delegates core operations to compound implementation
  • Dict comparison uses CompareCompound which properly handles term ordering
  • Dict unification works through standard compound term unification since dicts are represented as compounds
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify dict integration with core predicates
# Expected: Should find implementations handling dict terms

# Check unification implementation
ast-grep --pattern 'func Unify($_, $_) {
  $$$
  case $atomDict:
    $$$
}'

# Check type testing implementation
ast-grep --pattern 'func TypeCompound($_, $_) {
  $$$
  case $atomDict:
    $$$
}'

# Check comparison implementation
ast-grep --pattern 'func Compare($_, $_) {
  $$$
  case $atomDict:
    $$$
}'

Length of output: 242


Script:

#!/bin/bash
# Let's try a different approach to find dict-related implementations

# Search for dict-related code in core files
rg -A 5 "Dict" engine/

# Look for type checking implementations
rg -A 5 "IsCompound|TypeCompound" engine/

# Look for unification implementations
rg -A 5 "Unify|unify" engine/

# Look for comparison implementations
rg -A 5 "Compare|compare" engine/

Length of output: 66973

engine/exception.go (3)

56-56: Verify impact on error messages

The changes enable new error types for dictionary operations. Let's verify the error messages are properly documented.

#!/bin/bash
# Description: Check if the new error types are documented
rg -A 2 'type error.*dict' docs/
rg -A 2 'domain error.*dict_key' docs/

Also applies to: 75-75, 116-116, 138-138


56-56: LGTM: Type validation for dictionaries

The addition of validTypeDict and its mapping to atomDict follows the established pattern and will enable proper type checking for dictionary operations.

Let's verify that the required atom is defined:

Also applies to: 75-75


116-116: LGTM: Domain validation for dictionary keys

The addition of validDomainDictKey and its mapping to atomDictKey follows the established pattern and will enable proper domain validation for dictionary keys.

Let's verify that the required atom is defined:

Also applies to: 138-138

✅ Verification successful

LGTM: Atom definition verified

The atomDictKey is properly defined in engine/atom.go as atomDictKey = NewAtom("dict_key") and is correctly mapped to validDomainDictKey in engine/exception.go. The atom is also being used appropriately for domain validation in engine/dict.go.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that atomDictKey is defined in atom.go
rg 'atomDictKey.*=.*NewAtom.*"dict_key"' engine/atom.go

Length of output: 167


Script:

#!/bin/bash
# Let's search for any atom definitions related to dict_key or dictionary keys
rg -i "atom.*dict.*key" engine/

# Also search for the specific validDomainDictKey definition
rg "validDomainDictKey" engine/

# Let's also check atom.go file content to see all atom definitions
cat engine/atom.go

Length of output: 12749

engine/atom.go (1)

31-31: LGTM! Well-structured additions for dictionary support.

The new atoms atomDict and atomDictKey are:

  • Properly placed in alphabetical order
  • Follow the existing naming conventions
  • Align with the PR's objective of implementing dictionary support as per SWI-Prolog's specifications

Also applies to: 70-70

engine/parser_test.go (1)

144-144: LGTM! Error expectation updated correctly.

The change in error expectation from rejecting { to rejecting b is consistent with the new dictionary syntax support, as empty dictionaries {} are now valid terms.

engine/vm.go (2)

80-80: LGTM: OpPutDict opcode addition follows established patterns.

The opcode is correctly added to both the constants list and string representation array, maintaining consistency with existing opcodes.

Also applies to: 100-100


320-326: ⚠️ Potential issue

Add validation and improve type safety in OpPutDict implementation.

The current implementation has several potential issues:

  1. No type assertion for the operand as Integer
  2. Missing bounds checking for the length value
  3. Unnecessary slice reallocation

Consider this safer implementation:

 case OpPutDict:
-	l := operand.(Integer)
+	l, ok := operand.(Integer)
+	if !ok {
+		return Error(typeError(validTypeInteger, operand, env))
+	}
+	if l < 0 {
+		return Error(domainError(validDomainNotLessThanZero, l, env))
+	}
 	vs := make([]Term, int(l))
 	arg = &dict{compound: compound{functor: atomDict, args: vs}}
 	args = append(args, arg)
 	astack = append(astack, args)
-	args = vs[:0]
+	args = vs

Let's verify the usage of atomDict:

engine/dict.go (1)

187-219: Review error handling in Op3 function

Ensure that all possible cases are properly handled in the Op3 function, and that appropriate errors are returned. Specifically, check the default case when resolving function:

Would you like to verify the completeness of error handling in Op3? If so, consider reviewing all possible types of function and ensuring that corresponding error messages are accurate.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 187-210: engine/dict.go#L187-L210
Added lines #L187 - L210 were not covered by tests


[warning] 212-214: engine/dict.go#L212-L214
Added lines #L212 - L214 were not covered by tests


[warning] 216-217: engine/dict.go#L216-L217
Added lines #L216 - L217 were not covered by tests

engine/parser.go (3)

31-32: Addition of subGoals field to Parser struct is appropriate.

The subGoals slice will store sub-goals during parsing, facilitating the deferred application of certain terms.


144-145: Integration of applySubGoals in Term method ensures proper sub-goal application.

By applying sub-goals after parsing a term, the parser correctly handles deferred operations introduced during parsing.


405-405: Use of desugar function enhances operator handling during parsing.

Introducing desugar allows for special processing of operators like . (dot), which is essential for the new dictionary access syntax.

engine/parser_test.go Show resolved Hide resolved
engine/dict.go Show resolved Hide resolved
engine/dict.go Outdated Show resolved Hide resolved
engine/dict.go Outdated Show resolved Hide resolved
engine/parser.go Show resolved Hide resolved
@ccamel
Copy link
Member Author

ccamel commented Nov 15, 2024

@coderabbitai pause

Copy link

coderabbitai bot commented Nov 15, 2024

✅ Actions performed

Reviews paused.

@triska
Copy link

triska commented Nov 15, 2024

To make this project useful for organizations and civil engineers that must adhere to international standards, I recommend keeping to the Prolog ISO standard. This will simplify procurement, teaching, and resolution of warranty disputes for your business, among other benefits such as alignment with WTO principles like nondiscrimination for companies and governments that adopt your solutions.

It is possible to add an infix . as a conforming extension, the following document explains how:

https://www.complang.tuwien.ac.at/ulrich/iso-prolog/SWI7_and_ISO

@ccamel ccamel force-pushed the feat/dicts branch 2 times, most recently from 88f4676 to f1b0277 Compare November 15, 2024 17:51
@ccamel
Copy link
Member Author

ccamel commented Nov 15, 2024

@coderabbitai resolve

Copy link

coderabbitai bot commented Nov 15, 2024

✅ Actions performed

Comments resolved.

@ccamel
Copy link
Member Author

ccamel commented Nov 15, 2024

@triska Oh, interesting! The project has already diverged a bit from the Prolog ISO standard because we had to adapt it for a blockchain environment. This introduced specific constraints, which led us to fork the original ichiban/prolog project and resulted in these deviations.

That said, I agree that staying as close to the standard as possible is the right approach. I’ll take a closer look at the document and aim to make an implementation that respects the standard. Thanks for sharing it!

@ccamel ccamel marked this pull request as draft November 15, 2024 21:02
@ccamel ccamel force-pushed the feat/dicts branch 2 times, most recently from b6e9bf7 to db2e349 Compare November 19, 2024 13:48
@ccamel ccamel marked this pull request as ready for review November 19, 2024 13:59
@ccamel ccamel marked this pull request as draft November 19, 2024 14:07
@ccamel ccamel force-pushed the feat/dicts branch 3 times, most recently from 8aef758 to c1ffc5a Compare November 20, 2024 13:41
@ccamel ccamel marked this pull request as ready for review November 20, 2024 13:56
@ccamel ccamel merged commit 7be6699 into main Nov 20, 2024
2 of 3 checks passed
@ccamel ccamel deleted the feat/dicts branch November 20, 2024 16:04
@coderabbitai coderabbitai bot mentioned this pull request Nov 25, 2024
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