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

overhaul write_term/3 #228

Merged
merged 7 commits into from
Jul 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cmd/1pl/interpreter.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/ichiban/prolog/engine"
)

// New creates a prolog.Interpreter with some helper predicates.
func New(r io.Reader, w io.Writer) *prolog.Interpreter {
i := prolog.New(r, w)
i.Register2("call_nth", i.CallNth)
Expand Down
4 changes: 2 additions & 2 deletions cmd/1pl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ Type Ctrl-C or 'halt.' to exit.
func goal(i *prolog.Interpreter, pi engine.ProcedureIndicator, args []engine.Term, env *engine.Env) string {
goal, _ := pi.Apply(args...)
var buf bytes.Buffer
_ = i.Write(&buf, goal, env, engine.WithQuoted(true))
_ = goal.WriteTerm(&buf, &engine.WriteOptions{Quoted: true}, env)
return buf.String()
}

Expand Down Expand Up @@ -158,7 +158,7 @@ func handleLine(ctx context.Context, buf *strings.Builder, p *prolog.Interpreter
for i, v := range vars {
var sb strings.Builder
_, _ = fmt.Fprintf(&sb, "%s = ", v)
if err := p.Write(&sb, m[v], nil, engine.WithQuoted(true)); err != nil {
if err := p.Write(&sb, m[v], &engine.WriteOptions{Quoted: true}, nil); err != nil {
return err
}
ls[i] = sb.String()
Expand Down
56 changes: 31 additions & 25 deletions engine/atom.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package engine

import (
"bufio"
"bytes"
"fmt"
"io"
"regexp"
"strings"
)

var (
unquotedAtomPattern = regexp.MustCompile(`\A[a-z]\w*\z`)
graphicalAtomPattern = regexp.MustCompile(`\A[#$&*+\-./:<=>?@^~\\]+\z`)
quotedAtomEscapePattern = regexp.MustCompile("[[:cntrl:]]|\\\\|'|\"|`")
)
Expand Down Expand Up @@ -39,33 +41,37 @@ func (a Atom) Apply(args ...Term) Term {
}
}

// Unparse emits tokens that represent the atom.
func (a Atom) Unparse(emit func(Token), _ *Env, opts ...WriteOption) {
wto := defaultWriteOptions
for _, o := range opts {
o(&wto)
// WriteTerm writes the Atom to the io.Writer.
func (a Atom) WriteTerm(w io.Writer, opts *WriteOptions, _ *Env) error {
ew := errWriter{w: w}
var openClose bool
if opts.before != (operator{}) || opts.after != (operator{}) {
for _, op := range opts.ops {
if op.name == a {
openClose = true
break
}
}
}

switch {
case a == ",":
emit(Token{Kind: TokenComma, Val: ","})
case a == "[]":
emit(Token{Kind: TokenOpenList, Val: "["})
emit(Token{Kind: TokenCloseList, Val: "]"})
case a == "{}":
emit(Token{Kind: TokenOpenCurly, Val: "{"})
emit(Token{Kind: TokenCloseCurly, Val: "}"})
case a == ";":
emit(Token{Kind: TokenSemicolon, Val: string(a)})
case a == "!":
emit(Token{Kind: TokenCut, Val: string(a)})
case graphicalAtomPattern.MatchString(string(a)):
emit(Token{Kind: TokenGraphic, Val: string(a)})
case wto.quoted && !unquotedAtomPattern.MatchString(string(a)):
emit(Token{Kind: TokenQuoted, Val: quote(string(a))})
default:
emit(Token{Kind: TokenLetterDigit, Val: string(a)})
if openClose {
_, _ = fmt.Fprint(&ew, "(")
}

s := string(a)
if opts.Quoted {
p := newParser(bufio.NewReader(bytes.NewBufferString(string(a))))
if a, err := p.atom(); err != nil || string(a) != s {
s = quote(s)
}
}
_, _ = fmt.Fprint(&ew, s)

if openClose {
_, _ = fmt.Fprint(&ew, ")")
}

return ew.err
}

// Compare compares the atom to another term.
Expand Down
116 changes: 41 additions & 75 deletions engine/atom_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package engine

import (
"bytes"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -60,82 +61,47 @@ func TestAtom_Unify(t *testing.T) {
})
}

func TestAtom_Unparse(t *testing.T) {
t.Run("not quoted", func(t *testing.T) {
t.Run("no need to quote", func(t *testing.T) {
var tokens []Token
Atom("a").Unparse(func(token Token) {
tokens = append(tokens, token)
}, nil, WithQuoted(false))
assert.Equal(t, []Token{
{Kind: TokenLetterDigit, Val: `a`},
}, tokens)
func TestAtom_WriteTerm(t *testing.T) {
ops := operators{
{name: "+"},
{name: "-"},
}

tests := []struct {
atom Atom
quoted bool
before, after operator
output string
}{
{atom: `a`, quoted: false, output: `a`},
{atom: `a`, quoted: true, output: `a`},
{atom: "\a\b\f\n\r\t\v\x00\\'\"`", quoted: false, output: "\a\b\f\n\r\t\v\x00\\'\"`"},
{atom: "\a\b\f\n\r\t\v\x00\\'\"`", quoted: true, output: "'\\a\\b\\f\\n\\r\\t\\v\\x0\\\\\\\\'\\\"\\`'"},
{atom: `,`, quoted: false, output: `,`},
{atom: `,`, quoted: true, output: `','`},
{atom: `[]`, quoted: false, output: `[]`},
{atom: `[]`, quoted: true, output: `[]`},
{atom: `{}`, quoted: false, output: `{}`},
{atom: `{}`, quoted: true, output: `{}`},

{atom: `-`, output: `-`},
{atom: `-`, before: operator{name: "+"}, output: `(-)`},
{atom: `-`, after: operator{name: "+"}, output: `(-)`},
}

var buf bytes.Buffer
for _, tt := range tests {
t.Run(string(tt.atom), func(t *testing.T) {
buf.Reset()
assert.NoError(t, tt.atom.WriteTerm(&buf, &WriteOptions{
Quoted: tt.quoted,
ops: ops,
before: tt.before,
after: tt.after,
}, nil))
assert.Equal(t, tt.output, buf.String())
})

t.Run("need to quote", func(t *testing.T) {
var tokens []Token
Atom("\a\b\f\n\r\t\v\x00\\'\"`").Unparse(func(token Token) {
tokens = append(tokens, token)
}, nil, WithQuoted(false))
assert.Equal(t, []Token{
{Kind: TokenLetterDigit, Val: "\a\b\f\n\r\t\v\x00\\'\"`"},
}, tokens)
})
})

t.Run("quoted", func(t *testing.T) {
t.Run("no need to quote", func(t *testing.T) {
var tokens []Token
Atom("a").Unparse(func(token Token) {
tokens = append(tokens, token)
}, nil, WithQuoted(true))
assert.Equal(t, []Token{
{Kind: TokenLetterDigit, Val: `a`},
}, tokens)
})

t.Run("need to quote", func(t *testing.T) {
var tokens []Token
Atom("\a\b\f\n\r\t\v\x00\\'\"`").Unparse(func(token Token) {
tokens = append(tokens, token)
}, nil, WithQuoted(true))
assert.Equal(t, []Token{
{Kind: TokenQuoted, Val: "'\\a\\b\\f\\n\\r\\t\\v\\x0\\\\\\\\'\\\"\\`'"},
}, tokens)
})
})

t.Run("comma", func(t *testing.T) {
var tokens []Token
Atom(",").Unparse(func(token Token) {
tokens = append(tokens, token)
}, nil, WithQuoted(true))
assert.Equal(t, []Token{
{Kind: TokenComma, Val: ","},
}, tokens)
})

t.Run("nil", func(t *testing.T) {
var tokens []Token
Atom("[]").Unparse(func(token Token) {
tokens = append(tokens, token)
}, nil, WithQuoted(true))
assert.Equal(t, []Token{
{Kind: TokenOpenList, Val: "["},
{Kind: TokenCloseList, Val: "]"},
}, tokens)
})

t.Run("empty curlyBracketedTerm", func(t *testing.T) {
var tokens []Token
Atom("{}").Unparse(func(token Token) {
tokens = append(tokens, token)
}, nil, WithQuoted(true))
assert.Equal(t, []Token{
{Kind: TokenOpenCurly, Val: "{"},
{Kind: TokenCloseCurly, Val: "}"},
}, tokens)
})
}
}

func TestAtom_Compare(t *testing.T) {
Expand Down
Loading