Deck Library Reference

This is the reference manual for the Deck System Library. The System Library currently consists of all built-in objects (specifically, procedures, macros, mprocs and classes) defined by the Deck interpreter or in the module Lang.dk. It does not document the Deck language itself. For that, see the Reference Manual.

The manual itself is generated by the utility print_docstrings.dk from the docstrings of the various objects being documented. There is nothing new here that can't be found by reading the source code. However, this manual puts it all in one place.

Names beginning with _:: (i.e. belonging to the _ namespace) are internal to the system. You should never use them. They are documented here to satisfy any curiousity you might have and because you may occasionally run into system-generated code that uses them.

Package Lang

Package Lang contains core language features of Deck. It is automatically imported into each module and should be considered part of the language implementation.

MProcs

mproc Lang::do {strict sub body; strict sub final [default {}]}

Evaluate body once and return its result. If final is given, evaluate it after body finishes.

mproc Lang::dofor {sub 1 pr; seq}

Call procedure pr on each element in seq, discarding the result. This is a slightly more compact, less flexible form of the for loop.

mproc Lang::filter {sub 1 testProc; seq}

Apply procedure testProc to every element of sequence seq and return another sequence containing only the elements on which testProc returned a true value. The return value's type is compatible with seq's.

mproc Lang::fold {sub 2 pr; seq}

Performs a 'fold' (aka 'reduce') operation on seq using the first element as the initial value and applying pr to the remaining elements.

seq must contain at least one element.

See foldWith for a more detailed explanation.

mproc Lang::foldWith {sub 2 pr; initial; seq}

Performs a 'fold' (aka 'reduce') operation on seq, using procedure pr to reduce the entire sequence to a single element.

More precisely, it calls procedure pr once on each element in seq, passing it the element as its second argument. The first argument is initial on the first call and the result of the previous call on each subsequent call. The result is the result of the final call to pr.

For example, we can sum a series of numbers like this:

    sum = [foldWith {=a+b} 0 :[1 2 3 4 5] ]

If seq is empty, the result is initial.

mproc Lang::map {sub 1 transPr; seq}

Call procedure transPr on each element in seq and return another sequence containing the results of the calls on the corresponding input elements. The return value's type is compatible with seq's.

mproc Lang::repeat {count; sub 1 pr}

Evaluate procedure pr count times. pr takes one argument, the itteration number starting from zero. Does nothing if count is not greater than zero. Returns the result of the last evaluation of pr or nil if there is none.

mproc Lang::sort {sub 2 ucmp; seq}

Return a copy of seq with the elements sorted according to ucmp.

ucmp should take two arguments and return -1, 0 or 1 depending on whether the first argument is less than, equal to or greater than the second argument. (This is the same interface as cmp).

seq is an object that implements the sequence protocol and the return value is constructed by the procedure returned by seq's maker attribute.

mproc Lang::try {strict sub [Error] tryBlock; word catch; strict sub [Error] catchBlock [default {}]}

Evaluate a block, providing it with an Exception. If the exception is thrown, the rest of the block is not evaluated. However, the optional second block (following the word 'catch') is evaluated.

Both blocks are given an argument named Error. This is the Exception. It may be treated as any other object--passed to procedures, stored in global variables, etc.--but it is a fatal runtime error if its throw is called (for the first time) after the first block has finished executing.

Procedures

proc Lang::!= {left right}

Return true if left and right are not equal according to ==.

proc Lang::.. {start end}

Create an Interval for the range from start to end with an increment of 1. range is an alias for this procedure.

proc Lang::=== {lhs rhs} (Built-in)

Test if lhs and rhs are the same object.

proc Lang::_do_fold {pr initial seq startIndex}

Does the heavy lifting for fold and foldWith. startIndex is the index of the first element in seq to be used. Everything before it is ignored.

proc Lang::abs {aNum}

Return the absolute value of aNum, a Number.

proc Lang::append {destList args}

Return a new sequence of the same type as destList containing all elements in destList followed by each of the following arguments.

proc Lang::apply {fun argList} (Built-in)

Call procedure fun with the arguments in list argList and returns the result of the call. argList must be a standard Deck list and not merely an object that implements the sequence protocol.

proc Lang::asList {seq}

Return a list containing the contents of seq, an object that implements the list protocol.

proc Lang::atput {seq index value} (Built-in)

Store a value in a sequence.

proc Lang::byteArray {args} (Built-in)

Return a ByteArray containing the arguments. Arguments must be integers with values between 0 and 255.

proc Lang::bytesSized {size} (Built-in)

Create an empty (zero-initialized) ByteArray that is size bytes long.

proc Lang::chr {number} (Built-in)

Return the character represented by number in the character set. If number is not valid character in the current encoding, returns an empty string instead.

proc Lang::cmp {left right}

Compare left and right and return -1, 0 or 1 if left is less than, equal to or greater than right respectively. Operator <=> (i.e. the spaceship operator) is an alias to cmp.

proc Lang::concat {args}

Return a sequence containing the contents of all arguments (which must be sequences) concatenated together. The return type is determined by the first argument's maker. Under some circumstances, this may be faster than +.

proc Lang::defined {name} (Built-in)

Test if there is a global variable named name (a symbol) visible in the current namespace.

proc Lang::die {args} (Built-in)

Print the arguments (using the internal printer) concatenated together, then exit with an error status.

proc Lang::exit {status} (Built-in)

Exit immediately with exit status status. status must be a number. If it is not an integer, it is truncated down to the nearest integer value.

proc Lang::fail {args} (Built-in)

Exit with an error message and backtrace. The error message consists of all of the arguments stringified and concatented together.

proc Lang::getMethod {object methodName} (Built-in)

Return the MethodCall object that invokes the method named by symbol methodName in object object. If there is no matching method, the MethodCall invokes doesNotUnderstand.

This is almost never called explicitly. Usually, calls are generated by the macro ->.

proc Lang::getSuperMethod {object methodName} (Built-in)

This is identical to getMethod except that the method search starts at the superclass of object.

It is usually invoked by the macro -> and is not guaranteed to work unless object is the caller's self.

proc Lang::int {aNumber} (Built-in)

Return number aNumber as an integer. aNumber is truncated toward zero.

proc Lang::intern {aString} (Built-in)

Given string aString, return the symbol containing the same text.

proc Lang::irand {max}

Return an integer between 0 and max - 1.

proc Lang::join {tween seq}

Performs a Perl-style join on seq. Given string tween and sequence seq, returns a string containing all of the printables of seq concatenated together with tween between each pair of items.

For example:

   join ':' :['1' '2' '3' '4' '5']

yields:

   '1:2:3:4:5'

tween and elements of seq are stringified with the printable attribute so non-strings will work fine.

proc Lang::last {aSeq}

Return the index of the last item in sequence aSeq.

proc Lang::list {args} (Built-in)

Return a new list containing all of the arguments in the order they were given.

proc Lang::listSized {size} (Built-in)

Return an empty (nil-filled) list of size size.

proc Lang::lolcat {args}

CREATE LoL CONTAININ TEH LISTS IN ALL ELEMENTS. EACH ARGUMENT MUST ALSO BE LoL.

proc Lang::lookup {name} (Built-in)

Get the value of the variable named by symbol name in the current context. If name is undefined, it is a fatal error. name must be a global variable.

proc Lang::max {args}

Return the largest element in args as determined by the standard comparison operators.

proc Lang::min {args}

Return the smallest element in args as determined by the standard comparison operators.

proc Lang::mkstr {args} (Built-in)

Return a string containing all of the arguments' internal string representation (i.e. from the interpreter, not the printable attribute). This is used to expand double-quoted strings.

proc Lang::neg {aNumber} (Built-in)

Return number aNumber negated (i.e. with its sign flipped, so negative if it was positive and positive if it was negative.)

proc Lang::new {class args} (Built-in)

Create and return a new instance of the class given by class. The remaining arguments are passed to the new object's init method. This is identical to invoking the class's new method.

proc Lang::not {obj} (Built-in)

Return the boolean complement of obj.

proc Lang::perlobj {obj} (Built-in)

Return a PerlObj wrapping obj.

proc Lang::puts {args}

Write the printable form of each argument in turn on stdout followed by a newline.

proc Lang::quote {obj} (Built-in)

Return a Quote object wrapping obj.

Note: this does not in any way affect the evaluation of of its argument. quote is not a special form. If you want to delay normal evaluation of an expression, use the quote operator (:).

proc Lang::rand {max}

Return a random non-negative real number less than max.

proc Lang::say {args}

Write the printable form of each argument in turn on stdout.

proc Lang::shuffled {seq}

Return a copy of sequence seq with the elements shuffled.

proc Lang::size {aSeq}

Return the number of items in sequence aSeq.

proc Lang::slice {seq start end}

Return a sequence containing the elements of seq in the index range between start and end. If end is nil, the last index in seq is used instead. The return type is determined by the maker attribute of seq.

proc Lang::str2num {aString} (Built-in)

Parse aString as the printable form of a numeric constant. All of the forms accepted by the Deck parser are also accepted by str2num. If aString does not contain a valid number, str2num returns nil.

proc Lang::stringSized {size} (Built-in)

Create an empty string size characters long.

proc Lang::subify {exprList args} (Built-in)

From the given arguments, create a list which will, when evaluated as an expression, return a sub. It is intended to aid in writing macros and provides standard argument handling for many system macros already.

exprList is the body of the sub and must be a list or LoL. If it is not a LoL, it is automatically wrapped with another list, making it into a LoL.

args can be a list of symbols or a number. If it is a list of symbols, those symbols form the sub's formal argument list. If it is a number, the argument list is generated with that many arguments named a through z. Naturally, args must be between 0 and 26.

Note that subify does no syntax checking at all. If you provide garbage input, you'll get garbage output.

proc Lang::subifyOrDelay {expr} (Built-in)

Create a list which, when evaluated as an expression, will return a sub that evaluates expr. If expr is a list, subifyOrDelay will behave exactly like subify. Otherwise, the sub will evaluate and return expr, whatever it is.

This allows stuff like while a {a = a - 1} to work.

proc Lang::typeof {obj}

Return the name of the type of obj.

proc Lang::unintern {aSymbol} (Built-in)

Given symbol aSymbol, return a string containing the same text.

proc Lang::value {args} (Built-in)

Return the last item in the argument list. If none is given, return nil. All arguments are evaluated.

(Lang::value is an alias for _::value)

Macros

macro Lang::% {left right} (Built-in)

Expands to [left->op_Mod right].

macro Lang::& {left right} (Built-in)

Expands to [left->op_BitAnd right].

macro Lang::&& {left right} (Built-in)

Perform a short-circuited logical AND. right will only be evaluated if left has evaluated to true.

macro Lang::* {left right} (Built-in)

Expands to [left->op_Mult right].

macro Lang::** {left right} (Built-in)

Expands to [left->op_Pow right].

macro Lang::+ {left right} (Built-in)

Expands to [left->op_Add right].

macro Lang::- {left maybeRight} (Built-in)

If given two arguments, expands to [left-op_Sub maybeRight]> (i.e. ordinary subtraction). If maybeRight is ommitted, expands to [neg left] (i.e. negation).

macro Lang::-> {object message} (Built-in)

Performs a method lookup of RHS message on LHS object and returns the matching MethodLookup object. If object is the word super, self is used instead but the method search starts at the object's superclass.

Note that syntactic sugar in the compiler will implicitly wrap any bare -> expression at the start of an infix expression with round brackets, making it infix. Hence, [foo->bar 1] becomes [(foo->bar) 1].

macro Lang::. {object attribute} (Built-in)

Performs an attribute lookup. object.attribute expands to [object-attribute_get]. However, the assignment macros = and set will expand to an attribute_set call if the destination of the assignment is a . expression.

In addition, the synactic sugar in the compiler will automatically wrap any expression . word sequence in an infix expression with round brackets, making them infix. Hence, [add a.val b.val] becomes [add (a.val) (b.val)].

macro Lang::/ {left right} (Built-in)

Expands to [left->op_Div right].

macro Lang::// {left right} (Built-in)

Expands to [left->op_DivTrunc right].

macro Lang::< {left right} (Built-in)

Expands to [left->op_Lt right].

macro Lang::<< {left right} (Built-in)

Expands to [left->op_LShift right].

macro Lang::<= {left right} (Built-in)

Expands to [left->op_Lte right].

macro Lang::= {dest = value} (Built-in)

Assigns RHS value to LHS value. dest is either a bare name, a list access (@) expression or an attribute (.) expression.

macro Lang::== {left right} (Built-in)

Expands to [left->op_Equals right].

macro Lang::=> {args body} (Built-in)

Creates a sub. args and body must be list constants of the sorts allowed by sub.

Note that syntactic sugar in the compiler will automatically wrap any => expression in an infix expression with round brackets. Hence,

    [map {a} => {value (a*a)} l]

becomes

    [map ({a} => {value (a*a)}) l]

(This form may be deprecated in the future in favour of the '{||...}' form.)

macro Lang::> {left right} (Built-in)

Expands to [left->op_Gt right].

macro Lang::>= {left right} (Built-in)

Expands to [left->op_Gte right].

macro Lang::>> {left right} (Built-in)

Expands to [left->op_RShift right].

macro Lang::@ {left right} (Built-in)

Expands to [left->at right].

macro Lang::^ {left right} (Built-in)

Expands to [left->op_BitXor right].

macro Lang::class {name superclass body} (Built-in)

Define a class named by word name. Word superclass is the name of the superclass and may be ommitted, in which case Struct is assumed. body is the class body and is expected to be a LoL.

macro Lang::const {args} (Built-in)

Declares one or more constants in the local scope.

macro Lang::for {item in list body} (Built-in)

Alias for foreach.

macro Lang::foreach {item in list body} (Built-in)

Evaluates body over each element in list from start to end with a local variable item set to reference the element. The second argument must be the word in. This implements the standard foreach loop. Argument body is subified.

macro Lang::if {cond trueBlock else falseBlock} (Built-in)

Evaluate a sequence of instructions conditionally. Evaluates cond and if the result is true, then evaluates trueBlock. Otherwise, it evaluates falseBlock if present (it is optional). This is the standard if statement.

cond can be subified or delayed; trueBlock and falseBlock are always subified. falseBlock is optional. else is the word 'else'; it is always optional and should be omitted if falseBlock is also absent.

macro Lang::macro {name args body} (Built-in)

Declares a macro in the current module scope.

macro Lang::mproc {name args body} (Built-in)

Declares an mproc in the current module scope.

macro Lang::package {moduleName} (Built-in)

Declare this file to be the package named by word moduleName. This is really a compiler directive and it is an error to use anywhere other than the first (non-trivial) line of a module.

macro Lang::perlproc {name args body} (Built-in)

Define a Perl function plus bindings to Deck. name and args are identical to proc and friends but body is a string constant containing Perl code.

macro Lang::perluse {name} (Built-in)

Force the Perl interpreter running udeck to load the Perl module named by name via the require statement. This module must be accessed via perlproc functions.

macro Lang::proc {name args body final} (Built-in)

Declares a procedure in the current module scope. final is optional. The resulting procedure is also returned.

If name is omitted, the resulting proc is unnamed but is still returned. (Note that this is different from an anonymous sub in several ways.)

If called with only a name, the statement instead creates a forward declaration of the procedure. In this case, it returns nil.

macro Lang::set {dest value} (Built-in)

Performs assignments. Prefix alias for =.

macro Lang::sub {args body final} (Built-in)

Create a sub (i.e. a closure) in the local scope and return it. args is the list of arguments (in any of the acceptable formal argument formats) and body is a LoL containing the sub's source code. args and final are both optional but if final is present, args must also be present.

macro Lang::use {moduleName mode items} (Built-in)

Import the module named by word moduleName into the current namespace. items is the optional list of items to import, ignore or rename and mode must be one of with, without or rename. The last two arguments are optional.

macro Lang::var {args} (Built-in)

Declares one or more variables in the local scope.

macro Lang::while {cond block} (Built-in)

Repeatedly evaluate cond followed by block until the first time cond evaluates false. Returns the result of the last call to block or nil if that never happens. This is the standard while loop.

cond is processed by subifyOrDelay; block is processed by subify.

macro Lang::| {left right} (Built-in)

Expands to [left->op_BitOr right].

macro Lang::|| {left right} (Built-in)

Perform a short-circuited logical Or operation. right is evaluated only if left has evaluated to false.

Classes

Lang::ByteArray (Stringlike) -- Built-in

A ByteArray is a sequence of 8-bit bytes. Any sequence of bytes is allowed.

ByteArray implements the sequence protocol but will fail if you attempt to store a value in it that is not an integer between 0 and 255.

Attributes

readable maker

Sequence protocol: return a procedure which will create a collection suitable for holding the contents of self and which takes one argument, a number specifying the size. In this case, it's bytesSized.

readable printable

Return a human-readable textual represention of this object.

Methods

method op_Add {otherBArray}

+ operator, overloaded: Returns self and obj concatenated together. The result is the type returned by maker (ByteArray in this case). Note that obj does not have to be a ByteArray but must contain only bytes (i.e. integers between 0 and 255.

method op_Equals {obj}

== operator: True if obj is also a ByteArray and all elements equal the corresponding element in obj.

method shallowCopy {}

Return a copy of self.

Lang::Class (Object) -- Built-in

All classes (i.e. types) in Deck are themselves objects and those objects are instances of type Class. This includes Class itself.

Class serves two purposes: to provide information about the class and to create new instances via its new method.

Attributes

readable methods

Return a List of Symbols, each one the name of a method implemented by this class and not one of its superclasses.

public name

The class's name. Note that unnamed classes may exist and that the name attribute is not necessarily the same as the global symbol (if present) that references the class. This is the common case but it is not guaranteed.

readable printable

Return a human-readable textual represention of this object.

readable selectors

Return a List of Symbols, each one the name of a method implemented by this method or one of its superclasses.

readable superclass

Return a reference to this class's superclass. This can be nil if the class does not have a superclass. Currently, only Object is like that.

Methods

method can {message}

Test if this class implements a method named by message. message must be a symbol.

method new {args}

Create a new instance of this class and return it. The argument list is passed to the new object's _init method, which new calls first.

Lang::Exception (Struct)

Instances of Exception represent error conditions and are used to recover from them or bring the program to a graceful halt. Instances are typically created by the try mproc.

Exception has three public fields:

message is a human-readable description of the error.
id is a machine-parsable error message, typically a symbol.
info is a List of associated arguments.

Typical Exceptions wrap a continuation which will return control flow to some earlier context. Calling throw invokes this continuation and exits the current procedure and all other callers up to the try block that created it. throw also deletes the continuation, turning subsequent calls to throw into no-ops.

The global const Fatal references an Exception which will cause the current program to exit with an error.

Attributes

Methods

method shallowCopy {}

Make a copy of this Exception. Note that all fields are shared across both instances.

method throw {msg args}

Throw this Exception. If msg is given (i.e. not a false value), store it in the message field. If it is followed by a symbol (in args), that value is stored in the id field. The remaining arguments if present are stored in the info field. Thus

    exc->throw 'Oh no!' :error 1 2 3 4 5

is equivalent to

    exc.message = 'Oh no!' exc.id = :error exc.info = [list 1 2 3 4 5] exc->throw ''

Lang::Hash (Struct)

Instances of Hash are associative arrays (aka 'dictionaries' or 'hash tables') which map keys to values. The contents are accessed using the at and atPut methods so the @ operator can be used to access the contents.

Someday, any object will be a valid key but for now, the key must be a String, Symbol or Number.

(Actually, any object which implements the readable attribute hashKey will work if the implementation returns a string and guarantees that the the strings are equal if and only if the objects are equal. This is deprecated, however as it will break the planned future implementation of Hash. Instead, you should compute the string and explicitly use it as the key. The current implementation is like this so I can use Perl hashes to do the heavy lifting. This let me slap together a useful Hash class in a few hours.)

(Also, I know that Hash is a bad name for this class because it implies a specific underlying implementation, which is a no-no in OOP. I did it anyway because the term 'hash' has become common shorthand for associative arrays and Hash is probably clearer to most programmers than Dictionary or AssociativeArray. It's also easier to type.)

Attributes

readable keys

Return a list containing all of the keys in self.

readable keysAndValuePairs

Return a list of 2-element lists, one for each item stored in self with the first element in each pair being the key and the second being the value.

readable keysAndValues

Return a list containing each key in self immediately followed by the associated value.

readable printable

Return a human-readable textual represention of this object.

readable size

Return the number of items (i.e. key/value pairs) in self.

readable values

Return a list containing all of the values in self.

Methods

method _init {args}

Object initializer.

method _initState {}

Initialize perlHash. It holds a reference to a Perl hash, which does the actual work.

method _setInitialValues {values}

Given a list of key/value pairs, store each value in self with the associated key.

method at {key}

Retrieve the object in self stored at key. key must be present or it is a fatal error. key must be one of the supported key types.

method atPut {key value}

Store value in self at key. key must be one of the supported key types.

method exists {key}

Test if key is present in self. Returns true if present, false if not.

method op_Equals {obj}

Implements the == operator: tests for equality. Hashes are equal if their keys and associated values are all equal.

method removeKey {key}

Remove the key/value pair associated with key from self.

method shallowCopy {}

Create a new hash with the same contents.

Lang::Interval (Struct)

Instances of Interval mimic a list containing a consecutive series of numbers as defined by the new arguments startVal, endVal and incrVal, all Numbers truncated to the nearest integer. startVal is the first number, endVal is the last (possibly approximated) and incrVal is the increment from one value to the next.

The main purpose of Interval is to provide a way to do a for/foreach loop over a series of integers without having to create an actual array of integers. This allows you to do stuff like this:

   for i in (1 .. 10000000) { ... }

instead of

   var x = 0; while (x < 10000000) { ... ; x = x + 1 }

(The .. operator creates an Interval.)

Intervals implement the sequence protocol but atPut fails with an error since they are naturally not writable.

Attributes

readable end

The last value in self.

readable isIndexable

True. Intervals are indexable.

readable isTrue

This object's truth value. Like other sequences, true unless empty.

readable printable

The human-friendly description of self.

readable size

Sequence Protocol: Number of (imaginary) items.

Methods

method at {index}

Sequence Protocol: Return the item at position index. Indexes must be contiguous and start at zero. Negative indexes are subtracted from the list's size.

method atPut {index value}

Dies with an error if called.

method op_Equals {other}

== operator: True if other is also an Interval containing the same sequence of numbers.

method shallowCopy {}

Make a copy of this Interval.

Lang::List (Object) -- Built-in

List is the fundamental Deck list type. Unlike most Lispish languages, Deck does not present its lists as linked lists of cells. Instead, a Deck List is an array (i.e. a 'vector') of object references whose individual items can be accessed with the at and atPut methods (usually hidden by the @ operator). The indexes start at zero and increase to the number of items minus one.

This is different from most Lispish languages, where a list is implemented as a linked list of pairs of references (CONS cells).

List implements the sequence protocol: at, atPut, size, maker isIndexable returns true.

Attributes

readable isIndexable

Returns true, since List implements the sequence protocol.

readable printable

Return a human-readable textual represention of this List.

readable size

Sequence Protocol: Return the number of items in this object.

Methods

method at {index}

Sequence Protocol: Return the item at position index. Indexes must be contiguous and start at zero. Negative indexes are subtracted from the list's size.

method atPut {index value}

Sequence Protocol: Store value at position index and return value. Indexes start at zero and must be contiguous. Negative indexes are subtracted from the list's size.

method op_Add {otherSeq}

+ operator, overloaded: Returns self and otherSeq concatenated together. The result is the type returned by maker (list in this case).

method op_Equals {obj}

== operator: True if obj is also a List and all elements equal (via op_Equals) the corresponding element in obj.

method shallowCopy {}

Return a copy of self without copying the items it references.

Lang::Macro (Object) -- Built-in

Macro is the class of all Deck macros.

Attributes

readable isCallable

Tell if instances of this class are callable. Yes, in this case.

readable printable

Return a human-readable textual represention of this object.

Methods

method shallowCopy {}

Macros are immutable so we just return the same instance.

Lang::Method (Object) -- Built-in

Method is the class of all Deck methods.

Attributes

readable printable

Return a human-readable textual represention of this object.

Methods

method shallowCopy {}

Methods are immutable so we just return the same instance.

Lang::MethodCall (Object) -- Built-in

MethodCall is the class of all method call objects. Method calls are callable objects that will call a specific method on a specific object, both of which are captured inside the MethodCall.

Instances of MethodCall are the result of a call to getMethod or getSuperMethod (which are usually called by the macro ->).

Attributes

readable isCallable

Tell if instances of this class are callable. Yes, in this case.

readable printable

Return a human-readable textual represention of this object.

Methods

method shallowCopy {}

MethodCalls are immutable so we just return the same instance.

Lang::Nil (Object) -- Built-in

Nil is the type of the object representing uninitialized variables. There is only one instance, the global constant nil. Unset variables are initialized to nil, as are empty lists.

Attributes

readable isNil

Test if this object is nil. Returns true.

readable printable

Return a human-readable textual represention of this object.

Methods

method shallowCopy {}

Return self since nil is immutable.

Lang::Number (Object) -- Built-in

Number is the class of all (built-in) number types in Deck. Instances are floating-point values.

Attributes

readable hashKey

Deprecated. Return a string suitable for representing this object as the key in a Perl hash. Used in class Hash.

readable printable

Return a human-readable textual represention of this object.

Methods

method addNumber {num}

Add self to number num

method bitAndNumber {num}

Return num bitwise ANDed with self. Both are first truncated to the nearest integer.

method bitOrNumber {num}

Return num bitwise ORed with self. Both are first truncated to the nearest integer.

method bitXorNumber {num}

Return num bitwise XORed with self. Both are first truncated to the nearest integer.

method divNumber {num}

Return num divided by self.

method divTruncNumber {num}

Return num divided by self and rounded toward zero.

method gtNumber {num}

Test if num is greater than self

method gteNumber {num}

Test if num is greater than or equal to self

method ltNumber {num}

Test if num is less than self.

method lteNumber {num}

Return true if num is less than or equal to self.

method modNumber {num}

Return num modulo self.

method multNumber {num}

Return num multiplied by self.

method op_Add {obj}

+ operator. Performs addition.

method op_BitAnd {obj}

& operator. Perform bitwise AND operation. Fractional arguments are first truncated toward zero.

method op_BitOr {obj}

| operator. Perform bitwise OR operation. Fractional arguments are first truncated toward zero.

method op_BitXor {obj}

^ operator. Perform bitwise exclusive-OR operation. Fractional arguments are first truncated toward zero.

method op_Div {obj}

/ operator. Performs division.

method op_DivTrunc {obj}

// operator. Performs division, truncating to the nearest int.

method op_Equals {obj}

Test if self and obj have the same numeric value. (Non-numbers clearly do not.)

method op_Gt {obj}

> operator. Test if self is greater than obj. This overrides the version in Object for no good reason.

method op_Gte {obj}

>= operator. Test if self is greater than or equal to self. This overrides the version in Object for no good reason.

method op_LShift {obj}

<< operator. Shift self left by obj.

method op_Lt {obj}

< operator. Test if self is less than obj. This overrides the version in Object for no good reason.

method op_Lte {obj}

<= operator. Performs greater-than-or-equal-to test.

method op_Mod {obj}

% operator. Performs the modulo operation.

method op_Mult {obj}

* operator. Performs multiplication.

method op_Pow {obj}

** operator. Return self raised to the power of other.

method op_RShift {obj}

>> operator. Shift self right by obj.

method op_Sub {obj}

- operator. Performs subtraction.

method powNumber {num}

Return num raised to the power of self.

method shallowCopy {}

Return self, since Numbers are immutable.

method shiftLeft {num}

Return num shifted left by self

method shiftRight {num}

Return num shifted right by self

method subNumber {num}

Subtract self from num

Lang::Object (none) -- Built-in

Object is the root class. All other classes in Deck are derived from Object.

Object is a pure abstract base class. It cannot be instantiated.

Attributes

readable class

Return the class of this object.

readable hashKey

Deprecated. Return a string suitable for representing this object as the key in a Perl hash. By default, calling this is an error.

readable isCallable

Tell if instances of this class are callable.

readable isIndexable

Tests if this object can be treated as a sequence (i.e. implements the sequence protocol). If true, the object must implement at least at, size and maker as expected and atPut should either behave as expected as well or fail with an error.

readable isNil

Returns a true value if this object is nil, false otherwise.

readable isTrue

Return this object's truth value. Somewhat magical.

readable last

Sequence Protocol: Return the index of the last item in this object.

readable maker

Sequence protocol: return a procedure which will create a collection suitable for holding the contents of self and which takes one argument,a number specifying the size. It defaults to listSized.

readable printable

Return a human-readable textual represention of this object.

readable self

Return this object.

Methods

method _init {args}

This is the message that each object receives when it is first created. Its implementation is expected to initialize the new object.

method _sanitizeIndex {index}

Sequence Protocol: Given an index into a sequence, return the normal index for the object (i.e. an integer between 0 and the last index or die with an error if it cannot be mapped to a valid index.

In particular, _sanitizeIndex replaces a negative index with the matching positive index. (Negative indexes are relative to the end of the sequence.)

method abstract {}

Called by abstract methods to signal that an error has occurred.

method copy {}

Make a copy of this object.

method doesNotUnderstand {name args}

This method is called when the object receives a message it does not understand (i.e. there is no corresponding method implemented.)

Default behaviour is to exit with an error message.

method op_Equals {other}

== operator: Test if self and other are equal with respect to their types. Should be overridden by subclass; defaults to using ===.

method op_Gt {obj}

Operator >: Test if self is greather than obj.

method op_Gte {obj}

Operator >=: Test if self is greater than or equal to obj.

method op_Lt {obj}

Operator <: Test if self is less than obj.

method op_Lte {obj}

Operator <=: Abstract method. Subclasses must implement this.

method shallowCopy {}

Make a copy of this object without copying the objects it references.

Lang::PerlObj (Object) -- Built-in

PerlObj is a wrapper around some Perl data. Perl functions created using perlproc can return Perl data that has no meaningful representation inside Deck and these can then be passed to other Perl procedures.

For example, a Deck wrapper around a Perl library may use a PerlObj to hold a reference to an instance of a class defined in the library.

There is no way to modify a PerlObj in Deck.

Attributes

readable printable

Return a human-readable textual represention of this object.

Methods

method shallowCopy {}

PerlObjs are immutable so we just return the same instance.

Lang::Procedure (Object) -- Built-in

Procedure is the class of most Deck procedures (procs, subs, etc).

Attributes

readable isCallable

Tell if instances of this class are callable. Yes, in this case.

readable printable

Return a human-readable textual represention of this object.

Methods

method shallowCopy {}

Procedures are immutable so we just return the same instance.

Lang::Quote (Object) -- Built-in

Quote instances are used to represent quotation in Deck expressions. They are typically represented in Deck source code via the colon operator (:).

Each Quote contains a single data value which may be retrieved using the value attribute. A Quote in an expression evaluates to its wrapped value. For example, the compiler will evaluate this

[a b c]

as an expression where a, b and c are expected to be variables and a is expected to reference something callable and so will attempt to call the callable at a with arguments b and c.

On the other hand, this

:[a b c]

will evaluate to [a b c], a List of Symbols.

Instances are created with the procedure quote (but note that quote is not a special form; its argument is evaluated normally.)

In practice, you will rarely find references to Quote in everyday code. Their purpose is to affect compilation and that's generally over with by the time it reaches your code. You will (probably) only ever need to use a Quote when creating Deck expressions to be compiled later by the Deck compiler.

Attributes

readable printable

Return a human-readable textual represention of this object.

readable value

The thing being wrapped.

Methods

method op_Equals {obj}

== operator: True if obj is also a Quote and both objects' values are also equal according to op_Equals.

method shallowCopy {}

Create a new Quote wrapping the same object.

Lang::String (Stringlike) -- Built-in

String instances contain human-readable text which can be printed to the console or stored in a file. The class implements the sequence protocol but the objects stored or retrieved from a String must themselves be strings of length 1.

Unlike many other languages, Deck does not have a character type. Instead, strings are encoded in some manner and it is best not to make assumptions about the details. In particular, you should never use a String to hold arbitrary binary data as this will break when Deck switches to using UTF8. Use ByteArray for that.

That being said, Strings are currently 7-bit ASCII and all operations are performed within the C locality.

Attributes

readable hashKey

Deprecated. Return a string suitable for representing this object as the key in a Perl hash. Used in class Hash.

readable isSpace

Test if self is all ASCII whitespace.

readable isVowel

Return true if self contains one character and that character is an ASCII vowel.

readable maker

Sequence protocol: return a procedure which will create a collection suitable for holding the contents of self and which takes one argument, a number specifying the size. In this case, it's stringSized.

readable ord

Return the numeric code of the first character of self. If self is empty, returns 0. Note that while Deck currently encodes strings in ASCII or some variant, it is not safe to assume that this will continue in later versions.

readable printable

Return a human-readable textual represention of this object; in this case just self; a string is its own printable.

Methods

method lowercase {}

Return a copy of self with all uppercase characters replaced with their lowercase equivalents.

method op_Add {otherString}

+ operator, overloaded: Returns self and otherString concatenated together. The result is the type returned by maker (String in this case). Note that otherString does not have to be a string but must contain only strings of length 1 (i.e. characters).

method op_Equals {obj}

== operator: True if obj is also a String or Symbol and all characters match the the corresponding characters in obj.

method op_Lte {other}

<= operator: lexically compares self with other (which must be a String or Symbol) and returns true if self comes before other or if they are equal. The other comparisons are implemented in Object.

method shallowCopy {}

Create and return a copy of self.

Lang::Stringlike (Object) -- Built-in

This is the abstract base class for several classes representing various sequences of binary or specially-encoded data. It should not be used directly.

Attributes

readable isIndexable

Returns true, since all Stringlike subclasses implement the sequence protocol.

readable size

Sequence Protocol: Return the number of items in this object.

Methods

method at {index}

Sequence Protocol: Return the item at position index. Indexes must be contiguous and start at zero. Negative indexes are subtracted from the list's size.

method atPut {index value}

Sequence Protocol: Store value at position index and return value. Indexes start at zero and must be contiguous. Negative indexes are subtracted from the list's size. value must be of a type that can be stored in this object.

Lang::Struct (Object) -- Built-in

Struct is the base class for all traditional classes. A traditional class is a class whose data is stored in named fields.

This is an abstract base class and cannot be instantiated. All subclasses should implement the method init to initialize the fields when an instance is created.

Struct subclasses are typically instantiated using the new method or procedure.

Methods

method _structShallowCopy {}

Return a copy of self with all instance variables referencing the same objects the original references. A subclass should use this to implement shallowCopy only if the new copy does not interfere with the internal state of the original.

method shallowCopy {}

Create a suitably shallow copy of self such that the copy cannot interfere with the operation of the original. (For example, if the original contains a private list that it modifies, that list should be copied. Otherwise, both instances will modify the same (formerly) private list.)

Lang::Symbol (Stringlike) -- Built-in

Symbols are mostly used to represent names in expressions. They are similar to strings in that they contain human-readable text. However, there are some notable differences:

  1. Symbols are immutable. atPut will fail on one.

  2. Symbols are unique. There is only ever one symbol with a particular value.

Symbol implements the sequence protocol but as mentioned above, the atPut method will fail.

Symbols can be converted to and from strings via the intern and unintern procedures. Symbol literals are created by prefixing the symbol with the : character, e.g. :foo. This works as expected, with the quote delaying evaluation and so yielding the symbol instead of the variable it would represent.

Attributes

readable hashKey

Deprecated. Return a string suitable for representing this object as the key in a Perl hash. Used in class Hash.

readable maker

Sequence protocol: return a procedure which will create a collection suitable for holding the contents of self and which takes one argument, a number specifying the size. In this case, it's stringSized.

readable printable

Return a human-readable textual represention of this object.

Methods

method op_Add {obj}

+ operator, overloaded: Returns self and obj concatenated together. The result is the type returned by maker (String in this case). Note that obj does not have to be a String or Symbol but must contain only strings of length 1 (i.e. characters).

method op_Equals {obj}

== operator: true if self === obj or if obj is a string with the same characters in it.

method op_Lte {other}

<= operator: See String->op_Lte.

method shallowCopy {}

Symbols are immutable so just return self.

Package IO

This module provides basic file support. Actual file access is performed using instances of the class FileHandle while path management (e.g. file existence checks, directory listings) are performed using various procedures and/or mprocs. In addition, there are some convenience mprocs.

IO allows you to use Exceptions for error detection but does not require it.

MProcs

mproc IO::lsdir {dir; onError [default nil]}

Return a list containing the names of all directory entries in dir. On error, return nil. If exception onError is not nil, it is thrown when an error occurs.

mproc IO::mkdir {path; mask [default 511]; onError [default nil]}

Create a directory specified by path. mask is the directory umask (standard Unix file permissions--see the perl documentation on umask for an explanation). This is typically an octal constant. with the individual bits specifing read, write and execute bits for the user, group and other permisions. onError, if not nil, is thrown as an Exception if an error occurs. Otherwise, returns false on error and true on success.

mproc IO::rmdir {dir; onError [default nil]}

Delete directory dir. Returns true on success and false. If Exception onError is given, it is thrown instead on error. The directory must be empty.

mproc IO::stat {file; onError [default nil]}

Perform a stat operation on file. If successful, returns a StatResult describing the object. On error, returns nil unless onError is non-nil (and is an Exception), in which case it is thrown with an error message.

Delete (unlink) file. Returns true on success and false. If Exception onError is given, it is thrown instead on error.

Classes

IO::FileHandle (Struct)

FileHandle represents access to a file on disk. The filename is passed to the initializer along with a symbol indicating the mode (:read, :write or :readwrite) and an Exception to throw if an error occurs. If nil is given instead, no exception is thrown. Instead, the methods will all return nil on error. (But not the attribute getters--they return an appropriate value.)

The exception is accessible through the field errorException and may be replaced at any time.

FileHandle can treat its file as binary or text or some combination of both, depending on how it is accessed. Methods read and write will read or write the contents as ByteArray instances while getChar, getChars, getLine, put, puts and slurp read and write strings. Note that although it is currently possible to store any series of bytes in a Deck string, this may not be the case in the future. If you need to manipulate binary data, use ByteArrays.

FileHandles need to be closed when they are no longer needed. There is no finalization mechanism (yet) to close them when they are garbage-collected.

Attributes

readable canRead

Test if this FileHandle is readable.

readable canWrite

Test if this FileHandle is writeable.

readable eof

Test if this file handle is at the end of the file.

writeable exception

Get/set the error exception. This is the exception that gets thrown if there is an I/O error.

readable isOpen

Test if this FileHandle is open. If it has been closed (via close), this attribute will return false; otherwise, it will return true. Naturally, this attribute is safe to call on a closed FileHandle.

readable pos

Returns the position in bytes of this FileHandle relative to the start of the file.

Methods

method close {}

Close the underlying system file handle associated with this file. After close has been called, this object should no longer be used.

method getChar {}

Read a single character from this file and return it as a string.

method getChars {count}

Read count characters from the current input file and return them in a string. If count is more than the number of characters to the end of the file, the remaining characters are returned. This is true even if the FileHandle is already at the end of the file. In that case, the return value is an empty string.

method getLine {}

Read one line of text and return it as a String. The line delimiter is determined by the attribute eol. It defaults to the UNIX newline (0x0a). The delimiter is not stripped from the string. If the FileHandle is at the end of the file, getLine returns an empty string.

method put {string}

Writes string at the current file position.

method puts {args}

Writes the printable form of each argument to the file starting from the current position, then appends a newline (as defined by eol). Analogous to the puts function.

method read {numBytes}

Reads numBytes bytes from the file starting at the current position, then returns them in a ByteArray. If numBytes is more than the number of bytes remaining in the file, only the number of remaining bytes are read. If the current position is at the end of the file, returns an empty ByteArray.

method seek {pos whence}

Sets the position of this FileHandle to pos. whence controls how pos is used: SEEK_SET sets the position to pos, SEEK_CUR sets it to pos plus the current position and SEEK_END sets it to pos plus the end of the file (pos is typically negative.

method slurp {}

Read the remaining contents of this file and return them as a string. This can be an empty string if the file position is already at the end of the file.

method write {bytes}

Writes the bytes in bytes, a ByteArray, to the current file at the current position.

IO::StatResult (Struct)

StatResult is a data structure holding the results of a successful stat call. Readable fields are:

Attributes

readable printable

Return a human-readable representation.

Methods

Package Perl::Regex

This package provides some access to Perl regular expressions via the underlying Perl interpreter.

Most languages with regex support treat the regex as data, either as a string or as an opaque object. This library is different. It treats a regex as code. The functions and mprocs it exports all take the regex in a string as an argument and return a function that performs the actual match or transformation.

For example, in most languages, performing a match would look something like this:

    if [match '^ *' str] {
        puts 'Found leading whitespace.'
    }

Here, it looks like this:

    var leadingWhitespace = [matchsub '^ *']
    if [leadingWhitespace str] {
        puts 'Found leading whitespace.'
    }

This treats regexes as code (which they are) and also lets you save the compiled regex for reuse.

Note that all regular expressions are compiled and evaluated with the g, m and x flags (except splitsub for which g is meaningless) as explained in the perlre perldoc page.

Note also that Perl will sometimes issue warnings if a regex looks funny and that this library does not suppress those warnings.

Please refer to perlre for a complete explanation of the syntax and semantics of Perl regular expressions. You may also want to look at the perlop page for an explanation of the s/// and m// operators and the qr construct, all of which are used under the hood.

MProcs

mproc Perl::Regex::replacesub {regex; sub [args] replaceElem}

Create and return a sub that takes one argument, a string, and returns a new string with the parts matching regex replaced with the results of sub replaceElem.

replaceElem can be either a callable object or a LoL containing valid Deck code which will be turned into a sub by the mproc. It is expected to return a string; if it does not, the results are undefined. It is passed zero or more arguments, one for each captured parenthesis with an upper limit of 9. This can be troublesome if a capture group is optional because only the groups that are actually captured are passed. For example, this:

    re = replacesub '(foo)(bar)(quux)?'
    re 'foobar' {|f b q| puts f b q}

will fail with an error because the replaceElem argument is called with 2 arguments instead of 3. In a case like this, your best bet is to use args argument:

    re = replacesub '(foo)(bar)(quux)?'
    re 'foobar' {|args| puts args}

If regex is empty or not a valid regex, replacesub returns nil.

The underlying replacement is performed by the Perl s/PATTERN/REPLACEMENT/ operator where the pattern is regex and the replacement is the function replaceElem. It is called with the e, g, m and x options. These are explained in the Perl documentation.

Procedures

proc Perl::Regex::_check_and_compile {regex fun bail allowEmpty}

Compile the regex regex into a Perl object after first performing some checks.

proc Perl::Regex::matchsub {regex}

Create and return a sub that takes one argument, a string, and returns true only if regex matches it. regex must be a non-empty string containing a valid Perl regex compiled with the g, m and x flags.

For example:

    containsVowel = [matchsub '[aeiouAEIOU]']
    [containsVowel str] && [puts 'Found a vowel!']

If regex is not valid, returns nil instead. It is a fatal error for regex to be a non-string.

proc Perl::Regex::splitsub {regex}

Returns a function which splits a string into an array of strings where regex defines the delimiter.

regex is a string containing a Perl regular expression. If it is not valid, splitsub will return nil. Unlike the other Regex functions, splitsub allows an empty regular expression; it splits the string into its individual characters.

splitsub uses perl's split function. Regular expressions are compiled with the m and x modifiers (g is meaningless in this context). See the split manual for a detailed explanation of it's behaviour.

Package _

This namespace is reserved for internal objects. Do not use it or anything defined in it--later versions could change them and break your program.

Some of the objects in this namespace are documented. This is for the benefit of the curious and Deck developers only.

Procedures

proc _::atput {seq index value} (Built-in)

Store a value in a sequence.

(_::atput is an alias for Lang::atput)

proc _::class {superclass body name} (Built-in)

Create the class specified by superclass and body. name (a string) is not required to be the global const that typically references the class but it should be. Implements macro class.

proc _::class_ext {class body} (Built-in)

Adds docstrings and methods to built-in classes.

proc _::const {args} (Built-in)

This is a symbol that the compiler expands into a const declaration. Calling it is a fatal error.

proc _::defns {namespaceName} (Built-in)

Define a new namespace named by symbol namespaceName.

proc _::docstring_get {key} (Built-in)

Return a list containing the docstring information for the object named by symbol key. key is typically a global variable.

The result is a list in one of the following forms:

The first field is always a symbol and identifies the type of object being referenced and, by extension, the format of the rest of the list.

The second item is its name. The third (builtin) is a boolean that indicates whether the object is built into the interpreter.

args is the formal argument list and docstring is a string containing the long-form POD-formatted documentation for the object.

superclass and classname are references to classes that may be associated with the object. Note that not all classes are named or are named correctly. However, this generally only happens to classes that do not contain docstrings.

Attributes also have the attrib-name field, which is the name of the attribute, as opposed to the get/set method which implements it. In addition, its fifth item indicates its access mode.

proc _::docstring_keys {filter package} (Built-in)

Return a list containing the keys (i.e. names) of all documented objects in memory. The list is sorted using Perl's cmp operator. Keys are symbols and generally correspond to global variable names. filter (a Symbol) is one of the docstring types (see _::docstring_get for a list) and package (a Symbol) is the name of the package to which results are restricted. Both arguments may be nil.

proc _::foreach {list fn} (Built-in)

Backend for the 'for'/'foreach' macro.

proc _::getMethod {object methodName} (Built-in)

Return the MethodCall object that invokes the method named by symbol methodName in object object. If there is no matching method, the MethodCall invokes doesNotUnderstand.

This is almost never called explicitly. Usually, calls are generated by the macro ->.

(_::getMethod is an alias for Lang::getMethod)

proc _::getSuperMethod {object methodName} (Built-in)

This is identical to getMethod except that the method search starts at the superclass of object.

It is usually invoked by the macro -> and is not guaranteed to work unless object is the caller's self.

(_::getSuperMethod is an alias for Lang::getSuperMethod)

proc _::if {test trueSub falseSub} (Built-in)

Performs an 'if' comparison. This is the backend of a number of flow-control macros.

proc _::macro {name args body} (Built-in)

Defines a macro.

proc _::map {func seq} (Built-in)

Primitive implementation of 'map'.

proc _::mkstr {args} (Built-in)

Return a string containing all of the arguments' internal string representation (i.e. from the interpreter, not the printable attribute). This is used to expand double-quoted strings.

(_::mkstr is an alias for Lang::mkstr)

proc _::mkstr_all {argList} (Built-in)

Like _::mkstr but takes a single list of objects instead of multiple arguments.

proc _::mproc {name args body} (Built-in)

Define an mproc.

proc _::perlproc {name args bodyString} (Built-in)

Define a proc written in Perl with source code given in bodyString. Implements perlproc.

proc _::perluse {module} (Built-in)

Implement the perluse statement.

proc _::proc {name args body final} (Built-in)

Defines a proc described by the arguments. Should only be invoked by the proc macro.

proc _::puts {args} (Built-in)

Identical to _::say except that it also prints a newline.

proc _::say {args} (Built-in)

Displays a printable representation of each of its arguments to stdout. The string representations of the arguments are generated internally, not with the printable attribute so _::say (and _::puts) will work on objects with a defective printable_get.

proc _::set {name value} (Built-in)

Assigns a value to a variable.

proc _::sub {args body final} (Built-in)

Defines a sub.

proc _::use {module withTerm list} (Built-in)

Implements the use statement.

proc _::value {args} (Built-in)

Return the last item in the argument list. If none is given, return nil. All arguments are evaluated.

proc _::var {args} (Built-in)

This is a symbol that the compiler expands into a var declaration. Calling it is a fatal error.

proc _::while {test body} (Built-in)

The back-end for a number of looping macros.

Package __

This namespace is reserved for procs created by mproc. Do not use it or anything in it.