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
contains core language features of Deck. It is automatically imported into each module and should be considered part of the language implementation.
Evaluate body
once and return its result. If final
is given, evaluate it after body
finishes.
Call procedure pr
on each element in seq
, discarding the result. This is a slightly more compact, less flexible form of the for
loop.
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.
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.
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
.
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.
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.
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.
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.
Return true
if left
and right
are not equal according to ==
.
Create an Interval
for the range from start
to end
with an increment of 1. range
is an alias for this procedure.
Test if lhs
and rhs
are the same object.
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.
Return the absolute value of aNum
, a Number.
Return a new sequence of the same type as destList
containing all elements in destList
followed by each of the following arguments.
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.
Return a list containing the contents of seq
, an object that implements the list protocol.
Store a value in a sequence.
Return a ByteArray containing the arguments. Arguments must be integers with values between 0 and 255.
Create an empty (zero-initialized) ByteArray that is size
bytes long.
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.
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
.
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 +
.
Test if there is a global variable named name
(a symbol) visible in the current namespace.
Print the arguments (using the internal printer) concatenated together, then exit with an error status.
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.
Exit with an error message and backtrace. The error message consists of all of the arguments stringified and concatented together.
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 ->
.
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
.
Return number aNumber
as an integer. aNumber
is truncated toward zero.
Given string aString
, return the symbol containing the same text.
Return an integer between 0 and max
- 1.
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.
Return the index of the last item in sequence aSeq
.
Return a new list containing all of the arguments in the order they were given.
Return an empty (nil-filled) list of size size
.
CREATE LoL CONTAININ TEH LISTS IN ALL ELEMENTS. EACH ARGUMENT MUST ALSO BE LoL.
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.
Return the largest element in args
as determined by the standard comparison operators.
Return the smallest element in args
as determined by the standard comparison operators.
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.
Return number aNumber
negated (i.e. with its sign flipped, so negative if it was positive and positive if it was negative.)
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.
Return the boolean complement of obj
.
Return a PerlObj wrapping obj
.
Write the printable form of each argument in turn on stdout followed by a newline.
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 (:
).
Return a random non-negative real number less than max
.
Write the printable form of each argument in turn on stdout.
Return a copy of sequence seq
with the elements shuffled.
Return the number of items in sequence aSeq
.
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
.
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.
Create an empty string size
characters long.
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.
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.
Return the name of the type of obj
.
Given symbol aSymbol
, return a string containing the same text.
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)
Expands to [left->op_Mod right]
.
Expands to [left->op_BitAnd right]
.
Perform a short-circuited logical AND. right
will only be evaluated if left
has evaluated to true.
Expands to [left->op_Mult right]
.
Expands to [left->op_Pow right]
.
Expands to [left->op_Add right]
.
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).
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]
.
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)]
.
Expands to [left->op_Div right]
.
Expands to [left->op_DivTrunc right]
.
Expands to [left->op_Lt right]
.
Expands to [left->op_LShift right]
.
Expands to [left->op_Lte right]
.
Assigns RHS value
to LHS value
. dest
is either a bare name, a list access (@
) expression or an attribute (.
) expression.
Expands to [left->op_Equals right]
.
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.)
Expands to [left->op_Gt right]
.
Expands to [left->op_Gte right]
.
Expands to [left->op_RShift right]
.
Expands to [left->at right]
.
Expands to [left->op_BitXor right]
.
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.
Declares one or more constants in the local scope.
Alias for foreach
.
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.
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.
Declares a macro in the current module scope.
Declares an mproc in the current module scope.
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.
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.
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.
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.
Performs assignments. Prefix alias for =
.
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.
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.
Declares one or more variables in the local scope.
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
.
Expands to [left->op_BitOr right]
.
Perform a short-circuited logical Or operation. right
is evaluated only if left
has evaluated to false.
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
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
.
Return a human-readable textual represention of this object.
Methods
+
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.
==
operator: True if obj
is also a ByteArray and all elements equal the corresponding element in obj
.
Return a copy of self
.
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
Return a List
of Symbols
, each one the name of a method implemented by this class and not one of its superclasses.
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.
Return a human-readable textual represention of this object.
Return a List
of Symbols
, each one the name of a method implemented by this method or one of its superclasses.
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
Test if this class implements a method named by message
. message
must be a symbol.
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.
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
Make a copy of this Exception
. Note that all fields are shared across both instances.
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 ''
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
Return a list containing all of the keys in self
.
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.
Return a list containing each key in self
immediately followed by the associated value.
Return a human-readable textual represention of this object.
Return the number of items (i.e. key/value pairs) in self
.
Return a list containing all of the values in self
.
Methods
Object initializer.
Initialize perlHash
. It holds a reference to a Perl hash, which does the actual work.
Given a list of key/value pairs, store each value in self
with the associated 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.
Store value
in self
at key
. key
must be one of the supported key types.
Test if key
is present in self
. Returns true if present, false if not.
Implements the ==
operator: tests for equality. Hashes are equal if their keys and associated values are all equal.
Remove the key/value pair associated with key
from self
.
Create a new hash with the same contents.
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
The last value in self
.
True. Intervals
are indexable.
This object's truth value. Like other sequences, true unless empty.
The human-friendly description of self
.
Sequence Protocol: Number of (imaginary) items.
Methods
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.
Dies with an error if called.
==
operator: True if other
is also an Interval
containing the same sequence of numbers.
Make a copy of this Interval
.
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
Returns true, since List
implements the sequence protocol.
Return a human-readable textual represention of this List
.
Sequence Protocol: Return the number of items in this object.
Methods
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.
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.
+
operator, overloaded: Returns self
and otherSeq
concatenated together. The result is the type returned by maker
(list
in this case).
==
operator: True if obj
is also a List and all elements equal (via op_Equals
) the corresponding element in obj
.
Return a copy of self
without copying the items it references.
Macro
is the class of all Deck macros.
Attributes
Tell if instances of this class are callable. Yes, in this case.
Return a human-readable textual represention of this object.
Methods
Macros
are immutable so we just return the same instance.
Method
is the class of all Deck methods.
Attributes
Return a human-readable textual represention of this object.
Methods
Methods
are immutable so we just return the same instance.
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
Tell if instances of this class are callable. Yes, in this case.
Return a human-readable textual represention of this object.
Methods
MethodCalls
are immutable so we just return the same instance.
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
Test if this object is nil
. Returns true.
Return a human-readable textual represention of this object.
Methods
Return self
since nil is immutable.
Number
is the class of all (built-in) number types in Deck. Instances are floating-point values.
Attributes
Deprecated. Return a string suitable for representing this object as the key in a Perl hash. Used in class Hash
.
Return a human-readable textual represention of this object.
Methods
Add self to number num
Return num
bitwise ANDed with self
. Both are first truncated to the nearest integer.
Return num
bitwise ORed with self
. Both are first truncated to the nearest integer.
Return num
bitwise XORed with self
. Both are first truncated to the nearest integer.
Return num
divided by self
.
Return num
divided by self
and rounded toward zero.
Test if num
is greater than self
Test if num
is greater than or equal to self
Test if num
is less than self
.
Return true if num
is less than or equal to self
.
Return num
modulo self.
Return num
multiplied by self
.
+
operator. Performs addition.
&
operator. Perform bitwise AND operation. Fractional arguments are first truncated toward zero.
|
operator. Perform bitwise OR operation. Fractional arguments are first truncated toward zero.
^
operator. Perform bitwise exclusive-OR operation. Fractional arguments are first truncated toward zero.
/
operator. Performs division.
//
operator. Performs division, truncating to the nearest int.
Test if self
and obj
have the same numeric value. (Non-numbers clearly do not.)
>
operator. Test if self
is greater than obj
. This overrides the version in Object
for no good reason.
>=
operator. Test if self
is greater than or equal to self
. This overrides the version in Object
for no good reason.
<<
operator. Shift self left by obj
.
<
operator. Test if self
is less than obj
. This overrides the version in Object
for no good reason.
<=
operator. Performs greater-than-or-equal-to test.
%
operator. Performs the modulo operation.
*
operator. Performs multiplication.
**
operator. Return self
raised to the power of other
.
>>
operator. Shift self right by obj
.
-
operator. Performs subtraction.
Return num
raised to the power of self
.
Return self, since Numbers are immutable.
Return num
shifted left by self
Return num
shifted right by self
Subtract self from num
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
Return the class of this object.
Deprecated. Return a string suitable for representing this object as the key in a Perl hash. By default, calling this is an error.
Tell if instances of this class are callable.
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.
Returns a true value if this object is nil, false otherwise.
Return this object's truth value. Somewhat magical.
Sequence Protocol: Return the index of the last item in this object.
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
.
Return a human-readable textual represention of this object.
Return this object.
Methods
This is the message that each object receives when it is first created. Its implementation is expected to initialize the new object.
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.)
Called by abstract methods to signal that an error has occurred.
Make a copy of this object.
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.
==
operator: Test if self
and other
are equal with respect to their types. Should be overridden by subclass; defaults to using ===
.
Operator >
: Test if self is greather than obj
.
Operator >=
: Test if self is greater than or equal to obj
.
Operator <
: Test if self is less than obj
.
Operator <=
: Abstract method. Subclasses must implement this.
Make a copy of this object without copying the objects it references.
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
Return a human-readable textual represention of this object.
Methods
PerlObjs
are immutable so we just return the same instance.
Procedure
is the class of most Deck procedures (procs, subs, etc).
Attributes
Tell if instances of this class are callable. Yes, in this case.
Return a human-readable textual represention of this object.
Methods
Procedures
are immutable so we just return the same instance.
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
Return a human-readable textual represention of this object.
The thing being wrapped.
Methods
==
operator: True if obj
is also a Quote
and both objects' values are also equal according to op_Equals
.
Create a new Quote
wrapping the same object.
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
Deprecated. Return a string suitable for representing this object as the key in a Perl hash. Used in class Hash
.
Test if self
is all ASCII whitespace.
Return true if self
contains one character and that character is an ASCII vowel.
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
.
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.
Return a human-readable textual represention of this object; in this case just self
; a string is its own printable.
Methods
Return a copy of self
with all uppercase characters replaced with their lowercase equivalents.
+
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).
==
operator: True if obj
is also a String
or Symbol
and all characters match the the corresponding characters in obj
.
<=
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
.
Create and return a copy of self
.
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
Returns true, since all Stringlike
subclasses implement the sequence protocol.
Sequence Protocol: Return the number of items in this object.
Methods
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.
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.
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
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.
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.)
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:
Symbols are immutable. atPut
will fail on one.
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
Deprecated. Return a string suitable for representing this object as the key in a Perl hash. Used in class Hash
.
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
.
Return a human-readable textual represention of this object.
Methods
+
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).
==
operator: true if self === obj or if obj is a string with the same characters in it.
<=
operator: See String->op_Lte
.
Symbols are immutable so just return self
.
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.
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.
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.
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.
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.
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
Test if this FileHandle
is readable.
Test if this FileHandle
is writeable.
Test if this file handle is at the end of the file.
Get/set the error exception. This is the exception that gets thrown if there is an I/O error.
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
.
Returns the position in bytes of this FileHandle
relative to the start of the file.
Methods
Close the underlying system file handle associated with this file. After close
has been called, this object should no longer be used.
Read a single character from this file and return it as a string.
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.
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.
Writes string
at the current file position.
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.
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.
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.
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.
Writes the bytes in bytes
, a ByteArray, to the current file at the current position.
StatResult is a data structure holding the results of a successful stat call. Readable fields are:
name dev ino mode nlink uid gid rdev size atime mtime ctime blksize blocks
Attributes
Return a human-readable representation.
Methods
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.
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.
Compile the regex regex
into a Perl object after first performing some checks.
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.
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.
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.
Store a value in a sequence.
(_::atput is an alias for Lang::atput)
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
.
Adds docstrings and methods to built-in classes.
This is a symbol that the compiler expands into a const declaration. Calling it is a fatal error.
Define a new namespace named by symbol namespaceName
.
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:
[:class name builtin superclass docstring]
[:proc name builtin args docstring]
[:method name builtin classname methodname args docstring]
[:attrib name builtin classname :readable/:writeable/:public attrib-name docstring]
[:macro name builtin args docstring]
[:mproc name builtin args docstring]
[:package name docstring]
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.
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.
Backend for the 'for'/'foreach' macro.
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)
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)
Performs an 'if' comparison. This is the backend of a number of flow-control macros.
Defines a macro.
Primitive implementation of 'map'.
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)
Like _::mkstr
but takes a single list of objects instead of multiple arguments.
Define an mproc.
Define a proc written in Perl with source code given in bodyString
. Implements perlproc
.
Implement the perluse
statement.
Defines a proc described by the arguments. Should only be invoked by the proc
macro.
Identical to _::say
except that it also prints a newline.
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
.
Assigns a value to a variable.
Defines a sub.
Implements the use
statement.
Return the last item in the argument list. If none is given, return nil. All arguments are evaluated.
This is a symbol that the compiler expands into a var declaration. Calling it is a fatal error.
The back-end for a number of looping macros.
This namespace is reserved for procs created by mproc
. Do not use it or anything in it.