// readTerm returns true if it was able to read a term or if there was an // error reading a term (the error is in a term.Error value). If the stream // is empty, it returns false. func (r *TermReader) readTerm(p priority, i *lex.List, o **lex.List, t *term.Term) bool { // fmt.Printf("\nreading term\n") if r.tok(lex.EOF, i, o) { // fmt.Printf("hit EOF\n") return false } if r.term(p, i, o, t) { if r.tok(lex.FullStop, *o, o) { return true } else { msg := fmt.Sprintf("expected full stop after `%s` but got `%s`", *t, (*o).Value.Content) *t = term.NewError(msg, (*o).Value) return true } } msg := fmt.Sprintf("expected term but got `%s`", i.Value.Content) *t = term.NewError(msg, i.Value) return false }
// parse a single term func (r *TermReader) term(p priority, i *lex.List, o **lex.List, t *term.Term) bool { var op, f string var t0, t1 term.Term var opP, argP priority // fmt.Printf("seeking term with %s\n", i.Value.Content) // prefix operator if r.prefix(&op, &opP, &argP, i, o) && opP <= p && r.term(argP, *o, o, &t0) { opT := term.NewCallable(op, t0) return r.restTerm(opP, p, *o, o, opT, t) } // list notation for compound terms §6.3.5 if r.tok('[', i, o) && r.term(999, *o, o, &t0) && r.listItems(*o, o, &t1) { list := term.NewCallable(".", t0, t1) return r.restTerm(0, p, *o, o, list, t) } if r.tok('[', i, o) && r.tok(']', *o, o) { list := term.NewAtom("[]") return r.restTerm(0, p, *o, o, list, t) } // parenthesized terms if r.tok('(', i, o) && r.term(1200, *o, o, &t0) && r.tok(')', *o, o) { // fmt.Printf("open paren %s close paren\n", t0) return r.restTerm(0, p, *o, o, t0, t) } switch i.Value.Type { case lex.Int: // integer term §6.3.1.1 n := term.NewInt(i.Value.Content) *o = i.Next() return r.restTerm(0, p, *o, o, n, t) case lex.Float: // float term §6.3.1.1 f := term.NewFloat(i.Value.Content) *o = i.Next() return r.restTerm(0, p, *o, o, f, t) case lex.Atom: // atom term §6.3.1.3 a := term.NewAtomFromLexeme(i.Value.Content) *o = i.Next() return r.restTerm(0, p, *o, o, a, t) case lex.String: // double quated string §6.3.7 cl := term.NewCodeListFromDoubleQuotedString(i.Value.Content) *o = i.Next() return r.restTerm(0, p, *o, o, cl, t) case lex.Variable: // variable term §6.3.2 v := term.NewVar(i.Value.Content) *o = i.Next() return r.restTerm(0, p, *o, o, v, t) case lex.Void: // variable term §6.3.2 v := term.NewVar("_") *o = i.Next() return r.restTerm(0, p, *o, o, v, t) case lex.Comment: *o = i.Next() // skip the comment return r.term(p, *o, o, t) // ... and try again } // compound term - functional notation §6.3.3 if r.functor(i, o, &f) && r.tok('(', *o, o) { var args []term.Term var arg term.Term for r.term(999, *o, o, &arg) { // 999 priority per §6.3.3.1 args = append(args, arg) if r.tok(')', *o, o) { break } if r.tok(',', *o, o) { continue } panic("Unexpected content inside compound term arguments") } f := term.NewTermFromLexeme(f, args...) return r.restTerm(0, p, *o, o, f, t) } *t = term.NewError("Syntax error", i.Value) return false }