-
Notifications
You must be signed in to change notification settings - Fork 0
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
Conversation
Note Reviews pausedUse the following commands to manage reviews:
WalkthroughThe pull request introduces several enhancements to the Prolog engine, including the addition of a new operator Changes
Possibly related PRs
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Codecov ReportAttention: Patch coverage is
@@ 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
... and 14 files with indirect coverage changes 🚨 Try these New Features:
|
There was a problem hiding this 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:
- Term I/O predicates correctly handle dictionary terms
- Term comparison predicates work with dictionary access expressions
- 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:
- Error handling: The WriteTerm error is silently ignored
- 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 forGetDict3
functionStatic analysis indicates that several lines in
GetDict3
are not covered by tests. This includes scenarios wherekeyPath
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 inWriteTerm
methodThe
WriteTerm
method handles errors when writing toio.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 testsengine/parser.go (4)
149-164
: Consider adding comments toapplySubGoals
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 thedesugar
function to explain operator transformations.Adding comments to
desugar
will help future developers understand how certain operators are transformed during parsing, particularly the handling ofatomDot
.
830-885
: Review error handling indict
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 tokeyValue
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
: Renameerror
field toerr
to avoid confusion with the built-inerror
interfaceThe field name
error
in theresult
struct may cause confusion with the built-inerror
type in Go. It's a common practice to useerr
for variables or fields of typeerror
to improve code clarity.Apply this diff to rename the field:
type result struct { solutions map[string]TermString - error error + err error }
1091-1101
: Useassert.ErrorIs
orassert.ErrorContains
instead ofassert.EqualError
for error comparisonsComparing errors using
assert.EqualError
with exact error messages can make tests fragile if the error messages change. Consider usingassert.ErrorIs
to compare error types orassert.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:
- Dict.Arity() returns the correct number of key-value pairs
- 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
andput_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:
- Grouping dict-related predicates in a dedicated section with a comment header
- 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:
- Dict unification behavior with
=/2
andunify_with_occurs_check/2
- Dict type testing with
compound/1
- Dict comparison with
compare/3
andsort/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
:
Add validation and improve type safety in OpPutDict implementation.
The current implementation has several potential issues:
- No type assertion for the operand as Integer
- Missing bounds checking for the length value
- 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.
@coderabbitai pause |
✅ Actions performedReviews paused. |
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 https://www.complang.tuwien.ac.at/ulrich/iso-prolog/SWI7_and_ISO |
88f4676
to
f1b0277
Compare
@coderabbitai resolve |
✅ Actions performedComments resolved. |
@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! |
b6e9bf7
to
db2e349
Compare
8aef758
to
c1ffc5a
Compare
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.
Implementation strategy
Data structure
Dicts are currently represented as a compound term (
Compound
) using the functordict
.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:
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 theop/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:
is translated into:
with the generated bytecode:
Implemented features
This PR implements the following features for Dicts:
get(?KeyPath)
function (t{a:x}.get(a)
,t{a:t{b:x}}.get(a/b)
).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
Future Work
Planned improvements include:
S = point{6:1, x:12}
).get(?KeyPath, +Default)
put(+KeyPath, +Value)
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