core

package
v0.0.0-...-c76748b Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2015 License: BSD-3-Clause Imports: 17 Imported by: 0

Documentation

Overview

Package core implements a Scheme interpreter. TODO: add more documentation

Index

Constants

This section is empty.

Variables

View Source
var BadCodeVersion = errors.New("byte code version not supported")
View Source
var BadMagicNumber = errors.New("magic number does not match")
View Source
var InvalidUtf8String = errors.New("input contains invalid UTF-8 bytes")
View Source
var NumberOutOfRange = errors.New("number value of out range")
View Source
var OutOfBounds = errors.New("index out of bounds")
View Source
var ParserError = errors.New("unexpected parser error")
View Source
var StringIsImmutable = errors.New("immutable string cannot be set!")
View Source
var TypeMismatch = errors.New("type mismatch in atom comparison")
View Source
var UnknownType = errors.New("unknown type, cannot serialize")

Functions

func BindArguments

func BindArguments(env Environment, names interface{}, values Sequence) (Environment, LispError)

BindArguments binds the argument names to the given values, allowing for extra arguments to be assigned to the last name if the list is improper. Returns the new environment ready for evaluation.

func Car

func Car(a interface{}) interface{}

Car returns the first element in a sequence.

func Cdr

func Cdr(a interface{}) interface{}

Cdr returns the second element in a sequence.

func Compile

func Compile(name string, expr interface{}) (CodeObject, LispError)

Compile converts the parsed and expanded s-expression into a CodeObject which can be executed by the stack-based byte code interpreter.

func CompileLambda

func CompileLambda(args interface{}, expr interface{}) (CodeObject, LispError)

CompileLambda compiles the given expression assuming that it is a lambda expression which accepts the given arguments.

func CompileString

func CompileString(name string, prog string) (CodeObject, LispError)

CompileString parses, expands, and compiles the given program.

func Cxr

func Cxr(name string, a interface{}) interface{}

Cxr implements all of the caar, cadr, ... cddddr procedures defined in Scheme, where name is the name of the procedure to process.

func EncodeCode

func EncodeCode(code CodeObject, out io.Writer) (err error)

EncodeCode writes the given code object to given writer.

func NewLambda

func NewLambda(body interface{}, params interface{}) *lambda

NewLambda constructs a new lambda for the given function body and parameters.

Types

type Atom

type Atom interface {
	// CompareTo compares other to this atom and returns:
	//
	//   -1 if this <  other
	//    0 if this == other
	//    1 if this >  other
	//
	// An error is returned if the object is not of a suitable type for
	// comparison.
	CompareTo(other Atom) (int8, error)
	// EqualTo returns true if the values of this atom and the specified
	// object are equal, false otherwise. An error is returned if the
	// object is not of the same type.
	EqualTo(other Atom) (bool, error)
	// Eval returns the result of evaluating this object.
	Eval() interface{}
	// String returns the string representation of this object.
	String() string
}

Atom represents all things in our Scheme implementation which can be evaluated to a value outside of the context of a specific environment. These include strings, symbols, characters, and numbers.

type Boolean

type Boolean interface {
	Atom
	// Value returns the boolean value.
	Value() bool
}

Boolean represents a true/false value in Scheme.

var BooleanFalse Boolean = booleanImpl(false)

BooleanFalse is the singleton instance of the 'false' value.

var BooleanTrue Boolean = booleanImpl(true)

BooleanTrue is the singleton instance of the 'true' value.

func BooleanFromBool

func BooleanFromBool(val bool) Boolean

BooleanFromBool returns the singleton instance of the Boolean value that matches the value given (i.e. BooleanTrue or BooleanFalse).

func NewBoolean

func NewBoolean(val string) Boolean

NewBoolean compares the input with the expected values for Scheme booleans (e.g. "#t", "#T", "#f", and "#F") and constructs a new Boolean atom. If val does not represent a boolean value then panic ensues.

func NewParsedBoolean

func NewParsedBoolean(val string, row, col int) Boolean

NewParsedBoolean returns a Locatable Boolean object.

type ByteVector

type ByteVector []uint8

ByteVector represents the bytevector type in Scheme. It is a sequence of bytes whose values range from 0 to 255.

func NewByteVector

func NewByteVector(data []uint8) ByteVector

NewByteVector wraps the given data in a ByteVector type.

func (ByteVector) Get

func (b ByteVector) Get(pos int) uint8

func (ByteVector) Len

func (b ByteVector) Len() int

func (ByteVector) ObjectId

func (b ByteVector) ObjectId() uintptr

func (ByteVector) Set

func (b ByteVector) Set(pos int, val uint8)

func (ByteVector) String

func (b ByteVector) String() string

String converts the bytevector to a string representation of itself (e.g. "#u8(0 10 5)"). This is not to be confused with the procedures for converting the bytes in the vector to a UTF-8 string.

type Character

type Character interface {
	Atom
	// ToRune returns the rune this character represents.
	ToRune() rune
}

Character represents a single character (e.g. '#\\a' or '#\\space') in Scheme.

func NewCharacter

func NewCharacter(val string) Character

NewCharacter creates an instance of Character to represent the given Scheme character. Characters are prefixed with #\, as in #\a for the letter 'a'. Special sequences are #\space for ' ' and #\newline for the newline character. Invalid input, such as a short string, will result in the uf8.RuneError character.

func NewParsedCharacter

func NewParsedCharacter(val string, row, col int) Character

NewParsedCharacter returns a Locatable Character object.

type Closure

type Closure interface {
	// Bind this closure with the given arguments and return the new
	// environment, suitable for evaluating this closure.
	Bind(values Sequence) (Environment, LispError)
	// Body returns the body of the closure for evaluation.
	Body() interface{}
	// Apply evaluates the body of the closure within the given
	// environment, returning the result, or an error.
	Apply(env Environment) (interface{}, LispError)
}

Closure represents a procedure that can be invoked. It has an associated environment in which the procedure was defined, and any evaluations will be done in the context of that environment.

func NewByteClosure

func NewByteClosure(body CodeObject, env Environment, vm VirtualMachine) Closure

NewByteClosure returns an implementation of Closure that applies to a compiled procedure, bound to the given environment and virtual machine.

func NewClosure

func NewClosure(body interface{}, params interface{}, env Environment) Closure

NewClosure constructs a new Closure with the given definition, defining environment, and parameters.

type CodeObject

type CodeObject interface {
	fmt.Stringer
	// Name returns the name of the original source file, primarily used
	// for error reporting.
	Name() string

	// Arguments returns the arguments for the compiled procedure.
	Arguments() interface{}
	// LineForOffset returns the line number in the original source code
	// which corresponds to the given byte code offset, primarily used
	// for error reporting.
	LineForOffset(pos uint) int
	// ConstantLen returns the number of constants contained within.
	ConstantLen() uint
	// GetConstant returns a constant from the constants table.
	GetConstant(pos uint) interface{}
	// SymbolLen returns the number of symbols contained within.
	SymbolLen() uint
	// GetSymbol returns a symbol from the symbols table.
	GetSymbol(pos uint) Symbol
	// CodeLen returns the number of instructions contained within.
	CodeLen() uint
	// GetInstruction returns an instruction from the set of instructions.
	GetInstruction(pos uint) Instruction
	// contains filtered or unexported methods
}

CodeObject encapsulates a compiled script or procedure.

func DecodeCode

func DecodeCode(in io.Reader) (code CodeObject, err error)

func NewCodeObject

func NewCodeObject(name string, args interface{}, codes []Instruction, cons []interface{},
	syms []Symbol, lines []byteLinePair) CodeObject

NewCodeObject constructs a new instance of CodeObject given the name, arguments, byte codes, constants, symbols, and mapping of line numbers to byte code offsets.

type Compiler

type Compiler interface {
	// AddInstruction adds the given instruction to the accumulated results.
	AddInstruction(code Opcode, arg interface{})
	// FindOrAddConstant ensures the constants table holds the given value,
	// returning the offset for that constant.
	FindOrAddConstant(con interface{}) uint
	// FindOrAddSymbol ensures the symbols table holds the given name,
	// returning the offset for that symbol.
	FindOrAddSymbol(sym Symbol) uint
	// Compile produces the byte codes for the given expression
	Compile(expr interface{}) LispError
	// Assemble pulls the final result into a cohesive set of instructions
	// in which all intermediate values have been stripped.
	Assemble(name string, args interface{}) CodeObject
}

Compiler constructs a CodeObject one piece at a time and assembles the final result on demand.

func NewCompiler

func NewCompiler() Compiler

NewCompiler constructs an instance of Compiler.

type Complex

type Complex interface {
	Number
	// ToComplex converts this Complex to a complex128 value.
	ToComplex() complex128
	// RealPart returns the floating-point real part of the complex number.
	RealPart() float64
	// ImagPart returns the floating-point imaginary part of the complex number.
	ImagPart() float64
}

Complex represents a complex number, with real and imaginary parts.

func NewComplex

func NewComplex(val complex128) Complex

func NewParsedComplex

func NewParsedComplex(val complex128, row, col int) Complex

NewParsedComplex returns a Locatable Complex object.

type EmptyList

type EmptyList int

EmptyList is a type unto itself, representing the "empty" value in Scheme, as well as marking the end of lists.

func (EmptyList) Append

func (e EmptyList) Append(a interface{}) Pair

Append on the empty list returns a new list whose cdr is the empty list, which allows additional append operations to work as expected.

func (EmptyList) First

func (e EmptyList) First() interface{}

First always returns nil.

func (EmptyList) Iterator

func (e EmptyList) Iterator() Iterator

func (EmptyList) Join

func (e EmptyList) Join(a interface{})

Join does nothing on an empty list. EmptyList is empty.

func (EmptyList) Len

func (e EmptyList) Len() int

Len returns the length of the empty list, which is always zero.

func (EmptyList) Map

func (e EmptyList) Map(f func(interface{}) interface{}) Sequence

Map always returns the empty list without calling the function.

func (EmptyList) ObjectId

func (e EmptyList) ObjectId() uintptr

ObjectId of empty list is always zero.

func (EmptyList) Rest

func (e EmptyList) Rest() interface{}

Rest always returns nil.

func (EmptyList) Reverse

func (e EmptyList) Reverse() Pair

Reverse always returns the empty list.

func (EmptyList) Second

func (e EmptyList) Second() interface{}

Second always returns nil.

func (EmptyList) String

func (e EmptyList) String() string

String returns the string representation of the empty list, which is always "()".

func (EmptyList) Third

func (e EmptyList) Third() interface{}

Third always returns nil.

func (EmptyList) ToSlice

func (e EmptyList) ToSlice() []interface{}

ToSlice on the empty list always returns nil.

type Environment

type Environment interface {
	// Find looks for the given symbol in this environment, and the parent
	// environment, if one is associated with this environment.
	Find(sym Symbol) interface{}
	// Lookup looks for the given symbol pairing (where the value is ignored)
	// and retrieves the value found in this environment. This has little
	// practical value outside of Environment implementations.
	Lookup(key SymbolPair) interface{}
	// Define sets the value for a symbol in this environment, creating
	// a new mapping if one does not already exist.
	Define(sym Symbol, val interface{})
	// Set assigns the value to the symbol in this environment, but only
	// if there is a previously defined value for that symbol.
	Set(sym Symbol, val interface{}) LispError
}

Environment encapsulates all of the visible symbols in the current scope. It may consist of parent environments, such that a symbol missing in this environment may be found in a parent.

func NewEnvironment

func NewEnvironment(parent Environment) Environment

NewEnvironment constructs an Environment with the given parent to provide a fallback for finding variables. The parent may be nil.

func NewRestrictedEnvironment

func NewRestrictedEnvironment(parent Environment, mapping map[Symbol]interface{}) Environment

NewRestrictedEnvironment constructs an Environment with the given set of mappings. The environment cannot be modified.

type ErrorCode

type ErrorCode int

ErrorCode indicates the error status of the Scheme evaluation, with EOK representing no error.

const (
	EOK       ErrorCode = iota // no error
	EARGUMENT                  // e.g. illegal, missing
	ECOMMAND                   // e.g. undefined, unsupported, unknown
	ESUPPORT                   // feature unsupported
	ESYNTAX                    // e.g. invalid number syntax
	ESYMBOL                    // e.g. undefined
	ELEXER                     // lexer error
	EIO                        // I/O error
	EINTERNAL                  // something bad happened
)

Error constants

type ExecutionFrame

type ExecutionFrame interface {
	// NextInstruction returns the next instruction and advances the
	// program counter. When the end of the code object is reached, an
	// instruction whose code is OP_NOP is returned.
	NextInstruction() Instruction
	// Jump moves the program counter to the given byte code offset.
	Jump(pos uint)
	// Environment returns the environment instance for this frame.
	Environment() Environment
	// Constant retrieves the constant value at the index within the
	// constants table contained in the code object in this frame.
	Constant(pos uint) interface{}
	// Symbol retrieves the symbol at the index within the symbols table
	// contained in the code object in this frame.
	Symbol(pos uint) Symbol
}

ExecutionFrame represents the a frame of execution of a code object. It has a program counter that advances as each instruction in the code object is requested (and presumably executed).

func NewExecutionFrame

func NewExecutionFrame(code CodeObject, env Environment) ExecutionFrame

NewExecutionFrame constructs an instance of ExecutionFrame.

type Float

type Float interface {
	Number
	// ToFloat converts the float to a float64 value.
	ToFloat() float64
}

Float represents a floating point numerical value.

func NewFloat

func NewFloat(val float64) Float

NewFloat creates an Integer object for the given float64 value.

func NewParsedFloat

func NewParsedFloat(val float64, row, col int) Float

NewParsedFloat returns a Locatable Float object.

type ForwardReference

type ForwardReference interface {
	// Label returns the identifier for the forward reference.
	Label() string
	// Resolve returns the datum referred to by this reference. A nil value
	// signals an error (Scheme nil is represented using an instance of the
	// None type).
	Resolve() interface{}
}

ForwardReference provides a means for temporarily referring to an object that is being referenced before it is completely defined. An example would be a list of pairs that contains a reference to itself.

type Identifiable

type Identifiable interface {
	// ObjectId returns the unique identifier for this object.
	ObjectId() uintptr
}

Indentifiable objects implement this interface to provide their unique object identifier. While objects may mutate, their identifier should remain the same. The primary purpose of the identifier is to avoid infinite loops when traversing nested, possibly self-referencing, structures.

type ImmutableString

type ImmutableString string

ImmutableString is like a String but Set() returns an error.

func NewImmutableString

func NewImmutableString(val string) ImmutableString

NewImmutableString creates a new ImmutableString instance.

func (ImmutableString) CompareTo

func (is ImmutableString) CompareTo(other Atom) (int8, error)

func (ImmutableString) EqualTo

func (is ImmutableString) EqualTo(other Atom) (bool, error)

func (ImmutableString) Eval

func (is ImmutableString) Eval() interface{}

func (ImmutableString) Len

func (is ImmutableString) Len() int

func (ImmutableString) Set

func (is ImmutableString) Set(pos int, ch rune) error

func (ImmutableString) String

func (is ImmutableString) String() string

func (ImmutableString) Value

func (is ImmutableString) Value() string

type Instruction

type Instruction interface {
	// Code returns the opcode for this instruction (e.g. OP_CALL).
	Code() Opcode
	// Argument returns the optional argument for this opcode. Not all
	// operations take an argument, such as OP_POP and OP_RETURN. Typically
	// this is an index into either the constants or symbols table.
	Argument() uint
}

Instruction represents a single opcode and its argument, if any.

func NewInstruction

func NewInstruction(code Opcode, arg uint) Instruction

NewInstruction creates an instance of Instruction based on the arguments.

type Integer

type Integer interface {
	Number
	// Mod finds the remainder of dividing this number by the argument.
	Mod(modulus Integer) Integer
	// ToInteger converts the integer to an int64 value.
	ToInteger() int64
}

Integer represents an integral numeric value.

func NewInteger

func NewInteger(val int64) Integer

NewInteger creates an Integer object for the given int64 value.

func NewParsedInteger

func NewParsedInteger(val int64, row, col int) Integer

NewParsedInteger returns a Locatable Integer object.

type Iterator

type Iterator interface {
	// HasNext indicates if there is another value in the sequence.
	HasNext() bool
	// IsProper indicates that the sequence was a proper list (e.g. (a b
	// c)) versus an improper list (e.g. (a b . c). This function will
	// always return true until the end of an improper list has been
	// reached. Vectors are always proper.
	IsProper() bool
	// Next returns the next value in the sequence, returning nil if the
	// end of the sequence has been reached.
	Next() interface{}
}

Iterator provides a mechanism for efficiently and easily visiting all of the elements in a sequence.

type LispError

type LispError interface {
	error
	Locatable
	// ErrorCode returns the error code associated with this result.
	ErrorCode() ErrorCode
	// ErrorMessage returns the error message associated with this result.
	ErrorMessage() string
	// Ok indicates if the result is a non-error, indicating that
	// the result is suitable for consumption.
	Ok() bool
	// String returns a human readable error message.
	String() string
	// SetLocation may be used to specify where in the text the error was found.
	SetLocation(row, col int)
}

LispError is used to provide information on the type of error that occurred while parsing or evaluating the Lisp script. It implements the error interface.

func Eval

func Eval(expr interface{}, env Environment) (interface{}, LispError)

Eval evaluates the given s-expression using a specific environment and returns the results. This handles tail-call recursion and invoking procedures, both built-in and user-defined.

func EvaluateCode

func EvaluateCode(code CodeObject, env Environment) (interface{}, LispError)

EvaluateCode evaluates the compiled byte code of a Scheme program within the given environment and returns the result, or an error if evaluation failed for any reason.

func Interpret

func Interpret(prog string) (interface{}, LispError)

Interpret parses the given Scheme program, evaluates each of the top- level elements, returning the final result.

func NewLispError

func NewLispError(err ErrorCode, msg string) LispError

NewLispError creates a new LispError based on the given values.

func NewLispErrorf

func NewLispErrorf(err ErrorCode, form string, args ...interface{}) LispError

NewLispErrorf creates a new LispError, formatting the message according to the given format and optional arguments.

func NewLispErrorl

func NewLispErrorl(err ErrorCode, elem interface{}, msg string) LispError

NewLispErrorl returns a LispError of the given type, for the selected element, with the clarifying message. If the element has location information, it will be incorporated into the error message.

type Locatable

type Locatable interface {
	// Location returns the row and column (1-based) of the element.
	Location() (int, int)
}

Locatable is any Scheme element whose location within the parsed text is known, and is defined by the (1-based) row and column of the input text.

type None

type None int

None represents the result of a line comment, or other results of parsing that resolve to nothing.

func (None) String

func (n None) String() string

String for None returns the empty string.

type Number

type Number interface {
	Atom
	// Add the given value to this number and return a new number.
	Add(value Number) Number
	// Divide this number by the divisor and return a new Number.
	Divide(divisor Number) Number
	// Multiply this number by the multiplier and return a new Number.
	Multiply(multiplier Number) Number
	// Subtract the given value from this number and return a new number.
	Subtract(value Number) Number
	// ComplexValue returns the number as a Complex.
	ComplexValue() Complex
	// IntegerValue returns the number as an Integer.
	IntegerValue() Integer
	// FloatValue returns the number as an Float.
	FloatValue() Float
	// RationalValue returns the number as a Rational.
	RationalValue() Rational
}

Number represents all numbers in Scheme, from integers to rationals.

type Opcode

type Opcode byte

Opcode represents an operation byte code, such as "load variable", "return", or "function call". The compiler produces a set of opcodes which are typically followed by a single argument. Other values are typically pushed onto an argument stack prior to the opcode being processed.

const (
	OP_NOP      Opcode = iota // no operation, used to signal end of code
	OP_LABEL                  // placeholder in intermediate code; arg is label number
	OP_CONST                  // arg: constants index
	OP_LOADVAR                // arg: symbols index
	OP_STOREVAR               // arg: symbols index; stack: value
	OP_DEFVAR                 // arg: symbols index; stack: value
	OP_FUNCTION               // arg: constants index
	OP_POP                    // arg: <none>; stack: <removes one>
	OP_JUMP                   // arg: bytecode offset
	OP_FJUMP                  // arg: bytecode offset; stack: predicate
	OP_RETURN                 // arg: <none>; stack: <none>
	OP_CALL                   // arg: number of arguments; stack: arguments
)

Operation code constants

func (Opcode) String

func (o Opcode) String() string

type Pair

type Pair interface {
	Sequence
	// ObjectId returns the unique identifier for this object.
	ObjectId() uintptr
	// Reverse returns the chain of Pairs in reverse order.
	Reverse() Pair
	// Append adds the given item to the pair, forming a list. The element
	// to which the new value was added is returned, allowing the caller
	// to chain one append operation onto the next to form a chain.
	Append(a interface{}) Pair
	// Join finds the first available slot in the chained Pairs
	// and attaches the given thing there.
	Join(a interface{})
	// ToSlice constructs a Go slice containing the values in the list of pairs.
	ToSlice() []interface{}
	// contains filtered or unexported methods
}

Pair represents a pair of items, which themselves may be pairs. Pairs can be assembled to form arbitrary tree structures, or more commonly, linked lists.

func Cons

func Cons(a, b interface{}) Pair

Cons constructs a pair to hold item a and b such that they are stored in a single instance of Pair. This may form an improper list if b is not already a proper list.

func NewList

func NewList(a ...interface{}) Pair

NewList constructs a list of pairs from the given inputs.

func NewPair

func NewPair(a interface{}) Pair

NewPair returns an instance of Pair to hold the single element a.

func SequenceToList

func SequenceToList(seq Sequence) Pair

SequenceToList converts a sequence to a list of Pairs.

type PairBuilder

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

PairBuilder permits easily building a list by appending objects to the joiner, in order, and then requesting the completed list when finished.

func NewPairBuilder

func NewPairBuilder() *PairBuilder

NewPairBuilder constructs an empty PairBuilder for building a list.

func (*PairBuilder) Append

func (pj *PairBuilder) Append(elem interface{}) *PairBuilder

Append adds the given element to the end of the list managed by this PairBuilder instance.

func (*PairBuilder) Join

func (pj *PairBuilder) Join(elem interface{}) *PairBuilder

Join adds the given element to the end of the list managed by this PairBuilder instance in an improper fashion, forming an improper list.

func (*PairBuilder) List

func (pj *PairBuilder) List() Pair

List returns the head of the list constructed by this PairBuilder.

type PairIterator

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

PairIterator iterates over a chained Pair, whether proper or not.

func (*PairIterator) HasNext

func (i *PairIterator) HasNext() bool

HasNext indicates if there is another value in the Pair chain.

func (*PairIterator) IsProper

func (i *PairIterator) IsProper() bool

IsProper indicates that the list was a proper list (e.g. (a b c)) versus an improper list (e.g. (a b . c). This function will always return true until the end of an improper list has been reached.

func (*PairIterator) Next

func (i *PairIterator) Next() interface{}

Next returns the next value in the Pair chain, returning nil if the end of the list has been reached.

type ParsedBoolean

type ParsedBoolean struct {
	Boolean // Boolean object
	// contains filtered or unexported fields
}

ParsedBoolean is a Locatable Boolean type.

func (*ParsedBoolean) Location

func (pb *ParsedBoolean) Location() (int, int)

func (*ParsedBoolean) StripLocation

func (pb *ParsedBoolean) StripLocation() interface{}

type ParsedCharacter

type ParsedCharacter struct {
	Character // Character object
	// contains filtered or unexported fields
}

ParsedCharacter is a Locatable Character type.

func (*ParsedCharacter) Location

func (pc *ParsedCharacter) Location() (int, int)

func (*ParsedCharacter) StripLocation

func (pc *ParsedCharacter) StripLocation() interface{}

type ParsedComplex

type ParsedComplex struct {
	Complex // Complex object
	// contains filtered or unexported fields
}

ParsedComplex is a Locatable Complex type.

func (*ParsedComplex) Location

func (pc *ParsedComplex) Location() (int, int)

func (*ParsedComplex) StripLocation

func (pc *ParsedComplex) StripLocation() interface{}

type ParsedFloat

type ParsedFloat struct {
	Float // Float object
	// contains filtered or unexported fields
}

ParsedFloat is a Locatable Float type.

func (*ParsedFloat) Location

func (pf *ParsedFloat) Location() (int, int)

func (*ParsedFloat) StripLocation

func (pf *ParsedFloat) StripLocation() interface{}

type ParsedInteger

type ParsedInteger struct {
	Integer // Integer object
	// contains filtered or unexported fields
}

ParsedInteger is a Locatable Integer type.

func (*ParsedInteger) Location

func (pi *ParsedInteger) Location() (int, int)

func (*ParsedInteger) StripLocation

func (pi *ParsedInteger) StripLocation() interface{}

type ParsedRational

type ParsedRational struct {
	Rational // Rational object
	// contains filtered or unexported fields
}

ParsedRational is a Locatable Rational type.

func (*ParsedRational) Location

func (pr *ParsedRational) Location() (int, int)

func (*ParsedRational) StripLocation

func (pr *ParsedRational) StripLocation() interface{}

type ParsedString

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

ParsedString is a Locatable String type.

func (*ParsedString) CompareTo

func (ps *ParsedString) CompareTo(other Atom) (int8, error)

func (*ParsedString) EqualTo

func (ps *ParsedString) EqualTo(other Atom) (bool, error)

func (*ParsedString) Eval

func (ps *ParsedString) Eval() interface{}

func (*ParsedString) Len

func (ps *ParsedString) Len() int

func (*ParsedString) Location

func (ps *ParsedString) Location() (int, int)

func (*ParsedString) Set

func (ps *ParsedString) Set(pos int, ch rune) error

func (*ParsedString) String

func (ps *ParsedString) String() string

func (*ParsedString) StripLocation

func (ps *ParsedString) StripLocation() interface{}

func (*ParsedString) Value

func (ps *ParsedString) Value() string

type ParsedSymbol

type ParsedSymbol struct {
	Symbol // Symbol object
	// contains filtered or unexported fields
}

ParsedSymbol is a Locatable Symbol type.

func (*ParsedSymbol) IsSymbol

func (ps *ParsedSymbol) IsSymbol() bool

func (*ParsedSymbol) Location

func (ps *ParsedSymbol) Location() (int, int)

func (*ParsedSymbol) StripLocation

func (ps *ParsedSymbol) StripLocation() interface{}

type Parser

type Parser interface {
	// Parse will return a collection of Scheme objects parsed from the given
	// string, returning an error if the lexing or parsing fails.
	Parse(expr string) (Sequence, LispError)
	// ParseFile reads the named file as a Scheme program, returning the
	// parsed results, or an error if anything went wrong.
	ParseFile(filename string) (Sequence, LispError)
	// Expand takes the parsed results and performs some basic validation
	// and expands the results into the canoncial form.
	Expand(x interface{}) (interface{}, LispError)
}

Parser knows how to convert a string represetation of Scheme code into a runnable program, which can be passed to the Eval() function.

func NewParser

func NewParser() Parser

NewParser constructs a new Parser instance.

type Procedure

type Procedure interface {
	// Name returns the name of the procedure as a symbol.
	Name() string
	// Call invokes the built-in procedure with the given values.
	Call(values []interface{}) (interface{}, LispError)
}

Procedure represents a callable function in Scheme.

func NewBuiltin

func NewBuiltin(f builtinProcFunc, name string, min, max int) Procedure

NewBuiltin constructs a Procedure for the given built-in function, with an associated name (for error reporting), and a minimum and maximum number of arguments, which permits validation of inputs.

type Rational

type Rational interface {
	Number
	// BigRat returns the actual math/big/Rat instance.
	BigRat() *big.Rat
	// contains filtered or unexported methods
}

func NewParsedRational

func NewParsedRational(a, b int64, row, col int) Rational

NewParsedRational returns a Locatable Rational object.

func NewRational

func NewRational(a, b int64) Rational

type Sequence

type Sequence interface {
	fmt.Stringer
	// First returns the first element of the sequence.
	First() interface{}
	// Second returns the first non-Sequence thing in the Rest() sequence.
	Second() interface{}
	// Third returns the second non-Sequence thing in the Rest() sequence.
	Third() interface{}
	// Rest returns the portion of the sequence following the first element.
	Rest() interface{}
	// Len returns the number of things in the sequence.
	Len() int
	// Iterator returns an iterator the sequence.
	Iterator() Iterator
	// Map calls the function for each thing in the sequence, returning
	// a new sequence containing the results.
	Map(f func(interface{}) interface{}) Sequence
}

Sequence represents any collection of elements that can be visited in a sequential order. This includes (chained) pairs and vectors.

func SequenceAppend

func SequenceAppend(seq interface{}, elem interface{}) Sequence

SequenceAppend adds the given element to the end of the sequence, possibly returning a new sequence.

type String

type String interface {
	Atom
	// Len returns the number of characters in this string.
	Len() int
	// Set changes the rune at the given zero-based position within the
	// string. If the position is out of bounds, panic ensues.
	Set(pos int, ch rune) error
	// Value returns the string value itself, without quotes.
	Value() string
}

String represents a string of characters in Scheme. Strings in Scheme are mutable, unlike Go strings.

func NewParsedString

func NewParsedString(val string, row, col int) String

NewParsedString returns a Locatable String object.

func NewString

func NewString(val string) String

NewString constructs a Scheme string from the given Go string.

type StringImpl

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

StringImpl is an implementation of the String interface.

func (*StringImpl) CompareTo

func (s *StringImpl) CompareTo(other Atom) (int8, error)

func (*StringImpl) EqualTo

func (s *StringImpl) EqualTo(other Atom) (bool, error)

func (*StringImpl) Eval

func (s *StringImpl) Eval() interface{}

Eval returns the String as a Go string.

func (*StringImpl) Len

func (s *StringImpl) Len() int

Len returns the number of characters in this string.

func (*StringImpl) Set

func (s *StringImpl) Set(pos int, ch rune) error

Set changes the rune at the given zero-based position within the string. If pos is out of bounds, the function returns the OutOfBounds error.

func (*StringImpl) String

func (s *StringImpl) String() string

String returns the String as a Go string.

func (*StringImpl) Value

func (s *StringImpl) Value() string

Value returns the String as a Go string.

type Symbol

type Symbol interface {
	Atom
	// IsSymbol always returns true, it exists to distinquish this type from
	// Atom, otherwise the compiler treats all Atoms as Symbols.
	IsSymbol() bool
}

Symbol represents a variable or procedure name in a Scheme expression. It is essentially a string but is treated differently.

func NewParsedSymbol

func NewParsedSymbol(val string, row, col int) Symbol

NewParsedSymbol returns a Locatable Symbol object.

func NewSymbol

func NewSymbol(val string) Symbol

NewSymbol wraps the given string in a Symbol implementation.

type SymbolPair

type SymbolPair interface {
	llrb.Item
	Symbol() Symbol
	Value() interface{}
}

SymbolPair represents an item stored in an Environment, containing the symbol used as the key, and its associated value.

type TailRecursive

type TailRecursive interface {
	// Call invokes the tail recursive function with the given values.
	Call(int, Sequence, Environment) (interface{}, interface{}, LispError)
}

TailRecursive represents a tail recursive function.

func NewRecursive

func NewRecursive(f tailRecursiveFunc) TailRecursive

NewRecursive constructs a TailRecursive for the given function.

type Vector

type Vector []interface{}

Vector represents the vector type in Scheme.

func NewVector

func NewVector(data []interface{}) Vector

NewVector wraps the given data in a vector type, whose object identifier will be generated.

func NewVectorFromValues

func NewVectorFromValues(a ...interface{}) Vector

NewVectorFromValues is the variadic form of NewVector, receiving any number of arguments and building a Vector from them.

func (Vector) Append

func (v Vector) Append(elem interface{}) Vector

Append adds the given element to the end of the vector, returning a new instance of Vector.

func (Vector) First

func (v Vector) First() interface{}

func (Vector) Get

func (v Vector) Get(pos int) interface{}

func (Vector) Iterator

func (v Vector) Iterator() Iterator

func (Vector) Len

func (v Vector) Len() int

func (Vector) Map

func (v Vector) Map(f func(interface{}) interface{}) Sequence

func (Vector) ObjectId

func (v Vector) ObjectId() uintptr

func (Vector) Rest

func (v Vector) Rest() interface{}

func (Vector) Second

func (v Vector) Second() interface{}

func (Vector) Set

func (v Vector) Set(pos int, val interface{})

func (Vector) String

func (v Vector) String() string

func (Vector) Third

func (v Vector) Third() interface{}

type VirtualMachine

type VirtualMachine interface {
	// Run evaluates the compiled byte code of a Scheme program within the
	// context of a virtual machine and returns the result, or an error if
	// evaluation failed for any reason.
	Run(code CodeObject, env Environment) (interface{}, LispError)
	// RunClosure wraps the Run() function with an additional frame on the
	// stack since the closure will pop a frame when it returns. When applied
	// via built-in procedures, there is no OP_CALL executed and thus no frame
	// pushed onto the stack.
	RunClosure(code CodeObject, env Environment) (interface{}, LispError)
}

VirtualMachine contains the state of a virtual machine that executes compiled Scheme code.

func NewVirtualMachine

func NewVirtualMachine() VirtualMachine

NewVirtualMachine constructs an instance of VirtualMachine.

type Void

type Void int

Void is a placeholder in the environment for variables that have not been assigned a value, as in the letrec binding construct.

func (Void) CompareTo

func (v Void) CompareTo(other Atom) (int8, error)

func (Void) EqualTo

func (v Void) EqualTo(other Atom) (bool, error)

func (Void) Eval

func (v Void) Eval() interface{}

Eval returns nil since Void has no value.

func (Void) String

func (v Void) String() string

String returns the empty string.

type WireStripper

type WireStripper interface {
	// StripLocation returns this element without location information.
	StripLocation() interface{}
}

WireStripper removes the location information from a locatable element and returns the underlying element. That is, a parsed string becomes a normal string, and a parsed number becomes a normal number.

Jump to

Keyboard shortcuts

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