Skip to content

Commit

Permalink
don't panic, support swi dicts
Browse files Browse the repository at this point in the history
  • Loading branch information
guregu committed Jul 11, 2022
1 parent 00c2802 commit 697c9d2
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 9 deletions.
1 change: 1 addition & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ func (c Client) create(ctx context.Context, query string, destroy bool) (*Engine
if query != "" {
opts.Ask = query
}
opts.Destroy = destroy

evt, err := eng.post(ctx, "create", opts)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion prolog.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func (p *prologAnswers) handle(ctx context.Context, a string) error {
parser := defaultInterpreter.Parser(strings.NewReader(a), nil)
t, err := parser.Term()
if err != nil {
panic(err)
return fmt.Errorf("pengines: failed to parse response: %w", err)
}

event, ok := t.(*engine.Compound)
Expand Down
5 changes: 5 additions & 0 deletions send.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ func (e *Engine) post(ctx context.Context, action string, body any) (answer, err
}
defer resp.Body.Close()

// if e.debug {
// rrr, _ := httputil.DumpResponse(resp, true)
// fmt.Println("GOT: ", string(rrr))
// }

if resp.StatusCode != http.StatusOK {
return v, fmt.Errorf("bad status: %d", resp.StatusCode)
}
Expand Down
31 changes: 23 additions & 8 deletions term.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,14 @@ type Solution map[string]Term
// One of the fields should be "truthy".
// This can be handy for parsing query results in JSON format.
type Term struct {
Atom *string
Number *json.Number
Compound *Compound
Variable *string
Boolean *bool
List []Term
Null bool
Atom *string
Number *json.Number
Compound *Compound
Variable *string
Boolean *bool
List []Term
Dictionary map[string]Term
Null bool
}

// UnmarshalJSON implements json.Unmarshaler.
Expand Down Expand Up @@ -62,7 +63,21 @@ func (t *Term) UnmarshalJSON(b []byte) error {
case []any:
return json.Unmarshal(b, &t.List)
case map[string]any:
return json.Unmarshal(b, &t.Compound)
if _, ok := x["functor"]; ok {
return json.Unmarshal(b, &t.Compound)
}
rawDict := make(map[string]json.RawMessage, len(x))
if err := json.Unmarshal(b, &rawDict); err != nil {
return err
}
t.Dictionary = make(map[string]Term, len(rawDict))
for k, raw := range rawDict {
var v Term
if err := json.Unmarshal(raw, &v); err != nil {
return err
}
t.Dictionary[k] = v
}
case nil:
t.Null = true
default:
Expand Down

0 comments on commit 697c9d2

Please sign in to comment.