engine

package
v0.5.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 14, 2021 License: MIT Imports: 16 Imported by: 39

Documentation

Index

Constants

View Source
const (
	// StreamModeRead means you can read from the stream.
	StreamModeRead = StreamMode(os.O_RDONLY)
	// StreamModeWrite means you can write to the stream.
	StreamModeWrite = StreamMode(os.O_CREATE | os.O_WRONLY)
	// StreamModeAppend means you can append to the stream.
	StreamModeAppend = StreamMode(os.O_APPEND) | StreamModeWrite
)

Variables

View Source
var DefaultFunctionSet = FunctionSet{
	Unary: map[Atom]func(Term, *Env) (Term, error){
		"-":        unaryNumber(func(i int64) int64 { return -1 * i }, func(n float64) float64 { return -1 * n }),
		"abs":      unaryFloat(math.Abs),
		"atan":     unaryFloat(math.Atan),
		"ceiling":  unaryFloat(math.Ceil),
		"cos":      unaryFloat(math.Cos),
		"exp":      unaryFloat(math.Exp),
		"sqrt":     unaryFloat(math.Sqrt),
		"sign":     unaryNumber(sgn, sgnf),
		"float":    unaryFloat(func(n float64) float64 { return n }),
		"floor":    unaryFloat(math.Floor),
		"log":      unaryFloat(math.Log),
		"sin":      unaryFloat(math.Sin),
		"truncate": unaryFloat(math.Trunc),
		"round":    unaryFloat(math.Round),
		"\\":       unaryInteger(func(i int64) int64 { return ^i }),
	},
	Binary: map[Atom]func(Term, Term, *Env) (Term, error){
		"+":   binaryNumber(func(i, j int64) int64 { return i + j }, func(n, m float64) float64 { return n + m }),
		"-":   binaryNumber(func(i, j int64) int64 { return i - j }, func(n, m float64) float64 { return n - m }),
		"*":   binaryNumber(func(i, j int64) int64 { return i * j }, func(n, m float64) float64 { return n * m }),
		"/":   binaryFloat(func(n float64, m float64) float64 { return n / m }),
		"//":  binaryInteger(func(i, j int64) int64 { return i / j }),
		"rem": binaryInteger(func(i, j int64) int64 { return i % j }),
		"mod": binaryInteger(func(i, j int64) int64 { return (i%j + j) % j }),
		"**":  binaryFloat(math.Pow),
		">>":  binaryInteger(func(i, j int64) int64 { return i >> j }),
		"<<":  binaryInteger(func(i, j int64) int64 { return i << j }),
		"/\\": binaryInteger(func(i, j int64) int64 { return i & j }),
		"\\/": binaryInteger(func(i, j int64) int64 { return i | j }),
	},
}

DefaultFunctionSet is a FunctionSet with builtin functions.

View Source
var ErrInsufficient = errors.New("insufficient input")

ErrInsufficient represents an error which is raised when the given input is insufficient for a term.

View Source
var ErrNotANumber = errors.New("not a number")

Functions

func Contains added in v0.4.1

func Contains(t, s Term, env *Env) bool

Contains checks if t contains s.

func Each

func Each(any Term, f func(elem Term) error, env *Env) error

func EachList added in v0.4.1

func EachList(list Term, f func(elem Term) error, env *Env) error

EachList iterates over list.

func EachSeq added in v0.4.1

func EachSeq(seq Term, sep Atom, f func(elem Term) error, env *Env) error

EachSeq iterates over a sequence seq separated by sep.

func Write added in v0.4.1

func Write(w io.Writer, t Term, opts WriteTermOptions, env *Env) error

Write outputs one of the external representations of the term.

Types

type Atom added in v0.4.1

type Atom string

Atom is a prolog atom.

func (Atom) Apply added in v0.4.1

func (a Atom) Apply(args ...Term) Term

Apply returns a Compound which Functor is the Atom and Args are the arguments. If the arguments are empty, then returns itself.

func (Atom) String added in v0.4.1

func (a Atom) String() string

func (Atom) Unify added in v0.4.1

func (a Atom) Unify(t Term, occursCheck bool, env *Env) (*Env, bool)

Unify unifies the atom with t.

func (Atom) Unparse added in v0.4.1

func (a Atom) Unparse(emit func(Token), opts WriteTermOptions, _ *Env)

Unparse emits tokens that represent the atom.

type Compound added in v0.4.1

type Compound struct {
	Functor Atom
	Args    []Term
}

Compound is a prolog compound.

func (*Compound) String added in v0.4.1

func (c *Compound) String() string

func (*Compound) Unify added in v0.4.1

func (c *Compound) Unify(t Term, occursCheck bool, env *Env) (*Env, bool)

Unify unifies the compound with t.

func (*Compound) Unparse added in v0.4.1

func (c *Compound) Unparse(emit func(Token), opts WriteTermOptions, env *Env)

Unparse emits tokens that represent the compound.

type DoubleQuotes added in v0.4.1

type DoubleQuotes int
const (
	DoubleQuotesCodes DoubleQuotes = iota
	DoubleQuotesChars
	DoubleQuotesAtom
)

func (DoubleQuotes) String added in v0.4.1

func (d DoubleQuotes) String() string

type EOFAction added in v0.4.1

type EOFAction int

EOFAction describes what happens when you reached to the end of the stream.

const (
	// EOFActionEOFCode means either an atom `end_of_file`, or an integer `-1` will be returned.
	EOFActionEOFCode EOFAction = iota
	// EOFActionError means an error will be raised.
	EOFActionError
	// EOFActionReset means another attempt will be made.
	EOFActionReset
)

type Env added in v0.4.1

type Env struct {
	// contains filtered or unexported fields
}

Env is a mapping from variables to terms.

func NewEnv added in v0.4.1

func NewEnv() *Env

NewEnv creates an empty environment.

func (*Env) Bind added in v0.4.1

func (e *Env) Bind(k Variable, v Term) *Env

Bind adds a new entry to the environment.

func (*Env) FreeVariables added in v0.4.1

func (e *Env) FreeVariables(ts ...Term) Variables

FreeVariables extracts variables in the given terms.

func (*Env) Lookup added in v0.4.1

func (e *Env) Lookup(k Variable) (Term, bool)

Lookup returns a term that the given variable is bound to.

func (*Env) Resolve added in v0.4.1

func (e *Env) Resolve(t Term) Term

Resolve follows the variable chain and returns the first non-variable term or the last free variable.

func (*Env) Simplify added in v0.4.1

func (e *Env) Simplify(t Term) Term

Simplify trys to remove as many variables as possible from term t.

type Exception

type Exception struct {
	Term Term
}

Exception is an error represented by a prolog term.

func DomainError added in v0.4.0

func DomainError(validDomain Atom, culprit Term, format string, args ...interface{}) *Exception

DomainError creates a new domain error exception.

func ExistenceError added in v0.4.0

func ExistenceError(objectType Atom, culprit Term, format string, args ...interface{}) *Exception

ExistenceError creates a new existence error exception.

func InstantiationError added in v0.4.0

func InstantiationError(culprit Term) *Exception

InstantiationError creates a new instantiation error excdption.

func PermissionError added in v0.4.0

func PermissionError(operation, permissionType Atom, culprit Term, format string, args ...interface{}) *Exception

PermissionError creates a new permission error exception.

func SystemError added in v0.4.0

func SystemError(err error) *Exception

func TypeError added in v0.4.0

func TypeError(validType Atom, culprit Term, format string, args ...interface{}) *Exception

TypeError creates a new type error exception.

func (*Exception) Error

func (e *Exception) Error() string

type Float added in v0.4.1

type Float float64

Float is a prolog floating-point number.

func (Float) String added in v0.4.1

func (f Float) String() string

func (Float) Unify added in v0.4.1

func (f Float) Unify(t Term, occursCheck bool, env *Env) (*Env, bool)

Unify unifies the float with t.

func (Float) Unparse added in v0.4.1

func (f Float) Unparse(emit func(Token), _ WriteTermOptions, _ *Env)

Unparse emits tokens that represent the float.

type FunctionSet

type FunctionSet struct {
	Unary  map[Atom]func(x Term, env *Env) (Term, error)
	Binary map[Atom]func(x, y Term, env *Env) (Term, error)
}

FunctionSet is a set of unary/binary functions.

func (FunctionSet) Equal

func (fs FunctionSet) Equal(lhs, rhs Term, k func(*Env) *Promise, env *Env) *Promise

Equal succeeds iff lhs equals to rhs.

func (FunctionSet) GreaterThan

func (fs FunctionSet) GreaterThan(lhs, rhs Term, k func(*Env) *Promise, env *Env) *Promise

GreaterThan succeeds iff lhs is greater than rhs.

func (FunctionSet) GreaterThanOrEqual

func (fs FunctionSet) GreaterThanOrEqual(lhs, rhs Term, k func(*Env) *Promise, env *Env) *Promise

GreaterThanOrEqual succeeds iff lhs is greater than or equal to rhs.

func (FunctionSet) Is

func (fs FunctionSet) Is(result, expression Term, k func(*Env) *Promise, env *Env) *Promise

Is evaluates expression and unifies the result with result.

func (FunctionSet) LessThan

func (fs FunctionSet) LessThan(lhs, rhs Term, k func(*Env) *Promise, env *Env) *Promise

LessThan succeeds iff lhs is less than rhs.

func (FunctionSet) LessThanOrEqual

func (fs FunctionSet) LessThanOrEqual(lhs, rhs Term, k func(*Env) *Promise, env *Env) *Promise

LessThanOrEqual succeeds iff lhs is less than or equal to rhs.

func (FunctionSet) NotEqual

func (fs FunctionSet) NotEqual(lhs, rhs Term, k func(*Env) *Promise, env *Env) *Promise

NotEqual succeeds iff lhs doesn't equal to rhs.

type Integer added in v0.4.1

type Integer int64

Integer is a prolog integer.

func (Integer) String added in v0.4.1

func (i Integer) String() string

func (Integer) Unify added in v0.4.1

func (i Integer) Unify(t Term, occursCheck bool, env *Env) (*Env, bool)

Unify unifies the integer with t.

func (Integer) Unparse added in v0.4.1

func (i Integer) Unparse(emit func(token Token), _ WriteTermOptions, _ *Env)

Unparse emits tokens that represent the integer.

func (Integer) WriteTerm added in v0.4.1

func (i Integer) WriteTerm(w io.Writer, _ WriteTermOptions, _ *Env) error

WriteTerm writes the integer into w.

type Lexer added in v0.4.1

type Lexer struct {
	// contains filtered or unexported fields
}

Lexer turns bytes into tokens.

func NewLexer added in v0.4.1

func NewLexer(input *bufio.Reader, charConversions map[rune]rune) *Lexer

NewLexer create a lexer with an input and char conversions.

func (*Lexer) Next added in v0.4.1

func (l *Lexer) Next() (Token, error)

Next returns the next token.

type Operator added in v0.4.1

type Operator struct {
	Priority  Integer // 1 ~ 1200
	Specifier OperatorSpecifier
	Name      Atom
}

Operator is an operator definition.

type OperatorSpecifier added in v0.4.1

type OperatorSpecifier uint8
const (
	OperatorSpecifierNone OperatorSpecifier = iota
	OperatorSpecifierFX
	OperatorSpecifierFY
	OperatorSpecifierXF
	OperatorSpecifierYF
	OperatorSpecifierXFX
	OperatorSpecifierXFY
	OperatorSpecifierYFX
)

func (OperatorSpecifier) Term added in v0.4.1

func (s OperatorSpecifier) Term() Term

type Operators added in v0.4.1

type Operators []Operator

Operators are a list of operators sorted in a descending order of precedence.

type ParsedVariable added in v0.4.1

type ParsedVariable struct {
	Name     Atom
	Variable Variable
	Count    int
}

ParsedVariable is a set of information regarding a variable in a parsed term.

type Parser added in v0.4.1

type Parser struct {
	// contains filtered or unexported fields
}

Parser turns bytes into Term.

func NewParser added in v0.4.1

func NewParser(input *bufio.Reader, charConversions map[rune]rune, opts ...ParserOption) *Parser

NewParser creates a Parser.

func (*Parser) More added in v0.4.1

func (p *Parser) More() bool

More checks if the parser has more tokens to read.

func (*Parser) Number added in v0.4.1

func (p *Parser) Number() (Term, error)

Number parses a number term.

func (*Parser) Replace added in v0.4.1

func (p *Parser) Replace(placeholder Atom, args ...interface{}) error

Replace registers placeholder and its arguments. Every occurrence of placeholder will be replaced by arguments. Mismatch of the number of occurrences of placeholder and the number of arguments raises an error.

func (*Parser) Term added in v0.4.1

func (p *Parser) Term() (Term, error)

Term parses a term followed by a full stop.

type ParserOption added in v0.4.1

type ParserOption func(p *Parser)

ParserOption is option for NewParser.

func WithDoubleQuotes added in v0.4.1

func WithDoubleQuotes(quotes DoubleQuotes) ParserOption

WithDoubleQuotes sets how Parser handles double quotes.

func WithOperators added in v0.4.1

func WithOperators(operators *Operators) ParserOption

WithOperators sets operators for Parser.

func WithParsedVars added in v0.4.1

func WithParsedVars(vars *[]ParsedVariable) ParserOption

WithParsedVars sets where Parser to store information regarding parsed variables.

type ProcedureIndicator added in v0.3.0

type ProcedureIndicator struct {
	Name  Atom
	Arity Integer
}

ProcedureIndicator identifies procedure e.g. (=)/2.

func NewProcedureIndicator added in v0.4.1

func NewProcedureIndicator(pi Term, env *Env) (ProcedureIndicator, error)

NewProcedureIndicator creates a new ProcedureIndicator from a term that matches Name/Arity.

func (ProcedureIndicator) Apply added in v0.3.0

func (p ProcedureIndicator) Apply(args ...Term) (Term, error)

Apply applies p to args.

func (ProcedureIndicator) String added in v0.3.0

func (p ProcedureIndicator) String() string

func (ProcedureIndicator) Term added in v0.3.0

func (p ProcedureIndicator) Term() Term

Term returns p as term.

type Promise added in v0.4.1

type Promise struct {
	// contains filtered or unexported fields
}

Promise is a delayed execution that results in (bool, error). The zero value for Promise is equivalent to Bool(false).

func Arg

func Arg(nth, t, arg Term, k func(*Env) *Promise, env *Env) *Promise

Arg extracts nth argument of term as arg, or finds the argument position of arg in term as nth.

func AtomChars

func AtomChars(atom, chars Term, k func(*Env) *Promise, env *Env) *Promise

AtomChars breaks down atom into list of characters and unifies with chars, or constructs an atom from a list of characters chars and unifies it with atom.

func AtomCodes

func AtomCodes(atom, codes Term, k func(*Env) *Promise, env *Env) *Promise

AtomCodes breaks up atom into a list of runes and unifies it with codes, or constructs an atom from the list of runes and unifies it with atom.

func AtomConcat

func AtomConcat(atom1, atom2, atom3 Term, k func(*Env) *Promise, env *Env) *Promise

AtomConcat concatenates atom1 and atom2 and unifies it with atom3.

func AtomLength

func AtomLength(atom, length Term, k func(*Env) *Promise, env *Env) *Promise

AtomLength counts the runes in atom and unifies the result with length.

func Bool added in v0.4.1

func Bool(ok bool) *Promise

Bool returns a promise that simply returns (ok, nil).

func Catch added in v0.4.1

func Catch(recover func(error) *Promise, k func(context.Context) *Promise) *Promise

Catch returns a promise with a recovering function. Once a promise results in error, the error goes through ancestor promises looking for a recovering function that returns a non-nil promise to continue on.

func CharCode

func CharCode(char, code Term, k func(*Env) *Promise, env *Env) *Promise

CharCode converts a single-rune Atom char to an Integer code, or vice versa.

func Compare

func Compare(order, term1, term2 Term, k func(*Env) *Promise, env *Env) *Promise

Compare compares term1 and term2 and unifies order with <, =, or >.

func CopyTerm

func CopyTerm(in, out Term, k func(*Env) *Promise, env *Env) *Promise

CopyTerm clones in as out.

func Cut added in v0.4.1

func Cut(parent *Promise, k func(context.Context) *Promise) *Promise

Cut returns a promise that once the execution reaches it, it eliminates other possible choices.

func Delay added in v0.4.1

func Delay(k ...func(context.Context) *Promise) *Promise

Delay delays an execution of k.

func Error added in v0.4.1

func Error(err error) *Promise

Error returns a promise that simply returns (false, err).

func Failure

func Failure(_ *Env) *Promise

func Functor

func Functor(t, name, arity Term, k func(*Env) *Promise, env *Env) *Promise

Functor extracts the name and arity of term, or unifies term with an atomic/compound term of name and arity with fresh variables as arguments.

func Halt added in v0.3.0

func Halt(n Term, k func(*Env) *Promise, env *Env) *Promise

Halt exits the process with exit code of n.

func NumberChars

func NumberChars(num, chars Term, k func(*Env) *Promise, env *Env) *Promise

NumberChars breaks up an atom representation of a number num into a list of characters and unifies it with chars, or constructs a number from a list of characters chars and unifies it with num.

func NumberCodes

func NumberCodes(num, codes Term, k func(*Env) *Promise, env *Env) *Promise

NumberCodes breaks up an atom representation of a number num into a list of runes and unifies it with codes, or constructs a number from a list of runes codes and unifies it with num.

func Repeat

func Repeat(k func(context.Context) *Promise) *Promise

Repeat returns a promise that repeats k.

func SubAtom

func SubAtom(atom, before, length, after, subAtom Term, k func(*Env) *Promise, env *Env) *Promise

SubAtom unifies subAtom with a sub atom of atom of length which appears with before runes preceding it and after runes following it.

func Success

func Success(_ *Env) *Promise

func Throw

func Throw(ball Term, _ func(*Env) *Promise, env *Env) *Promise

Throw throws ball as an exception.

func TypeAtom

func TypeAtom(t Term, k func(*Env) *Promise, env *Env) *Promise

TypeAtom checks if t is an atom.

func TypeCompound

func TypeCompound(t Term, k func(*Env) *Promise, env *Env) *Promise

TypeCompound checks if t is a compound term.

func TypeFloat

func TypeFloat(t Term, k func(*Env) *Promise, env *Env) *Promise

TypeFloat checks if t is a floating-point number.

func TypeInteger

func TypeInteger(t Term, k func(*Env) *Promise, env *Env) *Promise

TypeInteger checks if t is an integer.

func TypeVar

func TypeVar(t Term, k func(*Env) *Promise, env *Env) *Promise

TypeVar checks if t is a variable.

func Unify

func Unify(t1, t2 Term, k func(*Env) *Promise, env *Env) *Promise

Unify unifies t1 and t2 without occurs check (i.e., X = f(X) is allowed).

func UnifyWithOccursCheck

func UnifyWithOccursCheck(t1, t2 Term, k func(*Env) *Promise, env *Env) *Promise

UnifyWithOccursCheck unifies t1 and t2 with occurs check (i.e., X = f(X) is not allowed).

func Univ

func Univ(t, list Term, k func(*Env) *Promise, env *Env) *Promise

Univ constructs list as a list which first element is the functor of term and the rest is the arguments of term, or construct a compound from list as term.

func (*Promise) Force added in v0.4.1

func (p *Promise) Force(ctx context.Context) (bool, error)

Force enforces the delayed execution and returns the result. (i.e. trampoline)

type State added in v0.5.0

type State struct {
	VM
	// contains filtered or unexported fields
}

State represents the internal state of an interpreter.

func (*State) Abolish added in v0.5.0

func (state *State) Abolish(pi Term, k func(*Env) *Promise, env *Env) *Promise

Abolish removes the procedure indicated by pi from the database.

func (*State) AssertStatic added in v0.5.0

func (state *State) AssertStatic(t Term, k func(*Env) *Promise, env *Env) *Promise

AssertStatic prepends t to the database.

func (*State) Asserta added in v0.5.0

func (state *State) Asserta(t Term, k func(*Env) *Promise, env *Env) *Promise

Asserta prepends t to the database.

func (*State) Assertz added in v0.5.0

func (state *State) Assertz(t Term, k func(*Env) *Promise, env *Env) *Promise

Assertz appends t to the database.

func (*State) BagOf added in v0.5.0

func (state *State) BagOf(template, goal, instances Term, k func(*Env) *Promise, env *Env) *Promise

BagOf collects all the solutions of goal as instances, which unify with template. instances may contain duplications.

func (*State) BuiltIn added in v0.5.0

func (state *State) BuiltIn(pi Term, k func(*Env) *Promise, env *Env) *Promise

BuiltIn declares a procedure indicated by pi is built-in and static.

func (*State) Call added in v0.5.0

func (state *State) Call(goal Term, k func(*Env) *Promise, env *Env) *Promise

Call executes goal. it succeeds if goal followed by k succeeds. A cut inside goal doesn't affect outside of Call.

func (*State) Catch added in v0.5.0

func (state *State) Catch(goal, catcher, recover Term, k func(*Env) *Promise, env *Env) *Promise

Catch calls goal. If an exception is thrown and unifies with catcher, it calls recover.

func (*State) CharConversion added in v0.5.0

func (state *State) CharConversion(inChar, outChar Term, k func(*Env) *Promise, env *Env) *Promise

CharConversion registers a character conversion from inChar to outChar, or remove the conversion if inChar = outChar.

func (*State) Clause added in v0.5.0

func (state *State) Clause(head, body Term, k func(*Env) *Promise, env *Env) *Promise

Clause unifies head and body with H and B respectively where H :- B is in the database.

func (*State) Close added in v0.5.0

func (state *State) Close(streamOrAlias, options Term, k func(*Env) *Promise, env *Env) *Promise

Close closes a stream specified by streamOrAlias.

func (*State) CurrentCharConversion added in v0.5.0

func (state *State) CurrentCharConversion(inChar, outChar Term, k func(*Env) *Promise, env *Env) *Promise

CurrentCharConversion succeeds iff a conversion from inChar to outChar is defined.

func (*State) CurrentInput added in v0.5.0

func (state *State) CurrentInput(stream Term, k func(*Env) *Promise, env *Env) *Promise

CurrentInput unifies stream with the current input stream.

func (*State) CurrentOp added in v0.5.0

func (state *State) CurrentOp(priority, specifier, operator Term, k func(*Env) *Promise, env *Env) *Promise

CurrentOp succeeds if operator is defined with priority and specifier.

func (*State) CurrentOutput added in v0.5.0

func (state *State) CurrentOutput(stream Term, k func(*Env) *Promise, env *Env) *Promise

CurrentOutput unifies stream with the current output stream.

func (*State) CurrentPredicate added in v0.5.0

func (state *State) CurrentPredicate(pi Term, k func(*Env) *Promise, env *Env) *Promise

CurrentPredicate matches pi with a predicate indicator of the user-defined procedures in the database.

func (*State) CurrentPrologFlag added in v0.5.0

func (state *State) CurrentPrologFlag(flag, value Term, k func(*Env) *Promise, env *Env) *Promise

CurrentPrologFlag succeeds iff flag is set to value.

func (*State) Dynamic added in v0.5.0

func (state *State) Dynamic(pi Term, k func(*Env) *Promise, env *Env) *Promise

Dynamic declares a procedure indicated by pi is user-defined dynamic.

func (*State) ExpandTerm added in v0.5.0

func (state *State) ExpandTerm(term1, term2 Term, k func(*Env) *Promise, env *Env) *Promise

ExpandTerm transforms term1 according to term_expansion/2 and unifies with term2.

func (*State) FindAll added in v0.5.0

func (state *State) FindAll(template, goal, instances Term, k func(*Env) *Promise, env *Env) *Promise

FindAll collects all the solutions of goal as instances, which unify with template. instances may contain duplications.

func (*State) FlushOutput added in v0.5.0

func (state *State) FlushOutput(streamOrAlias Term, k func(*Env) *Promise, env *Env) *Promise

FlushOutput sends any buffered output to the stream.

func (*State) GetByte added in v0.5.0

func (state *State) GetByte(streamOrAlias, inByte Term, k func(*Env) *Promise, env *Env) *Promise

GetByte reads a byte from the stream represented by streamOrAlias and unifies it with inByte.

func (*State) GetChar added in v0.5.0

func (state *State) GetChar(streamOrAlias, char Term, k func(*Env) *Promise, env *Env) *Promise

GetChar reads a character from the stream represented by streamOrAlias and unifies it with char.

func (*State) Negation added in v0.5.0

func (state *State) Negation(goal Term, k func(*Env) *Promise, env *Env) *Promise

func (*State) Op added in v0.5.0

func (state *State) Op(priority, specifier, operator Term, k func(*Env) *Promise, env *Env) *Promise

Op defines operator with priority and specifier, or removes when priority is 0.

func (*State) Open added in v0.5.0

func (state *State) Open(SourceSink, mode, stream, options Term, k func(*Env) *Promise, env *Env) *Promise

Open opens SourceSink in mode and unifies with stream.

func (*State) Parser added in v0.5.0

func (state *State) Parser(r io.Reader, vars *[]ParsedVariable) *Parser

func (*State) PeekByte added in v0.5.0

func (state *State) PeekByte(streamOrAlias, inByte Term, k func(*Env) *Promise, env *Env) *Promise

PeekByte peeks a byte from the stream represented by streamOrAlias and unifies it with inByte.

func (*State) PeekChar added in v0.5.0

func (state *State) PeekChar(streamOrAlias, char Term, k func(*Env) *Promise, env *Env) *Promise

PeekChar peeks a rune from the stream represented by streamOrAlias and unifies it with char.

func (*State) PutByte added in v0.5.0

func (state *State) PutByte(streamOrAlias, byt Term, k func(*Env) *Promise, env *Env) *Promise

PutByte outputs an integer byte to a stream represented by streamOrAlias.

func (*State) PutCode added in v0.5.0

func (state *State) PutCode(streamOrAlias, code Term, k func(*Env) *Promise, env *Env) *Promise

PutCode outputs code to the stream represented by streamOrAlias.

func (*State) ReadTerm added in v0.5.0

func (state *State) ReadTerm(streamOrAlias, out, options Term, k func(*Env) *Promise, env *Env) *Promise

ReadTerm reads from the stream represented by streamOrAlias and unifies with stream.

func (*State) Repeat added in v0.5.0

func (state *State) Repeat(k func(*Env) *Promise, env *Env) *Promise

func (*State) Retract added in v0.5.0

func (state *State) Retract(t Term, k func(*Env) *Promise, env *Env) *Promise

Retract removes the first clause that matches with t.

func (*State) SetInput added in v0.5.0

func (state *State) SetInput(streamOrAlias Term, k func(*Env) *Promise, env *Env) *Promise

SetInput sets streamOrAlias as the current input stream.

func (*State) SetOf added in v0.5.0

func (state *State) SetOf(template, goal, instances Term, k func(*Env) *Promise, env *Env) *Promise

SetOf collects all the solutions of goal as instances, which unify with template. instances don't contain duplications.

func (*State) SetOutput added in v0.5.0

func (state *State) SetOutput(streamOrAlias Term, k func(*Env) *Promise, env *Env) *Promise

SetOutput sets streamOrAlias as the current output stream.

func (*State) SetPrologFlag added in v0.5.0

func (state *State) SetPrologFlag(flag, value Term, k func(*Env) *Promise, env *Env) *Promise

SetPrologFlag sets flag to value.

func (*State) SetStreamPosition added in v0.5.0

func (state *State) SetStreamPosition(streamOrAlias, position Term, k func(*Env) *Promise, env *Env) *Promise

SetStreamPosition sets the position property of the stream represented by streamOrAlias.

func (*State) SetUserInput added in v0.5.0

func (state *State) SetUserInput(r io.Reader, opts ...StreamOption)

SetUserInput sets the given reader as a stream with an alias of user_input.

func (*State) SetUserOutput added in v0.5.0

func (state *State) SetUserOutput(w io.Writer, opts ...StreamOption)

SetUserOutput sets the given writer as a stream with an alias of user_output.

func (*State) StreamProperty added in v0.5.0

func (state *State) StreamProperty(streamOrAlias, property Term, k func(*Env) *Promise, env *Env) *Promise

StreamProperty succeeds iff the stream represented by streamOrAlias has the stream property property.

func (*State) WriteTerm added in v0.5.0

func (state *State) WriteTerm(streamOrAlias, t, options Term, k func(*Env) *Promise, env *Env) *Promise

WriteTerm outputs term to stream with options.

type Stream added in v0.4.1

type Stream struct {
	// contains filtered or unexported fields
}

Stream is a prolog stream.

func NewStream added in v0.4.1

func NewStream(f io.ReadWriteCloser, mode StreamMode, opts ...StreamOption) *Stream

NewStream creates a new stream from an opened file.

func Open added in v0.4.1

func Open(name Atom, mode StreamMode, opts ...StreamOption) (*Stream, error)

Open opens a file and creates a new stream out of it.

func (*Stream) Close added in v0.4.1

func (s *Stream) Close() error

Close closes the underlying file of the stream.

func (*Stream) String added in v0.4.1

func (s *Stream) String() string

func (*Stream) Unify added in v0.4.1

func (s *Stream) Unify(t Term, occursCheck bool, env *Env) (*Env, bool)

Unify unifies the stream with t.

func (*Stream) Unparse added in v0.4.1

func (s *Stream) Unparse(emit func(Token), _ WriteTermOptions, _ *Env)

Unparse emits tokens that represent the stream.

type StreamMode added in v0.4.1

type StreamMode int

StreamMode describes what operations you can perform on the stream.

type StreamOption added in v0.4.1

type StreamOption func(*Stream)

StreamOption describes an option on stream creation.

func WithAlias added in v0.4.1

func WithAlias(state *State, alias Atom) StreamOption

WithAlias sets an alias for the stream.

func WithEOFAction added in v0.4.1

func WithEOFAction(eofAction EOFAction) StreamOption

WithEOFAction sets eof_action for the stream.

func WithReposition added in v0.4.1

func WithReposition(b bool) StreamOption

WithReposition sets if the stream is random access.

func WithStreamType added in v0.4.1

func WithStreamType(streamType StreamType) StreamOption

WithStreamType sets type of the stream.

type StreamType added in v0.4.1

type StreamType int

StreamType describes what will be transferred in the stream, either text or binary.

const (
	// StreamTypeText means text.
	StreamTypeText StreamType = iota
	// StreamTypeBinary means binary.
	StreamTypeBinary
)

type Term added in v0.4.1

type Term interface {
	fmt.Stringer
	Unify(Term, bool, *Env) (*Env, bool)
	Unparse(func(Token), WriteTermOptions, *Env)
}

Term is a prolog term.

func Cons added in v0.4.1

func Cons(car, cdr Term) Term

Cons returns a list consists of a first element car and the rest cdr.

func List added in v0.4.1

func List(ts ...Term) Term

List returns a list of ts.

func ListRest added in v0.4.1

func ListRest(rest Term, ts ...Term) Term

ListRest returns a list of ts followed by rest.

func Rulify added in v0.4.1

func Rulify(t Term, env *Env) Term

Rulify returns t if t is in a form of P:-Q, t:-true otherwise.

func Seq added in v0.4.1

func Seq(sep Atom, ts ...Term) Term

Seq returns a sequence of ts separated by seq.

func Set added in v0.4.1

func Set(ts ...Term) Term

Set returns a list of ts which elements are unique.

func Slice added in v0.3.0

func Slice(list Term, env *Env) (ret []Term, err error)

type Token added in v0.4.1

type Token struct {
	Kind TokenKind
	Val  string
}

Token is a smallest meaningful unit of prolog program.

func (Token) String added in v0.4.1

func (t Token) String() string

type TokenKind added in v0.4.1

type TokenKind byte

TokenKind is a type of Token.

const (
	// TokenEOS represents an end of token stream.
	TokenEOS TokenKind = iota

	// TokenVariable represents a variable token.
	TokenVariable

	// TokenFloat represents a floating-point token.
	TokenFloat

	// TokenInteger represents an integer token.
	TokenInteger

	// TokenIdent represents an identifier token.
	TokenIdent

	// TokenQuotedIdent represents a quoted identifier token.
	TokenQuotedIdent

	// TokenGraphic represents a graphical token.
	TokenGraphic

	// TokenComma represents a comma.
	TokenComma

	// TokenPeriod represents a period.
	TokenPeriod

	// TokenBar represents a bar.
	TokenBar

	// TokenParenL represents an open parenthesis.
	TokenParenL

	// TokenParenR represents a close parenthesis.
	TokenParenR

	// TokenBracketL represents an open bracket.
	TokenBracketL

	// TokenBracketR represents a close bracket.
	TokenBracketR

	// TokenBraceL represents an open brace.
	TokenBraceL

	// TokenBraceR represents a close brace.
	TokenBraceR

	// TokenSign represents a plus/minus.
	TokenSign

	// TokenDoubleQuoted represents a double-quoted string.
	TokenDoubleQuoted
)

func (TokenKind) String added in v0.4.1

func (k TokenKind) String() string

type UnexpectedRuneError added in v0.4.1

type UnexpectedRuneError struct {
	// contains filtered or unexported fields
}

UnexpectedRuneError represents an error which is raised when the given input contains an unexpected rune.

func (UnexpectedRuneError) Error added in v0.4.1

func (e UnexpectedRuneError) Error() string

type UnexpectedTokenError added in v0.4.1

type UnexpectedTokenError struct {
	ExpectedKind TokenKind
	ExpectedVals []string
	Actual       Token
	History      []Token
}

func (UnexpectedTokenError) Error added in v0.4.1

func (e UnexpectedTokenError) Error() string

type VM

type VM struct {

	// OnCall is a callback that is triggered when the VM reaches to the predicate.
	OnCall func(pi ProcedureIndicator, args []Term, env *Env)

	// OnExit is a callback that is triggered when the predicate succeeds and the VM continues.
	OnExit func(pi ProcedureIndicator, args []Term, env *Env)

	// OnFail is a callback that is triggered when the predicate fails and the VM backtracks.
	OnFail func(pi ProcedureIndicator, args []Term, env *Env)

	// OnRedo is a callback that is triggered when the VM retries the predicate as a result of backtrack.
	OnRedo func(pi ProcedureIndicator, args []Term, env *Env)

	// OnUnknown is a callback that is triggered when the VM reaches to an unknown predicate and also current_prolog_flag(unknown, warning).
	OnUnknown func(pi ProcedureIndicator, args []Term, env *Env)
	// contains filtered or unexported fields
}

VM is the core of a Prolog interpreter. The zero value for VM is a valid VM without any builtin predicates.

func (*VM) Arrive added in v0.5.0

func (vm *VM) Arrive(pi ProcedureIndicator, args []Term, k func(*Env) *Promise, env *Env) *Promise

Arrive is the entry point of the VM.

func (*VM) Register0

func (vm *VM) Register0(name string, p func(func(*Env) *Promise, *Env) *Promise)

Register0 registers a predicate of arity 0.

func (*VM) Register1

func (vm *VM) Register1(name string, p func(Term, func(*Env) *Promise, *Env) *Promise)

Register1 registers a predicate of arity 1.

func (*VM) Register2

func (vm *VM) Register2(name string, p func(Term, Term, func(*Env) *Promise, *Env) *Promise)

Register2 registers a predicate of arity 2.

func (*VM) Register3

func (vm *VM) Register3(name string, p func(Term, Term, Term, func(*Env) *Promise, *Env) *Promise)

Register3 registers a predicate of arity 3.

func (*VM) Register4

func (vm *VM) Register4(name string, p func(Term, Term, Term, Term, func(*Env) *Promise, *Env) *Promise)

Register4 registers a predicate of arity 4.

func (*VM) Register5

func (vm *VM) Register5(name string, p func(Term, Term, Term, Term, Term, func(*Env) *Promise, *Env) *Promise)

Register5 registers a predicate of arity 5.

type Variable added in v0.4.1

type Variable string

Variable is a prolog variable.

func NewVariable added in v0.4.1

func NewVariable() Variable

func (Variable) Generated added in v0.4.1

func (v Variable) Generated() bool

func (Variable) String added in v0.4.1

func (v Variable) String() string

func (Variable) Unify added in v0.4.1

func (v Variable) Unify(t Term, occursCheck bool, env *Env) (*Env, bool)

Unify unifies the variable with t.

func (Variable) Unparse added in v0.4.1

func (v Variable) Unparse(emit func(token Token), opts WriteTermOptions, env *Env)

Unparse emits tokens that represent the variable.

type Variables added in v0.4.1

type Variables []Variable

func (Variables) Except added in v0.4.1

func (vs Variables) Except(ws Variables) Variables

func (Variables) Terms added in v0.4.1

func (vs Variables) Terms() []Term

type WriteTermOptions added in v0.4.1

type WriteTermOptions struct {
	Quoted     bool
	Ops        Operators
	NumberVars bool

	Priority int
}

WriteTermOptions describes options to write terms.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL