# REFERENCE

This file is automatically generated. _Do not edit._

Full reference documentation.

### How to use this documentation

The categorized index at the top provides a quick overview of each language element. To learn
more about a particular entry, search the full reference document for `^name`, where _name_ is the
symbol or word of interest.

## Index by category

### CONSTRUCTS

 - __all__ _(see: promising, all)_
 - __any__ _(see: promising, any)_
 - __break__ - exit a loop or switch case
 - __case__ _(see: switch)_
 - __catch__ _(see: promising, try)_
 - __continue__ - shortcut to the next iteration of a loop
 - __count__ - numerically controlled looping
 - __countdown__ - numerically controlled looping in reverse
 - __dountil__ - until variant that always executes the loop once
 - __dowhile__ - while variant that always executes the loop once
 - __each__ - object attribute enumeration
 - __else__ _(see: every, iterate, each, index, ply, count, countdown, if, unless, exists, switch)_
 - __elsexists__ _(see: if, unless, exists)_
 - __elsif__ _(see: if, unless, exists)_
 - __elsunless__ _(see: if, unless, exists)_
 - __every__ - general-purpose collection iterator
 - __exists__ - conditional flow control
 - __finalized__ _(see: promising)_
 - __finally__ _(see: promising, try)_
 - __if__ - conditional flow control
 - __index__ - custom order iterator
 - __iterate__ - sequentially examine values from a generator/iterator
 - __ply__ - iterate over an array-like collection
 - __promising__ - asynchronous flow control for Promises
 - __rejected__ _(see: promising)_
 - __resolved__ _(see: promising)_
 - __state__ - asynchronous finite state machine
 - __switch__ - choice-based conditional
 - __then__ _(see: promising)_
 - __throw__ - generate an exception
 - __try__ - handle exceptional errors
 - __unless__ - conditional flow control
 - __until__ - loop over a block of code while an expression is false
 - __while__ - loop over a block of code while an expression is true
 - __with__ - block-level pronoun assignment


### GLOBALS

 - __assert__ - run-time error checking
 - __debug__ - print diagnostics to the console
 - __environment__ - return SAI runtime environment information


### KEYWORDS

 - __$$__ - function arguments pseudo-array
 - __array__ - expression-oriented list literal
 - __as__ - pronoun renaming clause
 - __blank__ - an object with no traits
 - __chain__ - verb chain initiation
 - __contract__ - requirements for child objects
 - __dec__ - decrement verb
 - __delete__ - a verb that deletes variables
 - __empty__ - an array with no items
 - __enum__ - literal number enumeration
 - __exists__ - check for undefined
 - __expects__ - runtime paramater type validation
 - __false__ - boolean value false
 - __fields__ - structure literal
 - __get__ - dynamic object attribute
 - __given__ - parameter declaration and static values
 - __inc__ - value increment
 - __Infinity__ - constant representing infinity
 - __inherit__ - class heritage specification
 - __instance__ - object instance variable declaration
 - __.isa__ - object name attribute
 - __Iterator__ - name-of-the-Iterator method
 - __list__ - literal-based array construction
 - __local__ - locally scoped variable declaration
 - __main__ - indicates object should be instantiated at runtime
 - __NaN__ - not-a-number
 - __nop__ - no-operation statement
 - __null__ - a value that is no value
 - __object__ - object declaration
 - __orphan__ - rescoping this
 - __process__ - generative function definition
 - __promise__ - declare a Promise-producing function
 - __reference__ - declare global values
 - __reject__ - mark a Promise as having failed
 - __resolve__ - mark a Promise as succeeding
 - __return__ - exit a function, returning a value maybe
 - __set__ - variable assignment
 - __super__ - superclass function invocation
 - __swap__ - value swapper
 - __task__ - define a function
 - __to__ - set clause syntax
 - __traits__ - declare a structure of literal strings
 - __true__ - boolean value true
 - __unbound__ - mark a method as context-free
 - __undefined__ - the absence of a place
 - __using__ - function reference clause
 - __yield__ - process product
 - __yielding__ - process inclusion


### OPERATORS

 - __%__ - modulus
 - __*__ - multiplication
 - __**__ - exponentiation
 - __+__ - addition / string concatenation
 - __-__ - subtraction/negation
 - __/__ - mathematical division
 - __<__ - less comparison
 - __<<__ - bitwise left shift
 - __<=__ - less or equal comparison
 - __<=>__ - comparison
 - __<>__ - inequality comparison
 - __=__ - equality comparison
 - __>__ - greater comparison
 - __>=__ - greater or equal comparison
 - __>>__ - signed bitwise right shift
 - __>>>__ - unsigned bitwise right shift
 - __?<__ - minimum
 - __?>__ - maximum
 - __?? ::__ - trinary conditional
 - __and__ - logical and
 - __andb__ - bitwise and
 - __bind__ - function context binder
 - __copy__ - shallow copy
 - __create__ - object creation
 - __default__ - variable initialization
 - __initialized__ - default with assignment
 - __is__ - equivalence test
 - __isNaN__ - checks for NaN
 - __isnt__ - equivalence test
 - __isof__ - object information
 - __lsh__ - unsigned bitwise left shift
 - __nand__ - not-and logical
 - __new__ - object instantiation
 - __nor__ - not-or logical
 - __not__ - logical not
 - __notb__ - binary not
 - __number__ - numeric coercion
 - __or__ - logical or
 - __orb__ - bitwise-or
 - __rsh__ - signed bitwise right shift
 - __singleton__ - singleton object access
 - __typeof__ - javascript type disclosure
 - __ursh__ - unsigned bitwise right shift
 - __xor__ - logical exclusive-or
 - __xorb__ - binary exclusive-or


### PIPERS

 - __all__ - query a collection for all values
 - __and__ - confirms a collection
 - __any__ - query a collection for any of one-or-more values
 - __asc__ _(see: by)_
 - __audit__ - observe the elements of a collection
 - __by__ - collection sorting
 - __collect__ - collect values from an iterator into a static list
 - __concat__ - assemble two collections into a single list
 - __count__ - collection item count
 - __delete__ - multi-attribute removal
 - __desc__ _(see: by)_
 - __enkey__ - convert a list/iterator into a set of traits
 - __enlist__ - convert a collection to an array
 - __entrait__ - convert collections to object/traits
 - __expects__ - rule enforcer for traits
 - __first__ - first value
 - __has__ - collection filtering
 - __highest__ - search collection for highest value
 - __into__ - collection integration
 - __iterate__ - transforms a static collection into an iterated form
 - __keys__ - return a list of trait names
 - __last__ - last value
 - __limit__ - select certain array/iterator elements
 - __lowest__ - search collection for lowest value
 - __observe__ - inspect a value without changing it
 - __or__ - explores a collection
 - __reduce__ - collection reduction
 - __replicate__ - create a list by copying an element
 - __select__ - multi-attribute query
 - __set__ - replacement operator
 - __thru__ - transform a collection with a map-like operation
 - __total__ - reduction with addition/concatenation
 - __update__ - multi-attribute update
 - __values__ - return a list of collection values


### PRONOUNS

 - __counter__ - pronount for integer-based loops
 - __error__ - catch pronoun
 - __it__ - context-sensitive pronoun
 - __key__ - looping pronoun
 - __self__ - pronoun for set statements
 - __sum__ - reduction pronoun
 - __trial__ - pronoun for conditionals and switch


### SYNTAX

 - __!__ - function invocation operator
 - __#__ - existence assertion
 - __$__ - function parameter scoping prefix
 - __${ }__ - string composition
 - __' and "__ - string literals
 - __'''__ - multi-line string literal
 - __'d__ - conversational syntax
 - __'s__ - conversational syntax
 - __( )__ - parentheticals
 - __.__ - attribute lookup
 - __..__ - pastes two related lines together
 - __...__ - statement pasting operator
 - __//__ - source code comment indicator
 - __0b, 0o, 0x, and o__ - binary, octal, hexadecimal and radian numeric literals
 - __:__ - create an array or object literal
 - __;__ - structure definition closer
 - __<-__ - calculation precedence modifier
 - __?__ - safe fetch
 - __@__ - context-aware scoping prefix
 - __@@__ - context-ignoring scoping prefix
 - __[ ]__ - attribute lookup
 - __|__ - pipe operator prefix
 - __~__ - global scoping prefix
 - __call__ - function invocation
 - __from__ - function invocation




## Encyclopedia


### ! - _function invocation operator_ - syntax - ^!

In unary form **!** (bang) invokes the following identifier as a function call that returns a value,
passing in any parameters that follow. In binary form, invokes the method on the left as a method
of the object on the right.

    ... ! [identifier] ([parameters]) (;)
    ... [method] ! [object] ([parameters]) (;)

The following are synonymous:

    set record FetchRow!cursor
    set record !cursor.FetchRow
    set record cursor.FetchRow()

    set cursor !db.Query 'select * from names'
    set cursor to db.Query('select * from names')

If you like the `()` style of invoking functions, that's fine. But when you get into function
invokations that span multiple lines, you'll need to use the __!__ or do some really ugly
patchup work with __...__.

Neither the leading **!** nor parenthesis are needed when the verb begins the line as in
the `cursor.Close` statement below.

    set cursor !db.Query 'select * from names'
    set records !cursor.FetchAll
    cursor.Close

If you want to invert the verb/object in verb statements, you can do this:

    Close!cursor

If you wish to use **!** in a continuing expression, close the parameter
clause with a semicolon (like you'd close a structural literal).

The following examples are equivalent.

    set @x Math.sin($angle) * $magnitude
    set @x !Math.sin $angle; * $magnitude



### # - _existence assertion_ - syntax - ^#

When defining fields or traits, using a hash in front of a trait _name_ will automatically assign
a value of **true** to that trait.

    .. traits #[tagname]
    .. fields #[tagname]

The following two definitions are identical:

    set row1 to: name 'John', age 19, #cat, #dog
    set row2 to: name 'John', age 19, cat true, dog true



### $ - _function parameter scoping prefix_ - syntax - ^$

Easy access to the first parameter a function was called with (even if no parameters are declared
with __given__).

    .. $
    .. $[attribute]

When alone, **$** returns the first parameter a function was called with.

    set ShowParameter to task
      debug $
    ShowParameter 'Bianca'

    > Bianca

When followed immediately by an attribute name, that attribute of the first parameter in a
function. (It is not necessary to include the dot.)

    set ShowAttribute to task
      debug $name

    ShowAttribute friends[0]

    > Sara

Even if you use **given** to name your parameters, **$** continues to refer to the first parameter.

    set ShowParameters to task given p1, p2
      debug $
      debug p1
      debug p2

    ShowParameters 'First', 'Second'

    > First
    > First
    > Second



### $$ - _function arguments pseudo-array_ - keywords - ^$$

Equivalent to Javascript’s `arguments` and can be used the same way.

    .. $$

Best to refer to good documentation on this elsewhere.



### ${ } - _string composition_ - syntax - ^${ }

Allows the insertion of any arbitrary expression in the middle of a string literal.

    .. 'String ${ [expr] } continues.'    // single quote
    .. "String ${ [expr] } continues."    // double quote
    .. `String ${ [expr] } continues.     // backtick bareline
    .. '''                                // here document
      String ${ [expr] } continues.

As shown above, this is supported in all four string literal formats.

    set FriendSummary to task
      return 'Name: ${$name}, age: ${$age}'
    ply friends limit 3 as friend
      debug 'Subject ${key+1}: ${FriendSummary(friend)}'

    > Subject 1: Sara, age 23
    > Subject 2: John, age 19
    > Subject 3: Ellie, age 22

Use `\${` to represent `${` in a string literal.

    debug 'But I really need to include \${} in my output!'

    > But I really need to include ${} in my output!



### % - _modulus_ - operators - ^%

Calculates the mathematical **modulus**; returns the remainder of the left expression divided by the right.

    .. [expr] % [expr]

Examples:

    debug 5 % 2
    debug 6.2 % 1

    > 1
    > 0.2



### ' and " - _string literals_ - syntax - ^' and "

Declare a single line delimited literal string.

    .. 'Type your string literal here.'
    .. 'Use a backslash to escape ' and " and \ in your strings.'

String literals support embedded expressions (a.k.a. string compositions) using the
syntax: `${expr}`. Any normal expression can be evaluated and will be concatenated in-place.

Use backslash as an escape for string delimiters `\'` and `\"`, dollar signs
before braces `\${`, and the standard control characters `\n \r \t \b \f`.

    debug 'This here's ${'a'} test using \${} composition.'
    > This here's is a test using ${} composition.

Double quote is semantically identical to single quote..



### ''' - _multi-line string literal_ - syntax - ^'''

Declare a multi-line string ideal for embedding longer passages of markup.

    .. '''
      Many lines of text
        Some Indented
      Continuing until
      Indent resets
        on the line below this.
    ..

This is also known as a _here document_ as in "here's a document!"

    .. '''
      Now you can type as much text as you want,
      remembering that leading and trailing whitespace
      will be stripped, though newlines will be preserved.
      So it's perfect for markup.

      It will even keep track of your indenting, assigning
      column zero to the start of the first line.

      The string goes on as long as the indenting does.

      And you can include \${'compo'+'sitions'} as well.

That’s three single quotes in a row, then an indented block.

Blank lines, indentation and comments are preserved, unless the comment
is outside the left margin.



### 'd - _conversational syntax_ - syntax - ^'d

The _verb'd_. An alternate way of invoking a verb on an object.

    .. [verb]'d [object] (parameters)

Here are some functionally identical ways of writing the same thing:

    biglist.push item
    push'd biglist item

    debug name.toUpperCase()
    debug !name.toUpperCase
    debug toUpperCase'd name

The thing I find displeasing about the subject-first syntax is that it obscures the action taken.
When the action (the verb) is not foremost on the line, program flow is more difficult to discern.

You can use any number of indirections on the object to be verb'd:

    set index to join'd library\reference\category.titles '\n'

I find this much clearer than:

    set index !library\reference\category.titles.join '\n'

Because as you're reading the code, you see WHAT action will take place first, then you learn
the subject and object and how they relate to each other.  Hey if you don't like it,
don't use it.



### 's - _conversational syntax_ - syntax - ^'s

The _posessive_. An alternate way of referencing the attributes of an object.

    .. [value]'s [attribute]
    [object]'s verb

Equivalent to the use of `.` when accessing named attributes.

Functionally equivalent examples:

    set mixer's colour to 'red'
    set mixer.colour to 'red'
    set mixer['colour'] to 'red'

    set index !library\reference\category.titles
    set index !library\reference\category's titles

    if config.options.speedometer
    if config.options's speedometer
    if config's options.speedometer
    if config's options's speedometer

In that last set of four, there was probably one that most accurately represented how you
would think about the way configuration data is organized. Using a coding style that reflects
that mental representation helps you write maintainable code.



### ( ) - _parentheticals_ - syntax - ^( )

Parenthesis wrap expressions that should be evaluated together, and also invokes functions.

    .. verb(parameters)
    .. ( expression )
    .. ( expression [as identifier])

#### invoking functions with parenthesis

Use parenthesis after a value to invoke that value as a function, passing in the values within
the parenthesis as parameters to the function.

    set fs to require('fs')
    set angle to Math.atan2(y, x)

You don't use parenthesis when the verb is the first thing on the line:

    db.query(key)       // incorrect
    db.query key        // correct

You also don't use parenthesis when you're in the middle of a function chain:

    set lines to chain fs.readFileSync(fn,'utf8')
      split /[

]+/       // no parens
      | has .length > 0     // pipe operator

You can't easily use parenthesis when your function call spans multiple lines, in this case you'd
use the exclamation mark before the function name, instead of parenthesis after
(see the documentation for __!__ for more):

    return !textReplacer text, fields
      name db.name
      address db.address
      phone db.phone

Note these are all valid ways of writing the same functionally:

    set angle Math.atan2(y, x)      // invokes Math.atan2 with parameters y, x
    set angle atan2!Math y, x       // ditto
    set angle !Math.atan2 y, x      // ditto

#### controlling precedence with parenthesis

The much more useful way that parens are used is to control the precedence of operations.
For example, what the heck is the result of this statement:

    set f to 3 * 8 - 2 / 2 + 5

There are certainly RULES about how this would be evaluated; multiplication and division would be done first,
then addition and subtraction.  But who wants to have to think about that all the damn time?  And what if
your assumptions are wrong, or you are just too tired or rushed to get it right?

    set f to ( ( 3 * 8 ) - 2 ) / (2 + 5)

That's what parenthesis are for. My advice is: use them any time you have more than one operator in an
expression, unless the operators are all the same. And maybe even then. Always use them when you're
altering values in parameters.

#### using __as__ with parenthesis

The parenthetic **as** assigns the value of the parenthesised expression to a named identifier.
The assignment happens as soon as the parethesis is evaluated, so you can use the identifier
in the same expression as the parenthetical, as long as the parenthetical is evaluated first.
_This is not a good style of coding_.

    set six to (1+2 as three)+three
    debug array three, six

    > [ 3, 6 ]

Parenthetic __as__ seems like it might be evil but I believe its use can be justified if
done with care and caution.



### * - _multiplication_ - operators - ^*

Multiplies two expressions.

    .. [expr] * [expr]

As in:

    debug 2 * 3

    > 6



### ** - _exponentiation_ - operators - ^**

Raises one value to the power of another.

    .. [lexpr] ** [rexpr]

Calculates an exponent; equivalent to `Math.pow([lexpr],[rexpr])`.

    debug 2 ** 3

    > 8



### + - _addition / string concatenation_ - operators - ^+

summary

    .. [expr] + [expr]
    

Adds two numbers OR concatenates two strings.  If both expressions are numbers, adds them.
Otherwise converts them both to strings and concatenates.

    debug 1+2
    debug '1'+2
    debug 1+'2'
    debug '1'+'2'

    > 3
    > 12
    > 12
    > 12



### - - _subtraction/negation_ - operators - ^-

summary

    .. [lexpr] - [rexpr]
    .. - [expr]

Used as a binary operator, subtracts the right expression from the left.

    debug 3 - 5
    > -2

Used as a unary operator, negates the expression (subtracts it from 0).

    set b to 5
    debug 3 + -b
    > -2

SAI will not let you write the following;

    set a - 3

Because that could be parsed one of two ways:

 - place the value `-3` in the variable `a`
 - subtract `3` from the variable `a`

If you try to write code like this, a compiler error will result.  Choose one of these
formats instead:

    set a to -3    // store -3 in a
    set a self - 3  // subtract 3 from a

Just a little gotcha.



### . - _attribute lookup_ - syntax - ^.

Looks up the object trait named _attribute_ in the expression.

    .. [expression].[attribute]
    .. .[attribute]
    .. .[numeric array index]

This is a _literal_ dereferencing; the text of the attribute is used as the lookup.

    set friend to friends.0

    debug friend.name
    debug friend['name']
    with friend
      debug it.name
      debug .name

    // prints 'Sara' four times

When used without a leading value,
references the named attribute in the **it** pronoun.

Named attributes can also be referenced with `'s` because why not.



### .. - _pastes two related lines together_ - syntax - ^..

You can use the two-dot _caboose_ to stitch a *single line* child code block onto the end of the
statement that requires it.

    line 1 .. line 2

The following are functionally identical:

    if error
      return -1

    if error .. return -1

Don't use the caboose unless it will help make your code clearer.



### ... - _statement pasting operator_ - syntax - ^...

You can use the three-dot _continue_ syntax to insert line breaks, or multiple child code blocks,
into a single statement.

    first part of statement
      maybe other stuff
    ... continuing statement
      perhaps additional stuff
    ... and more of the statement.

This is not considered good practice (period), as most overly complex statements should be
broken down into multiple statements (period), just like a run-on sentence should be
clarified by a good editor.

But should you really need it, it is there.

The three dot continuation must start at the same indent as the line it continues.

    debug traits
      name Sally
      age 32
      province QC
    ... update traits
      #cat
      province ON

    > { name: 'Sally', age: 32, province: 'ON', cat: true }

Or even:

    debug 1
    ... +
    ... 2
    ... +
    ... 3

    > 6

Syntactically, the continue is equivalent to a whitespace character with a bonus ability
to reset level of indent.

One more time; if you find yourself tempted to use a continue, take a hard look at the code you're
writing and see if it can't be written more clearly. It's okay to use more lines of code.
It's okay to use temporary variable names for clarity. It's okay to create clear and simple
subroutines. All of these things make for more maintainable code.



### / - _mathematical division_ - operators - ^/

Divides the expression on the left by the expression on the right.

    .. [expr1] / [expr2]

As in:

    debug 22 / 7
    debug 355 / 113

    > 3.142857142857143
    > 3.1415929203539825



### // - _source code comment indicator_ - syntax - ^//

Two forward slashes indicate the start of a comment.

    // any text goes here, is ignored through the end of line.

Judicious comments that indicate _intent_ are a good idea. Commenting how everything works
minutely is not so good. If code function isn't clear, the code has a problem.

One gotcha with comments and ''' here documents:

    debug '''
      This is a here document
        // this is a comment line in the here document
      // and so is this
    // but this one is not in the document.
      and it ends here.

    > This is a here document
    >   // this is a comment line in the here document
    > // and so is this
    > and it ends here.

Comments WITHIN the indentation bounds of a here document are included in the document as text.

Comments OUTSIDE the indentation bounds are treated as true comments.



### 0b, 0o, 0x, and o - _binary, octal, hexadecimal and radian numeric literals_ - syntax - ^0b, 0o, 0x, and o

Numeric literals in different formats.

    binary: 0b0101010101
    octal: 0o01234567
    hexadecimal: 0x0123456789abcdef
    radians: 360o

Numeric literals in a variety of formats are to be encouraged as a way of more clearly showing
data values.

    debug 0b01011101
    debug 0o777
    debug 0xdeadbeef
    debug 180o

    > 93
    > 511
    > 3735928559
    > 3.141592653589793



### : - _create an array or object literal_ - syntax - ^:

The colon __:__ is used to begin the declaration of a data structure.

    .. : [expr] (, [expr], [expr], ...) (;)          // array
    
    .. :
      [expr] ( , [expr], ... )                       // array
     ( [expr], [expr], ...
       [expr]
       ... )
    
    .. : [name] [expr], [name] [expr], ... (;)       // object
    
    .. :
      [name] [expr] (, [name] [expr], ...)           // object
     ( [name] [expr], [name] [expr], ...
       [name] [expr]
       ... )
    

The **:** structure definition parser determines whether to create an array or fields by
whether or not a field name is included before the first expression.

    debug :1, 2, 3;

    debug:
      1, 2
      3

    debug :a 1, b 2, c 3;

    debug:
      a 1
      b 2
      c 3

    > [ 1, 2, 3 ]
    > [ 1, 2, 3 ]
    > { a: 1, b: 2, c: 3 }
    > { a: 1, b: 2, c: 3 }

The semicolon at the end of the inline variety is not required except for clarity. Which means
it's a _really good idea_ to use it if the structure isn't the only thing on the line.

Give the documentation entry for __;__ a read to understand why!



### ; - _structure definition closer_ - syntax - ^;

Optional, closes the current structure definition when needed for clarity.

    .. list a, b, c;
    .. array 1, 2, 3;
    .. traits a Apple, b Banana, c Cabbage;
    .. fields r colour.red, g colour.green, b colour.blue;
    .. :1, 1, 2, 3, 5, 8;
    .. :name 'Jane, age 45, city 'Halifax';

Only needed when there is additional code on the same line that might mistakenly
bind too tightly to the final value in the structure.

    debug list 3, 2, 1 | by it
    debug array 3, 2, 1 | by it
    debug array 3, 2, 1; | by it

    > [ 1, 2, 3 ]
    > [ 3, 2, 1 ] // undesired result
    > [ 1, 2, 3 ]

In the example above, the **list** literal sorts properly because **list** elements
are not allowed to be mathematical expressions, so the parser can correctly
bind `by it` to the entire list.

However, the first **array** literal _doesn’t_ sort correctly because array elements
can be expressions, and `by it` is binding to the final term in the literal. Thus, the
definition is parsed as `array (3), (2), (1 by it)`.

One can force **list** to parse incorrectly by using the **=** list element expression
evaluation flag, but that’s ridiculous.

    debug list =3, =2, =1 | by it   // don't write code like this
    debug list =3, =2, =1; | by it  // just don't

    > [ 3, 2, 1 ]
    > [ 1, 2, 3 ]

The semicolon can also close parameter lists if using the **from** form of function invocation. The following examples are identical:

    set x to ~Math.sin(angle) * magnitude
    set x !Math.sin angle; * magnitude



### < - _less comparison_ - operators - ^<

Evaluates **true** if lexpr is numerically or lexically lower than rexpr, **false** otherwise.

    .. [lexpr] < [rexpr]

For example:

    debug 1 < 1 // false
    debug 1 < 2 // true
    debug 'a' < 'b' // true
    debug 'a' < 'B' // false, case matters

If you want a case insensitive comparison, you must ensure both expressions are of the same case.



### <- - _calculation precedence modifier_ - syntax - ^<-

The _precedent_ operator, __<-__ ensures the expressions on the right is calculated before the expression on the left.

    .. [expr] [operator1] <- [expr] [operator2] [expr]

Useful when chaining operators of identical precedence, the after operator changes the order
of operations from left->right to right->left.  Effectively, the right side of the after operator
is wrapped in parenthesis.

    debug 1 - 2 - 3

More to write...



### << - _bitwise left shift_ - operators - ^<<

Convert the expression to a 32 bit integer, then perform a binary left shift bitcount times.

    .. [expr] << [bitcount]
    .. [expr] lsh [bitcount]   // synonym

See its synonym __lsh__.



### <= - _less or equal comparison_ - operators - ^<=

Evaluates to **true** if lexpr is numerically or lexically lower or equal to rexpr, **false** otherwise.

    .. [lexpr] <= [rexpr]

You know how this works.



### <=> - _comparison_ - operators - ^<=>

Evaluates to **-1** if lexpr is lower than rexpr, **1** if it is greater, and **0** if they are equal.

    .. [lexpr] <=> [rexpr]

For example:

    debug 1 <=> 0      // returns 1
    debug 1 <=> 1      // returns 0
    debug 1 <=> 2      // returns -1
    debug 'b' <=> 'a'  // returns 1
    debug 'b' <=> 'b'  // returns 0
    debug 'b' <=> 'c'  // returns -1

Useful in sorting operations!



### <> - _inequality comparison_ - operators - ^<>

Tests two values for value inequality.

    .. [expr] <> [expr]

Compares two values for value equality; returns **true** if the values appear to be the
same, **false** otherwise.

This is implemented with Javascript’s != operator and the behaviour is identical.

Contrast with **isnt**.



### = - _equality comparison_ - operators - ^=

Evaluates to **true** if the two expressions are equivalent.

    .. [expr] = [expr]

This compiles directly to Javascript’s `==` operator and has the same occasionally
bizarre side effects. Basically, don’t use = except for comparing numeric, boolean or string values.

Use **is** or **isnt** to compare objects or object types, except when dealing with **NaN** in which
case the only reliable way to test for its existence is to use **isNaN**. That’s Javascript for you.



### > - _greater comparison_ - operators - ^>

Evaluates **true** if lexpr is numerically or lexically greater than rexpr, **false** otherwise.

    .. [lexpr] > [rexpr]

For example:

    debug 1 > 1 // true
    debug 1 > 2 // false
    debug 'a' > 'b' // false
    debug 'a' > 'B' // true, case matters

If you want a case insensitive comparison, you must ensure both expressions are of the same case.



### >= - _greater or equal comparison_ - operators - ^>=

Evaluates **true** if lexpr is numerically or lexically greater than or equal to rexpr, **false** otherwise.

    .. [lexpr] >= [rexpr]

You know the drill.



### >> - _signed bitwise right shift_ - operators - ^>>

Convert the expression to a 32 bit signed integer, then shift it right bitcount times,
maintaining the sign of the expression.

    .. [expr] rsh [bitcount]
    .. [expr] >> [bitcount]   // synonym

See __rsh__.



### >>> - _unsigned bitwise right shift_ - operators - ^>>>

Convert the expression to a 32 bit unsigned integer, then shift it right bitcount times,
Zero bits are added on the left side (msb), which does not preserve negative sign.

    .. [expr] ursh [bitcount]
    .. [expr] >>> [bitcount]   // synonym

See __ursh__.



### ? - _safe fetch_ - syntax - ^?

Adds extra type-checking to an expression ensuring that it will not throw an exception if roots are
undefined; instead just returning **undefined**.

    .. ? [expr]

Here's why you want this sometimes:

    set a to undefined
    debug a.a
    // throws an exception

    debug ?a.a
    > undefined

Super helpful when building caches, for example.



### ?< - _minimum_ - operators - ^?<

Evaluates to whichever expression is numerically or lexically lower.

    .. [lexpr] ?< [rexpr]

Kind of like Math.min except as an operator.

    debug 1 ?< 2   // returns 1
    debug 2 ?< 1   // returns 1

Handy when you need it.



### ?> - _maximum_ - operators - ^?>

Evaluates to whichever expression is numerically or lexically higher.

    .. [lexpr] ?> [rexpr]

Kind of like Math.max except as an operator.

    debug 1 ?> 2   // returns 2
    debug 2 ?> 1   // returns 2

Of course it only operates on two values at a time. But that's cool.



### ?? :: - _trinary conditional_ - operators - ^?? ::

Evaluates to expr1 if the left expression is _truthy_, otherwise evaluates to expr2.

    .. [expr] ?? [expr1] :: [expr2]

I get the grar about the ?: operator, it can make for unclear logic.  But I've found
with this _doubled up_ version that it's much easier to see when it's used, especially
if you keep spaces on either side of the operators.

    debug true ?? 'True' :: 'False'   // prints 'True'
    debug false ?? 'True' :: 'False'  // prints 'False'

It's still kind of not great, but on the other hand there are times when five lines of code
could be reduced to one without losing much clarity. And those are the times for ??::.



### @ - _context-aware scoping prefix_ - syntax - ^@

Reference a trait or method attached to the current object. Equivalent to Javascript’s `this.`.

    .. @
    .. @attribute
    @Task [parameters]

Here's the thing. In SAI you almost never need to use @ (this). That is because the compiler
knows what your instance variables are. So it just assumes when you use the name of an instance
variable, that you mean _this_ instance.  If you want it to reference some other instance, use
the the dot accessor in the usual way.

Here’s a short implementation of a 2D vector by way of illustration.

    object Vector2 1.0.0

    instance:         // declare some member variables up front so the compiler knows what
      x 0             // we are doing. Also so that other programmers, like future you,
      y 0             // know what we are did.

    angle set given radians
      SetPolar radians, magnitude  // SetPolar is an instance method. No need for "@"
    get
      return !Math.atan2 y, x

    magnitude set given units
      SetPolar angle, units
    get
      return !Math.sqrt x*x + y*y

    Instantiate task given x, y
      // OH NO THIS IS A COMPILER ERROR because x and y are instance variables
      // and you can't use instance variable names as parameters.  Try again!
      // You also can't use them as renames for pronouns. The compiler tries very
      // hard to keep you from stepping on yourself.

    Instantiate task given px, py
      if px isof 'Vector2' // if we were passed an object
        set x to px.x     // copy its values.
        set y to px.y     // no "@" for our object, "px." for the other one.
      else
        set x to px
        set y to py

    SetXY task given px, py
      set x to px
      set y to py

    SetPolar task given radians, units
      set x to units * Math.cos(radians)
      set y to units * Math.sin(radians)

#### You need @ for inherited attributes

It's worth noting that you can use @ if you want to. And sometimes, you must.
You can avoid the user of @ for member variables/methods only on variables/methods defined
in the same source file. Inherited members must be referenced with @.

This was borne of laziness in writing the compiler BUT ALSO it has the interesting property
of making it explicit in the source code where the use of an object member is _inherited_ vs
when it is not.  So for the moment I'm happy that it's like this.

#### Advanced information

Internally, @ always points to a variable that has been _assigned_ from the JS value
of `this`. It doesn't reference `this.` directly. In ever member function definition of the compiled
JS object code, you'll see this bit of code in the local variable declarations:

    $ = this['Dedenter'] ? this : $bindfail('Dedenter')

This does a couple things -- first, it verifies the `this` object is actually a kind of object
we're expecting, that is, that the object has a member attribute that matches the function name.
(If not, it throws a "binding fail" message.)

But if the test is successful, the `this` value is
assigned to our work variable `$`. Whenever you use reference member attributes in your code,
you're actually referencing the attributes of the `$` variable, not of `this`.

This captures the instance that was active at the start of the function call. If we
did not do this, and just used `this.` then it is very likely that asynchronous callbacks to functions
defined in the method would lose their object context -- because _callbacks are almost always unbound_ from
an object.

So, instead of forcing you to use that ugly-ass `self` workaround, SAI just does the work for you and
always captures the `this` value, because it's really unlikely that you wouldn't want it to work this
way anyhow.

And if, in case, you did, you could use the __@@__ prefix, or the __orphan__ keyword.



### @@ - _context-ignoring scoping prefix_ - syntax - ^@@

Maps directly to Javascript's `this`, the context-ignorant object scope.

    .. @@
    .. @@attribute
    @@Task [parameters]

Used inside called functions to refer to the "this" object in the scope of the call,
rather than the scope of the function definition.

You can use the __orphan__ statement to force decontextualization of the usual
"this" scope. Have a look at that entry for info.



### [ ] - _attribute lookup_ - syntax - ^[ ]

Performs an indirect lookup of a trait/element in the given value.

    .. [value] '[' [expr] ']'

The following debug statements print identical results.

    set field to 'name'
    set friend to friends[0]

    debug friend.name
    debug friend['name']
    debug friend['na'+'me']
    debug friend[field]
    debug friend\field

    // prints 'Sara' five times.



### | - _pipe operator prefix_ - syntax - ^|

The pipe character is a scoping prefix for second-class operators defined with the _piper_ system.

    .. | [operator name] [clauses] ...

A note about order of operations.

Pipers are processed left-to-right, as if data were feeding through a series of tubes, or machines
that slurped up what's given on the left and spits it out to the next machine along the line or as the
result of the operation.

Be sure when you're coding that you're aware of the order of operations, especially in a set statement.
For example, this may not produce what you want:

    set a list 1, 2, 3
    set b list 4, 5, 6

    set a | concat b | thru it * 2
    debug a

    > [ 2, 4, 6, 8, 10, 12 ]

Were you expecting this:

    > [ 1, 2, 3, 8, 10, 12 ]

Keep in mind that the flow of data is left to right, and in a self-modifying __set__ statement
the assignment happens at the end. These are the same:

    set a | concat b | thru it * 2
    set a to a | concat b | thru it * 2

If you want that construct to work the other way, use parenthesis, or the "precedent" syntax:

    set a | concat ( b | thru it * 2 )
    set a | concat <- b | thru it * 2



### ~ - _global scoping prefix_ - syntax - ^~

Use `~` in front of an identifier to access an object defined globally, e.g. by the runtime environment.

    .. ~GlobalIdentifier

You must use `~` in each of the following examples:

    set validated to ~parseInt(raw)
    ~process.exit 1
    set attendees to new ~Set
    set func to new ~Function(arg1, src)

You do not need to use `~` on file-level pseudo-globals defined with `reference`; it is only required
for functions/values/objects that originate outside SAI.



### | ALL - _query a collection for all values_ - pipers - ^all

Checks a collection to see if it has _all_ of multiple values. If so, returns true.

    ... | all [expr]
    

The expression to the left is the _haystack_, it is where we are looking. The expression on the right is the
(set of) _needles_ that we are looking for.

The __all__ piper examines the haystack to see if it has _all_ of the needles. If so, it returns __true__.
Otherwise, it returns __undefined__.

Example:

    set menu list tortilla, bean, lettuce, rice, meat, sauce

    debug menu | any list tofu, avocado       // undefined
    debug menu | any list fish, meat          // undefined
    debug menu | any list rice, bean          // true

You can also test against a single value:

    debug menu | any 'bean'                   // 'bean'
    debug menu | any 'gelato'                 // undefined

#### Quirks

You can use iterators on either side. Iterators on the needle side are collected, so don't try to
needle with an infinite generator.

When the haystack is an object, its keys are examined, not values.

Using an object (or any scalar value) as the needle creates a test for _that object/value_.
as if you had placed the object/value in an array by itself.

No optimizations are made that require assumptions about the sortability of either haystack or
needles, so this function is slower at the expense of being robust. If none of the needles are
found in the haystack, every needle has been compared with every item in the haystack. It might
be faster in some cases to sort and search, but this function does not do that.



### | AND - _confirms a collection_ - pipers - ^and

Examines every item in a collection, returning the collection itself if all of them are _truthy_.

    ... | and  
    

For example:

    set t: 'horse', 9, true
    set f: 0, 'goat', 99

    debug t | and
    debug f | and

    > [ 'horse', 9, true ]
    > 0

Rules for source data:

- __undefined__: returns `undefined`.

- __value__: returns the value.

- __array__: returns _the array_ itself if _every_ element in the array is _truthy_,
otherwise returns the first _falsy_ element.

- __traits__: returns _the object_ itself if _every_ value in the object is _truthy_,
otherwise returns the first _falsy_ value.

- __iterable__: yields `true` if _every_ value returned by the iterator is _truthy_,
otherwise yields the first _falsy_ value. This _vill_ lock up on infinite _truthy_
generators as it will try forever to find a _falsy_ value.

If given an iterator, __and__ returns an iterator that will yield one value (or lock up).



### AND - _logical and_ - operators - ^and

Checks two or more values; if they're all _truthy_, return a _truthy_ value.
Otherwise returns a _falsy_ value.

    .. [expr] and [expr]
    .. and [list of expressions]

As a binary operator, if the left expression evaluates to **falsy**, returns it,
otherwise returns the right expression.

Binay operator examples:

    debug 1 and 0     // prints '0'
    debug 1 and false // prints 'false'
    debug 0 and 1     // prints '0'
    debug false and 1 // prints 'false'
    debug 1 and 1     // prints '1'

    debug true and 'Fred'
    > Fred

As a unary operator given a list, returns the right-most element of the list if all the
elements in the list are _truthy_, otherwise returns the first _falsy_ element.

Unary operator examples:

    debug and 'frog', 2, true
    debug and 'toad', false, 'mario'

    > true
    > false

The list can be split on more than one line, indented:

    debug and:
      'hello', true
      'this', 4, 88
      lookup('thing')

    > [ result of call to lookup ]

You can nest logical operators on multiple lines:

    debug and:
      or test1(2), test2(3)
      or fallback(1), fallback(2)

It can get very clunky to try and use multi-line logical expressions with IF statements.
Instead, assign the results of your test to a clearly named variable that describes your
test and then use that in your IF statement:

    set buildOk to and:
      fileExists(fn)
      fileDate(fn) > lastBuild\fn
      not alreadyBuilt\fn
      extensionhandler[PATH.extension(fn)]

    if buildOk as hdlr
      hdlr.build fn       // rule about AND: last element in the list if all are true.



### ANDB - _bitwise and_ - operators - ^andb

Bitwise and operator. Converts, if possible, both left and right expressions into 32 bit signed integers, and performs a bitwise AND operation on them.

    .. [expr] andb [expr]

Examples:

    debug 5 andb 11

    > 1

    //  5 in binary: 00000000000000000000000000000101
    // 11 in binary: 00000000000000000000000000001011
    //  1 in binary: 00000000000000000000000000000001



### | ANY - _query a collection for any of one-or-more values_ - pipers - ^any

Checks a collection to see if it has _any_ of multiple values. If so, returns the value it found first.

    ... | any [expr]
    

The expression to the left is the _haystack_, it is where we are looking. The expression on the right is the
(set of) _needles_ that we are looking for.

The __any__ piper examines the haystack to see if it has _any_ of the needles. If so, it returns the first
one it finds. Otherwise, it returns __undefined__.

Example:

    set menu list tortilla, bean, lettuce, rice, meat, sauce

    debug menu | any list tofu, avocado       // undefined
    debug menu | any list fish, meat          // 'meat'
    debug menu | any list rice, bean          // 'rice'

You can also test against a single value:

    debug menu | any 'bean'                   // 'bean'
    debug menu | any 'gelato'                 // undefined

#### Quirks

You can use iterators on either side. Iterators on the haystack side are collected, so don't try to
query with an infinite generator.

When the haystack is an object, its keys are examined, not values.

Using an object (or any scalar value) as the needle creates a test for _that object_
as if you had placed the object/value in an array by itself.

No optimizations are made that require assumptions about the sortability of either haystack or
needles, so this function is slower at the expense of being robust. If none of the needles are
found in the haystack, every needle has been compared with every item in the haystack. It might
be faster in some cases to sort and search, but this function does not do that.



### ARRAY - _expression-oriented list literal_ - keywords - ^array

Used to specify the creation of a plain array of mathematical values; e.g. the result of a series
of expressions. As opposed to **list**, which is a plain array of bare literals.

    .. array [expr], [expr], ... (;)
    .. array
      [expr], [expr], ...
      [expr]
      ...

In general, the **colon** structure constructor will figure out what you want, but when you want
to be specific about creating an array of expressions, use **array**. Compare with **list**,
**fields** and **traits**.

Arrays may be specified on one line:

    debug array 1+1, 2*3, 'Fred'

    > [ 2, 6, ‘Fred’ ]

Or multiple lines in the form of an indented block:

    debug array
      width * ~Math.cos(angle)
      height * ~Math.sin(angle)

    > [  7.0710678118654755, 3.5355339059327373 ]

Or a combination of both:

    debug array
      1, 1, 2, 5
      14, 42, 132, 429
      1430, 4862

When using an array literal in an expression that might make the end of the array a matter of question, use a **semicolon** to close the array literal:

    debug array 5, 3, 2, 7, 4; has it%2

    > [ 5, 3, 7 ]

Or enclose the array in parenthesis:

    debug (array  4, 3, 2, 1) by it

    > [ 1, 2, 3, 4 ]

Arrays can be nested by use of either parenthesis or semicolons, or by using multiple levels of indent. Note that commas separate expressions on one line but are not included at the end of a line.

    debug array
      array 1, 2, 3;, array 4, 5, 6
      array
        7, 8, 9

    > [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]



### AS - _pronoun renaming clause_ - keywords - ^as

As declares named locally scoped variables within a code block based on values passed into the block.
(In general, **as** is optional because one can usually access such passed-in values through pronouns.)

    .. [pipe operator] as var1, var2, etc...
    .. [construct] as var1, var2, etc...
    .. ( [expression] as var 1)

**As** can be used in conjunction with almost any SAI function that creates pronouns.  You use __as__ to
give those pronouns specific names, rather than the generic ones. Named pronouns are generally ephemeral.

    // incomplete list
    switch [expr] (as [trial var])
    catch (as [error var])
    if [expression] (as [trial var])
    exists [expression] (as [it var])
    with [expression] (as [it var])

An example of **if** value reclamation with **as**:

    if @keydown as charcode
      switch charcode
        case 27
          @Escape
        case 32
          @Continue

Every construct that can accept __as__ pronoun renaming will indicate this in the documentation.

#### as with iterators

    // incomplete list
    iterate [expr] (as [it var])
    each [expr] (as [it var] (, [key var] ) )
    ply [expr] (as [it ident] (, [key var] ) )
    count [expr] (as [counter var])

An example, renaming **it** and **key** in an each iterator:

    each friends first as value, field
      debug `${field}: ${value}

    > name: Sara
    > age: 23
    > cat: true
    > province: ON

#### as with comprehensions

    // incomplete list
    .. | by (as [a var], [b var] )
    .. | thru (as [it var] (, [key var] ) )
    .. | audit (as [it ident] (, [key var] ) )
    .. | into [expr] (as [sum var] (, [it var] (, [key var] ) ) )

An example, renaming **it** and **key** in the block handler of a **thru** comprehension:

    debug friends | thru as friend, index
      return `${index}) ${friend.name} lives in ${friend.province}

    > [ '0) Sara lives in ON',
        '1) Jon lives in QC',
        '2) Ellie lives in QC',
        '3) Marshal lives in ON',
        '4) Doug lives in ON',
        '5) Ann lives in QC',
        '6) Harry lives in QC',
        '7) Jenna lives in ON' ]

#### as parenthetic

    .. ( [expr] as [var] )

The parenthetic **as** assigns the value of the parenthesised expression to a named identifier. The assignment happens as soon as the parethesis is evaluated, so you can use the identifier in the same expression as the parenthetical, as long as the parenthetical is evaluated first.  _This is not a good style of coding_.

    set six to (1+2 as three)+three
    debug array three, six

    > [ 3, 6 ]



### ASC

_See: by_



### ASSERT - _run-time error checking_ - globals - ^assert

If the first expression is _falsy_, throw an exception with the second expression as a message.
Otherwise, return the expression.

    assert [test value], [error message]
    
    .. !assert [test value], [error message]

For example:

    assert everythingIsAwesome, 'I have some bad news...'

    > Error: SAI: failed assertion: I have some bad news...

You can use __assert__ in an expression, because it returns the value passed.

    set sock !assert GetSocket, "Could not obtain socket resource"

__Assert__, like __debug__, is functionality that can be redefined by passing a new handler
to SAI's configuration facility.



### | AUDIT - _observe the elements of a collection_ - pipers - ^audit

Audit is used to pass all values in a collection into an expression, code block or method.
Audit doesn’t alter the collection, it just observes all values and keys/indices going by.

    ... | audit [expr]
    ... | audit (AS var1, var2...) [indent code block]
    ... | audit USING [function reference]
    

For example:

    set b to chain fruit
      |observe debug('Pre-sort')
      |audit debug('Fruit #${key} is ${it}')
      |by desc
      |observe debug('Post-sort')
      |audit debug('Fruit #${key} is ${it}')
    debug b

    > Pre-sort
    > Fruit #0 is Apple
    > Fruit #1 is Banana
    > Fruit #2 is Citron
    > Post-sort
    > Fruit #0 is Citron
    > Fruit #1 is Banana
    > Fruit #2 is Apple
    > [ 'Citron', 'Banana', 'Apple’ ]

This example shows how one could add instrumentation to a process in a light-weight fashion.

Neither **observe** nor **audit** alter the chained data. _A side effect of this is that
**observe** can’t be used with non-reproducible iterators as it’s impossible to statically observe
an iterator without draining it._



### BIND - _function context binder_ - operators - ^bind

The __bind__ operator _binds_ a function reference to the current object context.

    .. bind [function reference]

This is useful when you need to pass in a member function to a callback, and need to ensure the
execution context (specifically, the _this_ object) isn't lost.

Why is this important?

    Object car
    instance: plate '876 ACET'
    CheckPlate task
      DB.lookupPlate plate, PlateResults
    PlateResults task given status
      debug 'Status for ${plate}: ${status}'

In the above function definition of `CheckPlate` the `DB.lookupPlate` function is an asynchronous
call with a plate number and a callback function. As written, when the callback is invoked,
`PlateResults` will have been unbound from its object; it is a function reference with no context.

The code will produce this result:

    Looking up 876 ACET
    Status for undefined: Valid

Although the test was successful, we have _lost context_ on the callback because `PlateResults`
is passed in as an unbound function. Referring to the member trait `plate` within an unbound context
produces an undefined result. In order to make this function reference work, we need to bind it to
the current object with the __bind__ operator, as follows:

    DB.lookupPlate plate, bind PlateResults

Now when we run the asynchronous function, it works as expected, because the callback has its context;
e.g. it knows where it is going (or, more accurately, where it is returning to).

    Looking up 876 ACET
    Status for 876 ACET: Valid

Note that __bind__ is only necessary when passing references to object member functions.
Functions you define in-place won't have this issue, as they create their own context.
This version of __bind__ only binds functions to the current object. If you want to bind a
function on some other object, you'd write code something like this, making use of the Function
object's bind ability:

    ... !anObject.anyFunction.bind anObject

SAI compiled objects do a runtime check on any member method invocation to verify that the
current execution context is, if not correct, at least not totally absent.



### BLANK - _an object with no traits_ - keywords - ^blank

The keyword **blank** creates a plain object with no traits.

    .. blank

It is the SAI equivalent of Javascript’s `{}`.

    set player to blank
    set player.age to 21
    debug player

    > { age: 21 }

Contrast __blank__ with __empty__.  A whiteboard can be blank; having nothing written on it.
You would not usually say it was empty.  While an array or a list is usually thought of as empty,
rather than blank.



### BREAK - _exit a loop or switch case_ - constructs - ^break

To exit a loop, iterator or switch case before its natural end, use the **break** keyword.

    break  
    

As in:

    ply collection
      unless FileExists(collection)
        break

or ..

    switch choice
    case 'exit'
      if exiting
        break
      set exiting true
      ...

or ...

    count 5
      debug it
      if it=2
        debug 'Nevermind...'
        break

    > 1
    > 2
    > Nevermind…



### | BY - _collection sorting_ - pipers - ^by

To create a sorted array, use **by**. The newly resulting array will be sorted by the specified
inline expression or code block.

    ... | by [expr]
    ... | by (AS var1, var2...) [indent code block]
    ... | by USING [function reference]
    ... | by  
    
    (optional) asc  
    
    (optional) desc  
    

**By** does not sort in-place; it always returns a new array.
If **by** is used on an iterable, it will **collect** all values before sorting.
If **by** is used on a true object, it will be converted to an array.

#### by inline

When you use the inline expression form, the provided expression is used to extract a
value from a single record, which is then compared against other records to determine the sort order.

The **it** pronoun and its **dot** scoping prefix are available within the expression.

Print a list of friends sorted alphabetically by name:

    set result to friends | by .name

    debug ( result | thru .name ).join(', ')

    > Ann, Doug, Ellie, Harry, Jenna, John, Marshal, Sara

You may sort by more than one value by adding another **by** clause. Multiple sort clauses
are handled the way a database would: if a clause provides no guidance (the values are
identical), subsequent clauses are each checked in turn.

Print sorted by length of name, then age:

    set result to friends | by .name.length by .age

    debug (result | thru '${.name}: ${.age}').join('\n')

    > Ann: 23
    > Doug: 18
    > John: 19
    > Sara: 23
    > Ellie: 22
    > Jenna: 28
    > Harry: 31
    > Marshal: 21

#### Sorting of objects by the property/key

In _inline_ expression sorting only, if your source collection is an object, you can use the __key__
pronoun as sort criteria, in addition to the __it__ pronoun and related accessors. The key is the
property name. In the example below, `rejections` is one of the keys in the folder object,
while `34` is its value.

    set folder:
      rejections 34
      acceptances 23
      pending 4
    debug folder | by key

    > [ 4, 23, 34 ]

As you can see, the key is discarded in the final array output.  If you need
different behaviour, you'll need to partition the task into simpler components, e.g. by using
__enlist__, __by__ and __thru__ in turn to preserve the data in the form you need.

Using __key__ as sort criteria on something that isn't an object will throw a runtime exception.

#### by block

When using **by** with a block of code, the pronouns change. You are given both records
under consideration just as you would using the Javascript `.sort` method. And
perhaps unsurprisingly to those who have ever seen a programming textbook, the pronouns
are the letters **a** and **b**.

Print a sorted list of ages by province:

    set result to friends | by
      return a.province <=> b.province or a.age <=> b.age

    debug (result | thru '${.name}: ${.province}, ${.age}').join('
')

    > Doug: ON, 18
    > John: ON, 19
    > Marshal: ON, 21
    > Sara: ON, 23
    > Jenna: ON, 28
    > Ellie: QC, 22
    > Ann: QC, 23
    > Harry: QC, 31

Note the __key__ pronoun is not available with block expression sorting.

#### by using

__By using__ provides the ability to use a named function for your
sorting facilitator.

    set ProvinceAge to task given a, b
     return a.province <=> b.province or a.age <=> b.age

    set result to friends | by using ProvinceAge

    // same result as previous example

#### desc (descending) _modifier_

    .. [expr] | by [expr] (desc)

Used with the **by** comprehension just like **asc** but the sort order will be highest to lowest.

    debug list Bob, Carol, Ted, Alice | by it desc

    > [ 'Ted', 'Carol', 'Bob', 'Alice' ]



### CALL - _function invocation_ - syntax - ^call

**Call** invokes the identifier as a function call that returns a value, passing in any parameters that follow.

    .. call [identifier] ([parameters]) (;)

This is a synonym for __from__ and will likely be what replaces it.



### CASE

_See: switch_



### CATCH

_See: promising, try_



### CHAIN - _verb chain initiation_ - keywords - ^chain

summary

    .. chain [expr]             // in an expression
      [comprehension/method]
      [comprehension/method]
      ...
    
    chain [expr]                // as a verb
      [comprehension/method]
      ...
    

The **chain** clause allows you to compose (string together) a series of operations that will
each be applied in turn to a value, object, collection or iterator.

**Chain** is another way of writing `value.method().method().method().method()` that offers cleaner
code and more possibilities. You start with an object, then apply a sequence of verbs to it. Each verb
is a new link in the chain.

    set mirror to task
      return chain $
        split ''
        reverse
        join ''
    debug mirror('A man, a plan, a canal, Panama!')

    > !amanaP ,lanac a ,nalp a ,nam A

In the previous case, each verb was a trait (a method) of the string itself.

You can also chain pipe operators:

      debug chain friends
        | has .cat
        | by .name
        | thru 'My friend ${.name} likes cats.'

      > [ 'My friend Ann likes cats.',
      >   'My friend Jon likes cats.',
      >   'My friend Sara likes cats.' ]

And because one of the pipers is **set**, you can actually chain any function at all.

    set double to task
      return chain empty
        concat $
        concat $

    debug chain fruit
      | set double(it)

    > [ 'Apple',
        'Banana',
        'Citron',
        'Apple',
        'Banana',
        'Citron' ]

Functions you use in **chain** typically return a value; this is used as the object to pass to
the next link in the chain. However, some methods and functions don't return a value, instead
modifying their context in-place. If a function returns **undefined**, **chain** will reuse the
previous object for the next call.

_Be careful: some built-in methods return unexpected values that can foil **chain**.
For example, **Array.push** is very irritating for this; you cannot chain **.push** because it
returns the new array length instead of either the array or **undefined**._

#### chain as a verb

You can also use `chain` as a verb, that is, at the beginning of a line. This is useful when the
end result of the chain isn't useful but the intermediate results are, which can often be the case
when parsing data.

    set population empty
    chain friends
      audit
        inc population[.province] to (self default 0) + 1
    debug population

    > [ ON: 4, QC: 4 ]

Arguably it might be better to code this particular example with a discrete iterator statement
like `ply`, but not every use case is as trivial as this example.

_Note: If you use chain as a verb in this way, and the final result of the chain is a generator,
it will be drained automatically._ Otherwise, the code within the chain may never be executed,
because without a drain, generators do nothing.



### | COLLECT - _collect values from an iterator into a static list_ - pipers - ^collect

If the expression on the left is an iterator, converts it to an array/list by draining
the iterator; otherwise do nothing. If the iterator never ends, your system will
lock up until you run out of memory. (You could use a **limit** comprehension to keep that from happening.)

    ... | collect  
    

Example:

    set Odds to process
      local i to 1
      while i
        yield i
        set i + 2

    debug Odds() | collect //           !!!! this locks up the computer

    debug Odds() | limit 10 | collect

    > [ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 ]

The opposite of **collect** is **iterate**. The difference between **enlist** and
**collect** is that collect will only transform an iterator, while **enlist** will
transform all values.



### | CONCAT - _assemble two collections into a single list_ - pipers - ^concat

A list operator, not a string operator, **concat** returns a list that consists of a copy of
set 1 followed by a copy of set 2. Set 1 is not modified, a new array or iterable is returned.

    ... | concat [expr]
    

Undefined values are ignored, and scalar values are promoted to single element arrays.

As follows:

    [1, 2] concat [3, 4] -> [1, 2, 3, 4]
    [1, 2] concat [[3, 4], [5, 6]] -> [1, 2, [3, 4], [5, 6]]
    [1, 2] concat 3 -> [1, 2, 3]
    [1, 2] concat {c:3, d:4} -> [1, 2, {c:3, d:4}]
    [1, 2] concat undef -> [1, 2]

    1 concat [3, 4] -> [1, 3, 4]
    1 concat 3 -> [1, 3]
    1 concat {c:3, d:4} -> [1, {c:3, d:4}]
    1 concat undef -> [1]

    {a:1, b:2} concat [3, 4] -> [{a:1, b:2}, 3, 4]
    {a:1, b:2} concat 3 -> [{a:1, b:2}, 3]
    {a:1, b:2} concat {c:3, d:4} -> [{a:1, b:2}, {c:3, d:4}]
    {a:1, b:2} concat undef -> [{a:1, b:2}]

    undef concat undef -> undef
    undef concat 3 -> [3]
    undef concat {c:3, d:4} -> [{c:3, d:4}]
    undef concat [3, 4] -> [3, 4]

If the first set is an iterable, **concat** will return an iterable, otherwise
it returns a list (draining the second list if it is an iterable).



### CONTINUE - _shortcut to the next iteration of a loop_ - constructs - ^continue

In a loop or otherwise iterating block of code, **continue** short-cuts the remaining code in
the block, causing the loop to continue its next iteration immediately.

    continue  
    

An example:

    count 10
      unless key % 2
        continue
      debug key

    > 1
    > 3
    > 5
    > 7
    > 9



### CONTRACT - _requirements for child objects_ - keywords - ^contract

When defining an object, **contract** is used to specify tasks or traits that _children_ inheriting
from this object are intended to implement.

    contract:
      [task/trait name]
      [task/trait name]
      ...

Inheriting from an object that has contracts, and then not providing implementations for those contracts,
will result in a SAI exception.

    object fruit
    contract:
      Consume

    object apple
    inherit:
     fruit
    Consume task
      debug 'You ate an apple.'

    object pear
    inherit:
      fruit

    > exception thrown: “SAI: Contractually required task ‘Consume’ does not exist in object ‘pear’.”



### COPY - _shallow copy_ - operators - ^copy

Use the **copy** unary operator to create a _shallow copy_ of the expression it precedes.

    .. copy [expr]

You sometimes need this because ordinarily SAI and Javascript assign objects, rather than copies
of object values.

    set plate to fruit       // i want some fruit
    plate.push 'Ice cream'   // and also dessert
    debug fruit              // but now fruit has changed

    > [ 'Apple', 'Banana', 'Citron', 'Ice Cream' ]

    fruit.pop                 // get rid of the ice cream
    debug fruit

    > [ 'Apple', 'Banana', 'Citron' ]

    set plate to copy fruit
    plate.push 'Ice cream'
    debug fruit

    > [ 'Apple', 'Banana', 'Citron' ]

    debug plate               // there we go

    > [ 'Apple', 'Banana', 'Citron', 'Ice Cream' ]

Note that **copy** only copies enumerable attributes. There's a rabbit hole for ya.



### COUNT - _numerically controlled looping_ - constructs - ^count

In this most basic kind of loop, a block of code is executed a certain number of times with a counter
keeping track of iteration count. More complexity is available if needed.

    count [expr1 (, expr2, ...)] (AS var1, var2, ...) [indent code block]
    
    else [indent code block]
    

Specifically designed as an integer iterator for list elements, **count** always counts 1 at a time
(unless a **step** value is provided), and its highest value is always the step value less than the
high value provided (both when counting up and down).

To reiterate, **count** _never_ outputs the high value.

Variants:

    count [low expr], [high expr] ( as [counter ident] )
    count [low expr], [high expr], [step amount expr] ( as [counter ident] )

    countdown [high expr] ( as [counter ident] )
    countdown [high expr], [low expr] ( as [counter ident])
    countdown [high expr], [low expr],  [step expr] ( as [counter ident])

**Count** uses the pronoun **counter** for the value.

    count 10
      debug counter
    .. counts from 0 to 9

    count 5, 10
    ... numbers 5 to 9

    countdown 10 as i
    ... numbers from 9 to 0

    countdown 25, 15
    ... numbers 24 to 15

    count 0, 50, 10
    ... 0, 10, 20, 30, 40

    countdown 45, 0, -10
    ... 35, 25, 15, 5

When using a step with **count down**, be sure that the step expression is negative, otherwise an infinite loop will result.

    count aList.length
      debug 'List element ${counter} is ${aList[counter]}'
    else
      debug 'The list is empty.'

The optional **else** clause is executed instead of the main block if the **count** range length computes to 0 (or less).

You can use __break__ to exit out of the loop prematurely, and __continue__ to shortcut to the start.
See the documentation on these terms for more.



### | COUNT - _collection item count_ - pipers - ^count

Returns the number of elements in the collection.

    ... | count  
    

If the collection is an iterator, it will be drained.

    debug undefined count
    debug 1 count
    debug fruit count

    > 0
    > 1
    > 3



### COUNTDOWN - _numerically controlled looping in reverse_ - constructs - ^countdown

Very similar to __count__ except that __countdown__ is designed to operate with a negative step. That is,
the first value will be higher than the last value.

    countdown [expr1 (, expr2, ...)] (AS var1, var2, ...) [indent code block]
    
    else [indent code block]
    

See the entry for __count__ for details.



### COUNTER - _pronount for integer-based loops_ - pronouns - ^counter

A partner to **count**, **counter** is a _pronoun_, populated by the **count** iterator,
if no other variable is specified in an **as** clause.

    .. counter

Like all pronouns, **counter** is only visible in attached expressions or code blocks, not in
any functions that may be called within those expressions.

An example:

    count friends.length
      debug counter

Similar to **it** in nested contexts, you are unable to access “outer” values of **counter** within
inner contexts unless you assign them to a name other than **counter** using the **as** clause.

    count 3
      count 3
        debug counter
        // only the inner loop's 'counter' is visible here.

    // prints 0 1 2 0 1 2 0 1 2

    count 3 as i
      count 3
        debug i+','+counter
        // outer loop's 'counter' now available here as 'i'

    // prints 0,0  0,1  0,2  1,0  1,1  1,2  2,0  2,1  2,2

    count 3
      count 3 as j
        debug counter+','+j
        // no, this doesn't work, you still can't access the outer 'counter'
        // 'counter' always has the value of the innermost context

    // prints 0,0  1,1  2,2  0,0  1,1  2,2  0,0  1,1  2,2



### CREATE - _object creation_ - operators - ^create

Creates a SAI object by name.

    .. create [expr] [parameters]

If we are running in dynamic mode (that is, with source that is being dynamically compiled from
.SAI files), __create__ will attempt to find the object’s source by using the `SAI.config.Loader` function,
which defaults to `SAI.GetSourceFromPaths`, which tries to find a file named `[expr].sai` i
n the provided paths.

In runtime mode (that is, when running from plain Javascript .js files that have been pre-compiled),
__create__ will call `require`, but do see the source in the `sai-library` that discusses this.

    reference:
      Tally 'Tally ^1.0.0'
    ..

    set inventory to create Tally

The example follows best practices of placing object names in a **reference** section, aliasing
versioned names into literals.

See also __new__, which is a direct link to Javascript's `new`, and __singleton__, which works
like __create__ except instantiates the object only once in the scope of the runtime library; subsequent
calls will return that same object.



### DEBUG - _print diagnostics to the console_ - globals - ^debug

Prints the value of the expression to the console.

    debug [expr]

Compiles to a call to $AI.debug_op in `sai-library`, which you can hook to provide your own
implementation.

In the default implementation, just calls `console.log` with the provided value.

    debug "this is a test"

    > this is a test



### DEC - _decrement verb_ - keywords - ^dec

Decrements (reduces by 1) the value in the given variable.

    dec [var]

Example:

  set a to 2
  dec a
  debug a

  > 1



### DEFAULT - _variable initialization_ - operators - ^default

Examines the expression on the left; if it has a value, returns it. Otherwise returns the value on the right.

    ... [lexpr] default [rexpr]
    set [lexpr] default [rexpr]

#### default in expressions

If and only if the left expression evaluates to `undefined`, returns the right expression, otherwise
returns the left expression.

Like **or** except instead of checking for _truthy_ tests to see if a value is present.
Most useful in expressions where you’re not sure if a variable is initialized.

    set
      magnitude to undefined
      angle to 60o
    debug (magnitude default 1) * ~Math.cos(angle)

    > 0.5

#### default in **set** statements

If the left expression is `undefined` then evaluate the right expression and assign it to the left
expression. For example:

    set calculationCache[key] default ExpensiveCalculation(key)

This checks to see if the calculation cache has a value for the given key, and if not,
calculates the value and assigns it to the cache.



### DELETE - _a verb that deletes variables_ - keywords - ^delete

summary

    delete [variable]

When called on a variable or traits, undefines the named variable or attribute(s) of a variable.

    delete thisUnwantedValue
    delete goodObject.unwantedAttribute

This just calls the underlying Javascript version of **delete**, with all the same rules and caveats.

#### delete pipe operator

The __delete__ pipe operator has advanced functionality, which see.



### | DELETE - _multi-attribute removal_ - pipers - ^delete

Returns a copy of the collection with the specified attributes removed.
Elements in an array are removed in order, so sequence does matter.

    ... | delete [expr]
    

Examples

    set obj to: a 1, b 2, c 3, d 4, e 5, f 6
    set obj delete 'a'
    debug obj

    > { b: 2, c: 3, d: 4, e: 5, f: 6 }

    set obj delete: 'c', 'f'
    debug obj

    > { b: 2, d: 4, e: 5 }

    set obj delete: b 'B is for Bonobo.', d 'D is for Dixie cups.'
    debug obj

    > { e: 5 }

When **delete** operates on an array, it returns a copy of the array with the elements specified removed.

    debug (list 1,2,3,4,5) delete 1

    > 1, 3, 4, 5

    debug (list 1,2,3,4,5) delete (list 1,2)

    > 1, 3, 5

Elements are removed in first->last order, so sequence does matter.

    debug (list 1,2,3,4,5) delete (list 2,1)

    > 1, 4, 5

__delete__ is also a first-class keyword used for undefining variables entirely. Please review
the related entry in the keywords documentation.



### DESC

_See: by_



### DOUNTIL - _until variant that always executes the loop once_ - constructs - ^dountil

Functions just like the __until__ loop, except that the block of code is always executed once _first_,
before the test.

    dountil [expr] (AS var1, var2...) [indent code block]
    

I could duplicate text here or just refer you to __dowhile__ and __while__.  Which would you like?



### DOWHILE - _while variant that always executes the loop once_ - constructs - ^dowhile

Functions just like the __while__ loop, except that the block of code is always executed once _first_,
before the test.

    dowhile [expr] (AS var1, var2...) [indent code block]
    

Check out these wacky examples.

    dountil true
      debug 'Hello, World!'

    dowhile false
      debug 'Hello, World!'

Note there's no space in there. It's __dowhile__ and __dountil__. Makes parsing easier when it's one word.

You can use __break__ to exit out of the loop prematurely, and __continue__ to shortcut to the start.
See the documentation on these terms for more.  See __while__ for more.



### EACH - _object attribute enumeration_ - constructs - ^each

**Each** uses Javascript's `for-in` loop construct to iterate through an object's
enumerable properties. It steps through each element of the collection, in arbitrary
order, setting **it** and **key** variables, and executing the code block for each one.
If the collection is empty, executes the (optional) **else** block instead.

    each [expr] USING [function reference]
    each [expr] (AS var1, var2...) [indent code block]
    
    else [indent code block]
    

Example:

    set friend to friends | first
    each friend
      debug `${key}: ${it}
    else
      debug `You have no friends.

    > name: Jon
    > age: 19
    > cat: true
    > dog: true
    > province: QC

Recall that you can rename **it** and **key** with the **as** clause:

    each friend as value, field
      debug `${field}: ${value}

#### each ... using

**Each** can also call out to a function with the **each using** variation.

    set handler to task given value, field, collection
      debug `${field}: ${value}

    each friend using handler

The function is called for each attribute of the collection with three parameters:

 - attribute value (e.g. __it__)
 - attribute name (e.g. __key__)
 - reference to the collection itself

You can use __break__ to exit out of the loop prematurely, and __continue__ to shortcut to the start.
See the documentation on these terms for more.



### ELSE

_See: every, iterate, each, index, ply, count, countdown, if, unless, exists, switch_



### ELSEXISTS

_See: if, unless, exists_



### ELSIF

_See: if, unless, exists_



### ELSUNLESS

_See: if, unless, exists_



### EMPTY - _an array with no items_ - keywords - ^empty

A literal value indicating an empty list/array.

    .. empty

The equivalent of Javascript’s `[]`, **empty** creates an Array with no elements.

    debug empty
    debug empty.length

    > []
    > 0



### | ENKEY - _convert a list/iterator into a set of traits_ - pipers - ^enkey

__Enkey__ transforms a list into an object (set of traits) by turning each value in the list
into a trait with the value of `true`.

    ... | enkey  
    ... | enkey [expr]
    

This is similar to __entrait__ except that instead of assuming the source list has
embedded key/value pairs, the source list is used for the keys only, and the value is
either `true` or some other expression that is calculated.

Examples:

    set a list a, b, c
    set a | enkey
    debug a

    > { 'a': true, 'b': true, 'c': true }

    set a list a, b, c
    set a | enkey '${it.toUpperCase()}${key}'
    > { 'a': 'A0', 'b': 'B1', 'c': 'C2' }

Dry, but very useful.



### | ENLIST - _convert a collection to an array_ - pipers - ^enlist

Converts various collection types into a list/array such that it should be possible to
reverse the transformation later without losing data.

    ... | enlist  
    

Here are the basic rules:

    undefined -> undefined
    value -> [ value ]
    list -> self
    object -> [ [ key, value ], [ key, value ], ... ]
    iterable -> [ value, value, value, ... ]

Note specifically that **enlist** will turn a set of key, value pairs into an array
of [key,value] arrays thus no data is lost in the conversion.

    set data to:
      cats 7
      dogs 12

    debug data
    debug data | enlist

    > { cats: 7, dogs: 12 }
    > [ [ 'cats', 7 ], [ 'dogs', 12 ] ]

Such a result can be turned back into traits with **entrait**.

The difference between **enlist** and **collect** is that **enlist** will always transform its
source data into an array/list, while **collect** will only transform an iterator.



### | ENTRAIT - _convert collections to object/traits_ - pipers - ^entrait

Converts various collection types into traits/fields using rules that allow the
transformation to be reversed later without losing data.

    ... | entrait  
    

Here are the rules:

    undefined -> undefined
    value -> { value: true }
    list -> { [0][0]: [0][1], [1][0]: [1][1], ... }
    object -> self
    iterable -> { first[0]: first[1], next[0]: next[1]... }

**Entrait** is designed primarily to losslessly restore the results of enlist and iterators
that produce arrays of key/value pairs.

    debug 'Coyote' | entrait

    > { Coyote: true }

    set data to:
      list cats, 7
      list dogs, 12

    debug data
    debug data | entrait

    > [ [ 'cats', 7 ], [ 'dogs', 12 ] ]
    > { cats: 7, dogs: 12 }

**Entrait** ignores input data that does not conform to expectations; if given a list that
does not contain two-element key/value lists, it will not create traits.

You could, however, use **enkey** to transform this data:

     debug fruit | enkey

     > { Apple: true, Banana: true, Citron: true, Durian: true }



### ENUM - _literal number enumeration_ - keywords - ^enum

A convenience tool for initializing objects with sequential values.

    fields [identifier] enum, ( [identifier] enum, ... )

When declaring a set of fields, specifies a value 1 higher than the value of the previous
definition. If there is no previous definition, 1.

  debug fields a enum, b enum, c 10, d enum

  > { a: 1, b: 2, c:10, d: 11}



### ENVIRONMENT - _return SAI runtime environment information_ - globals - ^environment

Call the __environment__ function to gain information about the runtime state of your SAI module.

    .. set env to environment()

The __environment__ function returns different things based on whether your module is running
in static or dynamic mode.

In static mode (when you're running from a pre-compiled `.js` script), you get this:

    fields
      dynamic (false)
      static (true)

In dynamic mode (when you're using the `sai-language` package to compile on the fly), you get this:

    fields
      dynamic (true)
      static (false)
      paths (array)                             // array of paths searched dring CREATE

      Clean (function)                          // reset the compiler environment
      Configure (function)                      // e.g. change paths, etc
      GetSource (function)                      // return full JS source for a SAI object by name
      RegisterWithNode (function)               // theoretically register .sai with node's require
      Require (function)                        // a version of require that uses SAI's paths, not node's



### ERROR - _catch pronoun_ - pronouns - ^error

summary

    .. error

Valid only within the **catch** exception handler clause of a **try/catch/finally** construct. Receives the exception thrown.

    try
      noFunction
    catch
      debug error

    > [TypeError: undefined is not a function]

You can override this behaviour by using an **as** clause with the **catch** statement:

    try
      noFunction
    catch as e
      debug e

    > [TypeError: undefined is not a function]



### EVERY - _general-purpose collection iterator_ - constructs - ^every

**Every** is a general-purpose iterator that can handle any collection -- array, object or iterable -- or a even single value (which case it executes the block once).

    every [expr] USING [function reference]
    every [expr] (AS var1, var2...) [indent code block]
    
    else [indent code block]
    

__Every__ steps through each element of the collection, in order if possible (array, iterable), in
random order otherwise (objects), setting **it** and **key** pronouns, and executing the code block.

The **key** pronoun will be the index number for arrays, the attribute name for objects, or a row
counter for iterables. It will be `0` for the single pass granted a single value.

If the collection is empty, executes the (optional) **else** block instead.

    set friend to friends first
    every friend
      debug `${key}: ${it}
    else
      debug `You have no friends.

    > name: Jon
    > age: 19
    > cat: true
    > dog: true
    > province: QC

Recall that you can rename **it** and **key** with the **as** clause:

    every friend as value, fieldname
      debug `${fieldname}: ${value}


_Note:_ there is a slight performance penalty associated with using __every__ instead of a more specific iterator, as SAI must wrap the collection in a thin iteration in order to generically handle all cases. It is, however, very useful when you are not sure what kind of collection you'll be working with.

#### every ... using

**Every** can also call out to a function with the **every ... using** variation.

    set handler to task given value, field
      debug `${field}: ${value}

    every friend using handler

The function is called for each attribute of the collection with two parameters:

   - attribute value (e.g. __it__)
   - attribute name (e.g. __key__)

You can use __break__ to exit out of the loop prematurely, and __continue__ to shortcut to the start.
See the documentation on these terms for more.



### EXISTS - _conditional flow control_ - constructs - ^exists

If the expression is _not_ __undefined__, the code directly after the **exists** is executed.
Otherwise, perform additional tests if specified by any **elsif**, **elsexists** or **elsunless** clauses,
or failing those, perform the code after the optional **else** clause.

    exists [expr] (AS var1, var2...) [indent code block]
    
    elsif [expr] (AS var1, var2...) [indent code block]
    
    elsunless [expr] (AS var1, var2...) [indent code block]
    
    elsexists [expr] (AS var1, var2...) [indent code block]
    
    else [indent code block]
    

See __if__ for more details on th if/exists/unless constructions.

The only thing that does _not_ exist are things that are __undefined__.

( the following information should be in the EXISTS keyword )

However, there is an annoying trick. You can set a variable's value to __undefined__,
in which case the variable
technically exists, it is just the _value_ of the variable that is undefined.

    debug newvar
    > undefined
    debug newvar.attribute
    // throws an error, can't look up an attribute on an undefined value

    set newvar blank
    debug newvar
    > {}
    debug newvar.attribute
    > undefined

    set newvar.attribute 'a value'
    debug newvar.attribute
    > a value

    set newvar.attribute undefined
    debug newvar.attribute
    > undefined

    debug newvar
    > { 'attribute': undefined }

If you want to differentiate between an attribute that is not there
and one that is there but holds the __undefined__ value, use `.hasOwnProperty` as follows

    debug newvar.attribute
    > undefined
    debug newvar.hasOwnProperty('attribute')
    > true

    delete newvar.attribute

    debug newvar.attribute
    > undefined
    debug newvar.hasOwnProperty('attribute')
    > false



### EXISTS - _check for undefined_ - keywords - ^exists

Returns true if the following expression is _not_ `undefined`.

    .. exists [expr]

These three comparisons test the same thing and have the same effect:

    if undefined isnt var
      ...
    if exists var    // unary operator
      ...
    exists var       // flow control construct
      ...

The unary operator can be used in expressions, e.g.

    unless exists .name and exists .age
      return: error "Name and age are required."



### | EXPECTS - _rule enforcer for traits_ - pipers - ^expects

Expects compares an object againt a set of rules and returns a list of rules
that are **violated**. Thus, a successful test of expectations is an empty array.
An array with one or more elements is returned that contains a list of the
rules that were broken.

    ... | expects [expr]
    

In first-class usage as a keyword, __expects__ is used to check whether a function’s named parameters
(or any arbitrary object) has certain traits, and optionally if those traits are of a particular type.
For more on this, review the keywords documentation.

For use as a piper, __expects__ compares an object againt a set of rules and returns a list of rules
that are **violated**. Thus, a successful test of expectations is an empty array. An array with one
or more elements contains a list of the rules that were broken.

#### expects rules

Rules for **expects** take the form of a set of traits. Their names correspond to names of traits
that must be found in the expression under test. The value, if not _true_, is interpreted as an
object type; the trait must be of that type (or a child of that type).

Any violations to the rules are returned in a list; that list being made up of plain objects
with the following fields:

    .trait - name expected
    .expects - type expected
    .found - type found

Here are some examples, first as a keyword

    AddStudent task expects $name string, $age number
      @students.push copy $
    ..
    @AddStudent name 'Sally', age '12'

    > Error: SAI: parameter exception in AddStudent
    > age should be number, but it's string

Performing this same test in an ad-hoc fashion using the **expects** operator would look like this:

    set newStudent to: name 'Sally', age '12'
    set studentRules to: name 'string', age 'number'
    debug newStudent expects studentRules

    > [ { trait: 'age', expects: 'number', found: 'string' } ]

N.B. the **expects** clause rule format is identical to that of a single-line **traits** definition, with the additional requirement of a **$** before every trait name.



### EXPECTS - _runtime paramater type validation_ - keywords - ^expects

Used to check whether a function’s named parameters (or any arbitrary object) has certain
traits, and optionally if those traits are of a particular type.

    ... task/promise/process expects [rules definition]

When used as the clause in a **task**, **promise** or **process** function definition. **expects**
adds run-time parameter checking to the function, passing the first argument (the one that holds
named parameters) through an *expects check* based on the rules that follow. If any expectations
are not met, a runtime error is thrown.

Names appearing in **expects** clauses, and thus being used to check parameters, _must_ be
preceeded by **$**. This is intended as a reminder that *named parameters are always
referenced with the $ scoping operator*.

#### expects rules

Rules for **expects** take the form of a set of traits. Their names correspond to names of
traits that must be found in the expression under test. The value, if not _true_, is interpreted
as an object type; the trait must be of that type (or a child of that type).

Any violations to the rules in a function call results in an error being thrown describing the problem.

Here's an example:

    AddStudent task expects $name string, $age number
      @students.push copy $
    ..
    @AddStudent name 'Sally', age '12'

    > Error: SAI: parameter exception in AddStudent
    > age should be number, but it's string

Expects adds a small amount of overhead at runtime. My thinking is that it would be good for integration
testing but during a production build the checks would be commented out, like one might do with assertions.
This would be a nice option to add to the SAI compiler someday.



### FALSE - _boolean value false_ - keywords - ^false

This is the `false` value.

    .. false

The opposite of __true__.



### FIELDS - _structure literal_ - keywords - ^fields

Used to specify the creation of a plain object with a set of key/value pairs. (Contrast with **traits**.)

    .. fields [key] [expr], [key] [expr], ... (;)
    .. fields
      [key] [expr], [key] [expr], ...
      [key] [expr]
      ...

In general, the **colon** structure constructor will figure out what you want, but when you want to be
specific about creating a plain object with of keyed values & expressions, use **fields**. Compare
with **list**, **array** and **traits**.

The **key** is an identifying word or other string, specified without quotes (although quotes may be used
if desired/necessary). If a **#** preceeds the key (a hashtag), the key will be assigned a
value of **true**. The **expr** is any valid literal, variable, object or expression.

Fields may be specified on one line:

    fields name 'Sera', class 'Rogue', level 21, #focus

    > { class: 'Rogue', level: 21, name: 'Sera', focus: true }

Or multiple lines in the form of an indented block:

    fields
      x width * ~Math.cos(angle)
      y height * ~Math.sin(angle)

    > { x: 0.5, y: 0.866 }

Or a combination of both:

    fields
      str 16, dex 34, mag 14   // no comma at end of line
      con 42, wil 21, cun 45

    > { str: 16, dex: 34, mag: 14, con: 42, wil: 21, cun: 45 }

When using a fields literal in an expression that might make the end of the literal a matter of question,
use a **semicolon** to close the literal, or enclose it in parenthesis:

    fields x 5, y 4, z 3; thru it*2
    (fields x 5, y 4, z 3) thru it *2

    > { x: 10, y: 8, z: 6 }

Fields initializers can be nested by use of either parenthesis or semicolons, or by using multiple
levels of indent.



### FINALIZED

_See: promising_



### FINALLY

_See: promising, try_



### | FIRST - _first value_ - pipers - ^first

Returns the first value in a list or iterator. With an expression, block or function, returns the
first value where the expression is true.

    ... | first  
    ... | first [expr]
    ... | first (AS var1, var2...) [indent code block]
    ... | first USING [function reference]
    

Example:

    debug fruit | first
    > Apple

__First__ doesn't just crop the array, it unwraps whatever value is there, as
if you'd coded `array.[0]`. __First__ unwraps iterators, returning a single
value (or undefined). If you need the iteration chain preserved, use __limit__ (in combination with
__has__ if necessary).

#### First with a comparison

If you provide a comparison expression, block, or function, __first__ will evaluate the comparison
against each element in the collection, and return the first value that the comparison returns true.
If you use __first__ on an object, the order of comparisons is undefined.

Example:

    set fruit list Apple, Banana, Cherry, Durian

    debug fruit | first .length is 6      // Banana



### FROM - _function invocation_ - syntax - ^from

**From** invokes the identifier as a function call that returns a value, passing in any parameters that follow.

    .. from [identifier] ([parameters]) (;)

It is the preferred syntax for function calls that include indents, as it is difficult to close a parenthesis.

The following calls are synonymous:

    set record !cursor.FetchRow
    set record from cursor.FetchRow
    set record to cursor.FetchRow()

    set cursor !db.Query 'select * from names'
    set cursor from db.Query 'select * from names'
    set cursor to db.Query('select * from names')

**From** is the encouraged form for **set** statements because it allows a more natural reading of source code. __From__ indicates that the identifier that follows will be used as a verb and returning a value.

Neither **From** nor parenthesis are needed when the verb begins the line as in the `cursor.Close` statement below.

    set cursor from db.Query 'select * from names'
    set records from cursor.FetchAll
    cursor.Close

If you wish to use **from** in a continuing expression, close the parameter clause with a semicolon (like you'd close a structural literal). The following two examples are equivalent.

    set @x to Math.sin($angle) * $magnitude
    set @x from Math.sin $angle; * $magnitude

Both __from__ and __!__ (bang) do the same thing.



### GET - _dynamic object attribute_ - keywords - ^get

Declares a _getter_ for a dynamic object trait; that is, a trait that has a value that is only
calculated upon request.

    object [name] [version]
    
    [ident] get
      [code]
      return [value]
    ( set ( given [ident] )
      [code]

A brief example:

    object Vector2 1.0.0

    magnitude get     // dynamic getter for 'magnitude' trait
      return Math.sqrt(x*x + y*y)
    set given m       // dynamic setter for 'magnitude' trait
      set a to angle
      set x to m * Math.cos(a)
      set y to m * Math.sin(a)

You can have a getter without a setter, and a setter without a getter.

    documentation get
      return '''
        Lots of information about this object.

    tally set given token
      inc _tally	oken



### GIVEN - _parameter declaration and static values_ - keywords - ^given

Use __given__ to name the parameters to a function, and to define immutable traits.

    .. given p1, p2, p3 ...
    
      - or -
    
    [ object declaration ]
    given [definition of values]

To declare parameters:

    set [ident] (given [$ var]) // dynamic trait
    .. task (given [parameter1], [parameter2], ...)
    .. process (given [parameter1], [parameter2], ...)
    .. promise (given [parameter1], [parameter2], ...)

An example of parameter naming:

    set tally to blank
    set AddRow to task given item, quantity
      set tally[item] to (self default 0) + quantity

    AddRow 'socks', 3
    AddRow 'pants', 6
    debug tally

    > { socks: 3, pants: 6 }

#### given object constants

Defines immutable traits when declaring an object. These traits are assigned to the object prototype
itself and locked/frozen; they cannot be changed and yet are available in every instance of an
object. Givens are useful for static data.

    object Apple
    instance: varietal 'unknown'
    given: species 'M. domestica'
    Describe task
      return 'undefined var undefined
    ..
    set apple to create 'Apple'
    set apple.varietal to 'Macintosh'
    debug !apple.Describe
    > M. domestica var Macintosh

**Given** traits can only be changed/overridden through inheritance.

    object Crabapple
    inherit: Apple
    given: species 'M. coronaria'
    ..
    set specimen to create 'Crabapple'
    debug !specimen.Describe
    > 'M. coronaria var unknown'



### | HAS - _collection filtering_ - pipers - ^has

Use __has__ to test for exclusion each object in a collection.

    ... | has [expr]
    ... | has (AS var1, var2...) [indent code block]
    ... | has USING [function reference]
    

The pipe operator **has** indicates an expression based filter using the **it**
_pronoun_ to represent the item currently under examination. Since **it** is in play,
the associated **dot** scoping prefix is also active within the expression for
easy access to item fields.

#### has inline

    debug friends | has (.province = 'QC') and (.cat or .dog)

    > [ { name: 'Ann', age: 23, cat: true, province: 'QC' } ]

Any valid expression can be used in a **has** piper, and one can refer
to values outside the expression as well.

    set rentAge to: ON 25, QC 21
    debug friends | has .age >= rentAge[.province]

    > [ { name: 'Ellie', age: 22, province: 'QC' },
    >   { name: 'Ann', age: 23, cat: true, province: 'QC' },
    >   { name: 'Harry', age: 31, province: 'QC' },
    >   { name: 'Jenna', age: 28, dog: true, province: 'ON' } ]

#### has block

**Has** can reference a block of code directly, which makes
the **it** pronoun available within that block, or be given the name of a
task (or a task definition).

You must **return** a _truthy_ (keep) or
_falsy_ (discard) value from the block so the filter can take the according
action. If you don’t return a value, all rows will be discarded.

    friends | has
      return .age >= rentAge[.province]

#### has using

You can integrate function calls by adding the
**using** keyword immediately following the __has__ keyword itself.

    set CanRent to task given row
      return row.age >= rentAge[row.province]

    debug friends | has using CanRent



### | HIGHEST - _search collection for highest value_ - pipers - ^highest

Returns the collection element with the highest value of the expression.

    ... | highest [expr]
    ... | highest USING [function reference]
    ... | highest  
    ... | highest (AS var1, var2...) [indent code block]
    

Prepares the pronouns **it** and **key** for use by the expression.

    debug friends highest .age

    > { name: 'Harry', age: 31, province: 'QC' }

__Highest__ is like a combination of __by__ and __first__, except that instead of
sorting, it just runs through the collection and finds the correct answer. (This is faster.)



### IF - _conditional flow control_ - constructs - ^if

If the expression is _truthy_, the code directly after the **if** is executed.
Otherwise, perform additional tests if specified by any **elsif**, **elsexists** or **elsunless** clauses,
or failing those, perform the code after the optional **else** clause.

    if [expr] (AS var1, var2...) [indent code block]
    
    elsif [expr] (AS var1, var2...) [indent code block]
    
    elsunless [expr] (AS var1, var2...) [indent code block]
    
    elsexists [expr] (AS var1, var2...) [indent code block]
    
    else [indent code block]
    

What is _truthy_?  Any value which is not _falsy_.  See [http://www.sitepoint.com/javascript-truthy-falsy/][1] for specifics; excerpted here.

_Falsy_ values are: `false`, `0` (zero), `""` (empty string), `null`, `undefined`, and `NaN` (not-a-number).  Everything else is _truthy_.

The value used in the test of the **if** is available in the _pronoun_ **trial**, which can be reassigned using an **as** clause.

    if names[pk]
      debug trial // prints the contents of names[pk]

    if names[pk] as row
      debug row // prints the contents of names[pk]

N.B. that __trial__ holds the value of the entire condition, not any sub-elements.

    if key is 'esc'
      debug 'the value of trial is: ' + trial   // this prints 'true', not 'esc'

#### else

Specifies a block of code that will be executed if the condition leading to the previous block fails.
Used with conditional statements **if/unless/exists**.

    if b
      debug 'b is truthy'
    else
      debug 'b is falsy'

#### elsif _clause_

Combines __else__ and __if__. If the test succeeds, the tested value will be placed in the __trial__ pronoun.

    if b
      debug 'b is truthy: ' + trial    // trial holds value of b
    elsif c
      debug 'b is falsy, but c is truthy: ' + trial   // trial now holds c
    else
      debug 'neither b nor c is truthy.'


#### elsexists

Combines __else__ and __exists__. If the test succeeds, the tested value will be placed in the __it__ pronoun.

    exists a
      debug "a exists: " + it   // it holds the value of a
    elsexists b
      debug "a does not exist, but b does: " + it  // it holds the value of b
    else
      debug "neither a nor b exists."

### elsunless _clause_

Combines __else__ and __unless__.

    if a
      debug "a is truthy: " + trial
    elsunless b
      debug 'b is falsy!  And there is no pronoun for this clause.'
    else
      debug 'a is falsy and b is truthy.  No pronoun because else dosent' get one.'



### INC - _value increment_ - keywords - ^inc

Increments (adds 1 to) the given variable.

    inc [var]

As in:

    set a to 1
    inc a
    debug a

    > 2

The __inc__ statement has special behaviour around values that are _undefined_ or evaulate to _falsy_; when you increment one of these values, it becomes `1`.  For example:

    set a to undefined
    inc a
    debug a

    > 1

This is useful when tallying with an array, e.g. the following construct automatically initializes array elements the way the standard `++` operator does not, such that the `tally` object will contain a log of word usage.

    set tally blank
    every word
      inc tallyit

Note that __dec__ does not have similar initialization functionality.



### INDEX - _custom order iterator_ - constructs - ^index

__Index__ iterates through an array or object sequentially using a separately provided collection of
keys. The index is stepped through one row at a time, and the value of the object with that index is
presented in the enclosed block of code.

    index [expr1 (, expr2, ...)] USING [function reference]
    index [expr1 (, expr2, ...)] (AS var1, var2, ...) [indent code block]
    
    else [indent code block]
    

You provide a collection, and the index, separated by a comma.

    index [collection], [index]

In pseudo-code, this happens:

    ply index as key
      with collectionkey as it
        [ code ]

A real example:

    set fruit to traits a Apple, b Banana, c Cherry
    index fruit, list b, c, a, c
      debug it

    > Banana
    > Cherry
    > Apple
    > Cherry

It is relatively easy to synthesize the function of __index__ using a normal iterator and __with__,
nevertheless it is such a common pattern it makes sense to abstract it slightly for better clarity.

__Index__ can accept an iterator as the index, in which case it will be stepped through until it is
exhausted (or you  __break__ out of the loop).

If the index requests a key that does not exist in the collection, __undefined__ is presented to the block.
In other words, missing values are neither skipped nor thrown as an error.

#### index using

__Index__ also offers the __using__ variant, where a function is called rather than a block of code executed.

    set tally blank
    set Tally to task as name
      inc tally
ame

    set fruit to traits a Apple, b Banana, c Cherry
    index fruit, list b, c, a, c
      Tally it

    debug tally

    > { Banana: 1, Cherry: 2, Apple: 1 }

You can use __break__ to exit out of the loop prematurely, and __continue__ to shortcut to the start.
See the documentation on these terms for more.



### INFINITY - _constant representing infinity_ - keywords - ^Infinity

Represents an infinitely large value.

    

Generally obtained by attempting to evaluate an expression with a divisor of zero.

    debug 1/0

    > Infinity



### INHERIT - _class heritage specification_ - keywords - ^inherit

Specify inheritance during object definition.

    inherit:
      [classname]
      ...

An object can have multiple parents at each level of inheritance, as in the following example.

    object Licensed
    instance: licenseTag false
    ..
    object Passengers
    instance: paxCount 0
    contract: paxMaximum
    ..
    object Automobile
    inherit: Licensed, Passengers
    ..
    object Sedan
    inherit: Automobile
    instance: paxMaximum 6
    ..
    set myCar to create 'Sedan'
    debug myCar
    > { licenseTag: false, paxCount: 0, paxMaximum: 6 }

    debug myCar.isa
    > Sedan

    debug myCar.isof
    > { Licensed:
       { version: '0.0.0-unspecified',
         isa: 'Licensed',
         load: './sample/Keywords/Licensed.sai' },
      Passengers:
       { version: '0.0.0-unspecified',
         isa: 'Passengers',
         load: './sample/Keywords/Passengers.sai' },
      Automobile:
       { version: '0.0.0-unspecified',
         isa: 'Automobile',
         load: './sample/Keywords/Automobile.sai',
         inherit: [ 'Licensed', 'Passengers' ] },
      Sedan:
       { version: '0.0.0-unspecified',
         isa: 'Sedan',
         load: './sample/Keywords/Sedan.sai',
         inherit: [ 'Automobile' ] } }

Note the use of **contract** in the _Passengers_ object; this requires any child object to offer
a `paxMaximum` trait. Contracts can be fulfilled by class functions (**task**/**process**/**promise**),
class traits (**given**) or **instance** traits.



### INITIALIZED - _default with assignment_ - operators - ^initialized

Examines the variable on the left; if it has a value, returns it. Otherwise calculates the value
on the right, stores it in the variable on the left, and returns it.

    ... [lexpr] initialized [rexpr]

The __initialized__ operator works very much like the __set/default__ combination, but allows
you to use it in the middle of an expression. You should only use variables on the left,
as trying to assign into a function or calculated expression will not work.

The only real use for this is in scenarios where you would like to cache the result of an
expression and want the code to reflect this simple idea.

Here is a trivial example:

    GetCachedThing task with identifier
      return thingCacheidentifier initialized from thingComputation identifier



### INSTANCE - _object instance variable declaration_ - keywords - ^instance

Define initial values for an object’s traits.

    instance:
      [varname] [initial value]
      ...

When an object is created, instance traits are assigned the given values before the
object’s **Instantiate** task is called.

    object Sock 1.0.0

    instance:
      colour 'Brown'
      pattern 'Argyle'
      size 'M'
      kind 'dress'

    Instantiate task
      debug @ select list colour, pattern, size, kind

    ....

    set aSock to create 'Sock'
    > { colour: 'Brown', pattern: 'Argyle', size: 'M', kind: 'dress' }

Instance traits, when declared with __instance__ or __given__, do not need to have their scope
indicated with `@` when used in their own object. Said another way, declared instance variables
are automatically scoped to the object. This is similar to the way that __reference__ values
don't need to use the `~` global scoping prefix.

The following are equivalent:

    instance:
      x 0
      y 0

    ...

    set x 34
    set @x 34          // this is not necessary

When referring to another object's instance variables, you will need to properly scope them:

    CopyPoint given point
      set x to point.x
      set y to point.y

Instance variables cannot be initialized with functions or "complex" expressions. The compiler will
warn you about it. Nevertheless, you should still declare all instance variables, even if you must start
them with `undefined`. That's because the compiler looks at the instance variables you've declared to
know what your instance variables are.

    object AppleCrate

    instance:
      sku '448893003'
      label ~GetLabel(.sku)  /// this won't work, instead:


    instance:
      sku '448893003'
      label undefined

    Instantiate task
      set label ~GetLabel(.sku)



### | INTO - _collection integration_ - pipers - ^into

Javascript features the array method `Array.prototype.reduce` which performs the reduction function,
and SAI extends its applicability with the **into** compherension keyword.

    ... | into [value] [expr]
    ... | into [value] (AS var1, var2...) [indent code block]
    ... | into [value] USING [function reference]
    

In addition to the item (**it**) and the item key (**key**) available in other comprehensions,
an sum variable (**sum**) is used when evaluating **into** expressions. The value
of the expression becomes the value of **sum** the next time the expression is evaluated.

#### into inline

The **sum** variable is initialized by the value following **into** — in the example below
`0` — and then each row in the collection is visited and we add `.age` to it. This adds up
the ages of every friend.

    debug friends | into 0 sum + .age

    > 185

#### into block

The **into** comprehension, like other comprehensions, has an inline version with an
expression, and a long-form which takes a block of code.

A more complex example.  See if you can suss out how it works.

    debug friends | into blank
      set sum[.province] to (self default 0) + 1

    > { ON: 5, QC: 3 }

Here’s a hint: **self** is a _pronoun_ used only in **set** statements. It is initialized to
the previous value of the variable being changed by **set**.

Another hint: **default** is an operator that evaluates to its right hand value if
and only if the left hand value is _undefined_.

Last hint: **blank** initializes an object with no traits; it is the SAI equivalent
of Javascript’s `{}`.  The comparable word for arrays/lists with no elements is **empty**;
in Javascript you’d write `[]`.

#### into using

The addition of **using** lets you call an external function.  The function must
always `return` the value you wish to be used as the sum so the value can be preserved
across function calls.  (The block version of **into** takes care of this for you.)

    set ageTotal to task given accumulator, row
      return accumulator + row.age

    debug friends | into 0 using ageTotal

    > 185



### IS - _equivalence test_ - operators - ^is

Returns **true** if the two expressions are completely indistinguishable.

    .. [expr] is [expr]

More rigorous than **=** when objects differ in type.

    debug 0 = false
    debug 0 is false

    > true
    > false

_Note: Do not use **is** or **isnt** to test values against **NaN**. You must use the
specific **isNaN** operator for this._



### .isa - _object name attribute_ - keywords - ^.isa

All prototyped SAI objects have an **isa** trait that identifies the object name.

    .. [object].isa

Further details about the object and its inheritance are found in the **isof** trait.

    object Fruit 1.0.0
    Instantiate task
      debug 'I am a ${isa}'

    set a to create 'Fruit'
    > I am a Fruit

    object Pear 1.0.0
    inherit: Fruit

    set b to create 'Pear'
    > I am a Pear



### isNaN - _checks for NaN_ - operators - ^isNaN

Returns true if the expression is the **NaN** flag.

    .. isNaN [expr]

Note there is no other way to test for NaN than by using **isNaN**.

Note also that capitalization matters.

    set a !parseInt 'This is not a number.'
    debug a           // NaN
    debug a = 0       // false
    debug a = false   // false
    debug a = NaN     // false
    debug isNaN a     // true

Right?  Seriously:

    debug NaN = NaN   // false
    debug NaN is NaN  // false

So that's why we need this keyword for this one little function.



### ISNT - _equivalence test_ - operators - ^isnt

Returns **true** if the two expressions are in any way distinguishable.

    .. [expr] isnt [expr]

More rigorous than **<>** when objects are of differing types.

    debug 1 <> true
    debug 1 isnt true

    > false
    > true

_Note: Do not use **is** or **isnt** to test values against **NaN**. You must use the specific **isNaN** operator for this._



### ISOF - _object information_ - operators - ^isof

All prototyped SAI objects have an **isof** trait that is a plain object that encapsulates detailed
information about the SAI object and its heritage.

    .. [object].isof
     - or -
      .. [object] isof [class name expr]

Let's just see how this works:

    object Fruit 1.0.0
    Instantiate task
      debug 'I am a ${isa}'

    set a to create 'Fruit'
    > I am a Fruit

    object Pear 1.0.0
    inherit: Fruit

    set b to create 'Pear'
    > I am a Pear

    debug a.isof

    > { Fruit:
    >   { version: '1.0.0',
    >     isa: 'Fruit',
    >     context: './sample/Keywords/Fruit.sai' } }

    debug b.isof

    > { Fruit:
    >   { version: '1.0.0',
    >     isa: 'Fruit',
    >     context: './sai/sample/Keywords/Fruit.sai' },
    >  Pear:
    >   { version: '1.0.0',
    >     isa: 'Pear',
    >     context: './sai/sample/Keywords/Pear.sai',
    >     inherit: [ 'Fruit' ] } }

  You can trace an object’s creation in order recursively by starting at the **isof** entry for the
  present object — `isof[isa]` — and stepping through the **inherit** array.

#### isof operator

  .. [object] isof [class name expr]

Returns true if the object is an instance of a class that is, or inherits from, the given class name.

    class Parent 1.0.0

    class Child 1.0.0
    inherits: Parent

    set a to create 'Child'
    debug a isof 'Child'   // true
    debug a isof 'Parent'  // true



### IT - _context-sensitive pronoun_ - pronouns - ^it

**It** is the most commonly used pronoun, populated by most iterators and comprehensions, as well as
the **exists** conditional and **with** contextualizer.

    .. it

_Pronouns_ have values when provided by the system during certain code events.

The **it** variable is only available in attached expressions or code blocks -- not in any functions that
may be called within those expressions, and not in code outside those blocks.

A partial list of **it** enabled events:

    exists [expr] // it: expr
    with [expr]   // it: expr

    iterate [iterable] // it: each iterated value
    each [collection]  // it: each value in the collection
    ply [list]         // it: each element in the array

    .. [collection] | thru // it: each value in the collection
    .. [collection] | audit
    .. [collection] | into
    .. [collection] | has
    .. [collection] | highest
    .. [collection] | lowest

When nesting contexts that create a **it** context, you will be unable to access “outer”
values of **it** within the inner contexts unless you assign them to a name other
than **it** using the **as** clause.

    ply: 1,2,3
      ply: 4,5,6
        debug it

    // prints 4 5 6 4 5 6 4 5 6

    ply: 1,2,3
      ply: 4,5,6 as inner
        debug it

    // still prints 4 5 6 4 5 6 4 5 6

    ply: 1,2,3 as outer
      ply: 4,5,6
        debug outer

    // prints 1 1 1 2 2 2 3 3 3

When **it** is populated, you can also use the “unrooted” **attribute** ( . dot) scoping
prefix.  The following are all synonymous:

    set field to 'province'
    set quebeckers to friends has it.province='QC'
    set quebeckers to friends has it[field]='QC'
    set quebeckers to friends has .province='QC'

(There is no unrooted [] lookup available, you can't `[field]`.)



### ITERATE - _sequentially examine values from a generator/iterator_ - constructs - ^iterate

The **iterate** statement steps through each value in an _iterable expression_.
This can be an object with fields/traits, an array/list with numbered elements, or a passive
iterator/generator that **yield**s values for iteration.

    iterate [expr] USING [function reference]
    iterate [expr] (AS var1, var2...) [indent code block]
    
    else [indent code block]
    

What’s an iterable expression?  It’s an object that **yield**s values for iteration, or an object that
on demand (via call to **[Symbol.iterator]** produces such an expression. (In ES6, native collection
types based on **Array**, **Map**, and **Set** support lazy iteration.)

This construct steps through each result of an _iterable expression_, passing it through a block
of code via the **it** pronoun.  If an **else** clause is present, that code is executed only if there is
no iteration.

Even though generators don't provide a key to match the value, when using a generator **iterate**
nevertheless provides **key**, giving you the row number of each value returned.

    set seen to new ~Set
    seen.add 'horse'
    seen.add 'pig'
    seen.add 'horse'
    iterate seen
      debug '${key} - ${it}'

    > 0 - horse
    > 1 - pig

#### iterate ... using

This variation calls the given function with two parameters, the iteration value and the current row number:

    set fruit list Apple, Banana, Citron, Durian
    set SeeFunctionParameters to task
      debug $$

    iterate (fruit iterate) using SeeFunctionParameters

    > { '0': 'Apple', '1': 0 }
    > { '0': 'Banana', '1': 1 }
    > { '0': 'Citron', '1': 2 }
    > { '0': 'Durian', '1': 3 }

You can use __break__ to exit out of the loop prematurely, and __continue__ to shortcut to the start.
See the documentation on these terms for more.



### | ITERATE - _transforms a static collection into an iterated form_ - pipers - ^iterate

Ensures the collection is an iterable. If it already is an iterable, return it unchanged.
If it has a **Iterate** method, call it and return that iterable. If it's an Array,
produce an iterator over its values. If it's an object, produce an iterator that returns
for each trait a 2-element array with trait name, trait value.
If it's just a plain value, produce an iterator that returns that value.

    ... | iterate  
    

Using **iterate** in this way allows you to guarantee that processing is being done using an
iteration rather than a static collection. To go the other way, use **collect**, which turns an
iterable into an Array.

The following example follows the one in the keyword **Iterator**:

    ply inventory | by it.1
      debug it

    > [ apple: 2, banana: 1 ]  // undesired result

    ply inventory | iterate | by it.1
      debug it

    > [ 'banana', 1 ]          // correct result
    > [ 'apple', 2 ]

The example wants to print out a sorted list of inventory items.

The undesired result comes about because **by** needs access to the entire collection
in order to sort it, so must process imperatively. Even if you give **by** an object
with a **Iterate** method, which all objects and arrays have whether you put it there
yourself or not, that method will not naturally be called.

So, **by** converts the `inventory` object into an array so it can be sorted. The
array conversion produces an array of all enumerable traits; in the case of `Tally`
objects, the only enumerable trait is `bag`, and so an array that looks like `[ bag ]`
is sorted (to no effect) and then printed one element at a time.

When you force a call to **Iterator** with the **iterate** comprehension, you get the
correct result you're expecting, as you thereby force **by** to use your custom iterator
rather than a naive array conversion.

The upshot is that right now SAI favours imperative collections rather than lazy
iterators except when specifically using the **iterate** statement or comprehension.



### Iterator - _name-of-the-Iterator method_ - keywords - ^Iterator

When creating an object you want to provide an invisible iterator for, use this keyword as the name of the
process.

    Iterator process (as [parameter list])
      [block]

This will be a little gritty, because ES6 is gritty. When you name an object process **Iterator** (note
the specific uppercase initial), the function won't be assigned to the object trait `object.Iterator`. Instead,
it will be assigned to `object[Symbol.iterator]`.

The bad news is that this means you can't specifically refer to that trait by name in SAI without
using the convoluted approach of `object[~Symbol.iterator]` (because **Symbol** is a global and globals
must use the global scoping prefix).

The good news is this means you probably won't ever *have to* refer to it by name, because all of SAI's
comprehensions, as well as the **iterate** statement, and ES6's `for-of` loop, all implicitly check for
the existence of the `Symbol.iterator` function and will use it if present.

    object Tally 1.0.0
    instance:
      bag empty
    Count task
      set bag[$] to (self default 0) + 1
    Iterator process
      each bag
        yield: key, it

    set inventory to create 'Tally'
    inventory.Count 'apple'
    inventory.Count 'banana'
    inventory.Count 'apple'
    iterate inventory
      debug it

    > [ 'apple', 2 ]
    > [ 'banana', 1 ]

In the example, when we **iterate** over `inventory`, a check is made to see if the object to iterate
has an **Iterator** process, which in this case it does, so it is called, and then iteration takes place
over the result. See the **iterate** construct for more on this.

Note that this sleight-of-hand doesn't apply to an object **task** (as opposed to **process**)
named "Iterator"; in fact SAI will not let you use that name for an object task, because doing so would
break expectations of what an iterator is supposed to do (e.g. yield things).  Gah, the cruft, it burns.



### KEY - _looping pronoun_ - pronouns - ^key

Often a partner to **it**, **key** is the second most commonly used _pronoun_, populated by most
iterators and comprehensions.

    .. key

Like all pronouns, **keys** is only visible in attached expressions or code blocks, not in any functions that may be called within those expressions.

A partial list of **keys** enabled events:

    each [collection]   // key: the trait name of each value in the collection
    ply [list]          // key: the array index of each element in the array
    count [expr]        // key: the number being counted
    iterate [generator] // key: the row number of the value being processed

    .. [collection] thru  // key: each trait name/array index of the collection
    .. [collection] audit
    .. [collection] into
    .. [collection] has

An example:

    ply friends
      debug key

    // prints: 0 1 2 3 4 5 6 7

    each friends[0]
      debug key

    // prints: name age cat province

Similar to **it** and **counter** in nested contexts, you are unable to access “outer”
values of **key** within inner contexts unless you assign them to a specific variable
using the **as** clause. See **counter** for an example of this issue.



### | KEYS - _return a list of trait names_ - pipers - ^keys

Returns the keys (or indices) of a collection’s elements.

    ... | keys  
    

__Keys__ returns a list comprising the keys/indices of the collection it is given.

If you give it an object/traits, you get the trait names.

    debug friends | first | keys

    > [ 'name', 'age', 'cat', 'province']

If you give it an array, it returns an array of indexes.

    debug fruit | keys

    > [ 0, 1, 2 ]

Given an iterator, it returns an iterator that counts from 0 to the number of results in the source.
Of course, you lose the values, but you didn't want them, did you.



### | LAST - _last value_ - pipers - ^last

Returns the last value in a list or iterator. With an expression, block or function, returns the
first value where the expression is true.

    ... | last  
    ... | last [expr]
    ... | last (AS var1, var2...) [indent code block]
    ... | last USING [function reference]
    

If the collection is an iterator, it will be exhausted. If it's an infinite iterator, the machine will stop
responding.

    debug fruit | last

    > Citron

__Last__ doesn't just crop the array, it unwraps whatever value is there, as
if you'd coded `array.[array.length-1]`.  __Last__ unwraps iterators, returning a single
value (or undefined). If you need the iteration chain preserved, use __limit__ (in combination with
__has__ if necessary).

#### Last with a comparison

If you provide a comparison expression, block, or function, __last__ will evaluate the comparison
against each element in the collection, and return the falst value that the comparison returns true.
If you use __last__ on an object, the order of comparisons is undefined.

Example:

    set fruit list Apple, Banana, Cherry, Durian

    debug fruit | last .length is 6      // Durian

#### Quirks

Arrays: __last__ starts looking at the tail of the array.

Objects: since the keys of an object are presented with no defined order, __last__ and __first__
examine elements in an object the same way.

Iterators: __last__ starts at the beginning, compares every item, and returns the last one found
when the iterator ends. If the iterator doesn't end, __last__ will hang. If no match is found,
__last__ does not yield a value, it simply terminates. If your comparison is expensive, you may
wish to __collect__ the iterator (turning it into an array) before applying __last__; this exchanges
memory use for processing speed.



### | LIMIT - _select certain array/iterator elements_ - pipers - ^limit

Returns a subset of elements from an array, string, or iterator.

    ... | limit [expr1 (, expr2, ...)]
    

If one parameter is provided, returns the first **qty** elements in the
collection if **qty** is positive. If negative, returns the last (absolute) **qty**
number of elements.

If an **index** is supplied, return **qty** elements starting at **index**.
Negative index values do interesting things, there's a chart below.

  .. [collection] | limit [qty]
  .. [collection] | limit [index], [qty]

  .. [string] | limit [character count]
  .. [string] | limit [start character], [character count]

You always get a list back, even if just one element will be returned.

    limit -y            last y rows
    limit 0             empty
    limit undefined     everything
    limit +y            first y rows

    limit -x, -y        everything except last y rows starting x from end of list
    limit -x, 0         empty
    limit -x, undef     last x rows
    limit -x, +y        y rows starting x from end of list

    limit 0, -y         everything except last y rows
    limit 0, 0          empty
    limit 0, undef      everything
    limit 0, +y         first y rows

    limit +x, -y        everything except last y rows starting at x
    limit +x, 0         empty
    limit +x, undef     everything starting at x
    limit +x, +y        y rows starting at x

If the collection is an iterable, it will only be fetched as many times as needed.
(If you ask for elements offset from the end, the iterator will be exhausted because an
iterator’s length can only be ascertained by exhausting it.)

If the iterator is infinite and you ask for an offset from the end, you'll run out of
memory as it will cache an infinite number of intermediate results order to comply
with your impossible request. (Infinite iterators have no end.)

#### limit with strings

You can use __limit__ to extract substrings. For this purpose characters are
treated as elements in the array.

    debug 'abcdef' | limit 2,2      // cd
    debug 'abcdef' | limit -3       // def
    debug 'abcdef' | limit -3,2     // de
    debug 'abcdef' | limit 1,-1     // bcde

And so on. One "gotcha" is operator precedence; pipers have the lowest
priority, so you will need to wrap them in parenthesis if using __limit__ in any
logical expression.

    Do this:
      if '#!' is (line | limit 0,2)   // correct code

    Not this:
      if '#!' is line | limit 0,2     // bad code
      if ('#!' is line) | limit 0,2   // also bad

Another "gotcha" is the way  __limit__ intentionally changes behaviour when its
arguments change from negative to positive. If you pass calculated values that
could become negative, __limit__ may return things you don't expect.



### LIST - _literal-based array construction_ - keywords - ^list

Used to specify the creation of a plain array of literal values.

    .. list [term], [term], ... (;)
    .. list
      [term], [term], ...
      [term]
      ...

As opposed to **array**, which is an array of mathematical expressions.

The following are acceptable terms:

    true or false
    number literal
    string literal quoted with ' or " or ` or '''
    unquoted bare string literal
       all characters available except } , ) ; | [cr]
       (note the comma, that will trip you up; comma separates terms)
    an equal sign (=) followed by an expression
    a nested definition starting with :, list, array, traits, or fields

Lists may be specified on one line:

    debug list Apple, Banana, Citron

    > [ 'Apple', 'Banana', 'Citron' ]

Or multiple lines in the form of an indented block, or a combination:

    debug list
      Vladimir, Estragon
      Pozzo, Lucky, The Boy

    > [  'Vladimir', 'Estragon', 'Pozzo', 'Lucky', 'The Boy' ]

When using a list literal in an expression that might make the end of the array a matter of
question, use a **semicolon** to close the array literal:

    debug list Vash, Spike, Jack, Cat thru '${it} the cat'
    > { 'Vash', 'Spike', 'Jack', 'Cat the cat' ] // undesired result

    debug list Vash, Spike, Jack, Cat; thru '${it} the cat' // with semicolon
    > [ 'Vash the cat', 'Spike the cat', 'Jack the cat', 'Cat the cat' ]

Or enclose the array in parenthesis:

    debug (list Vash, Spike, Jack, Cat).length
    > 4

Arrays can be nested by use of either parenthesis or semicolons, or by using multiple
levels of indent. Note that commas separate expressions on one line but are not
included at the end of a line.



### LOCAL - _locally scoped variable declaration_ - keywords - ^local

Create a local variable that exists only within the current level of indent (or deeper).
Uses Javascript's `let` declaration. (And this is the only construct in SAI that does so.)

    local [varname] to [expr]

Syntax identical to **set** however the variable created is limited to the current block in
scope. (Normally, variables are scoped to the object method they’re used in.) **Local** causes the
generated Javascript to declare variables with the `let` keyword.

Javascript's scoping around global/local variables can be tricky and has caught even experienced
programmers multiple times.

**Local** allows you to do dumb things like this:

    set a 1
    if a is 1
      local a 2
      debug a
    debug a

    > 2
    > 1

In general, SAI is designed such that you should only very rarely need __local__ variables.



### | LOWEST - _search collection for lowest value_ - pipers - ^lowest

Returns the collection element with the lowest value of the expression.

    ... | lowest [expr]
    ... | lowest USING [function reference]
    ... | lowest  
    ... | lowest (AS var1, var2...) [indent code block]
    

Prepares the pronouns **it** and **key** for use by the expression.

    debug friends lowest .age

    > { name: 'Doug', age: 18, province: 'ON' }

__Lowest__ is like a combination of __by__ and __first__, except that instead of
sorting, it just runs through the collection and finds the correct answer. (This is faster.)



### LSH - _unsigned bitwise left shift_ - operators - ^lsh

Convert the expression to a 32 bit integer, then shift it left bitcount times.

    .. [expr] lsh [bitcount]
    .. [expr] << [bitcount]   // synonym

For example:

    debug 4 lsh 1   // 8
    debug -8 lsh 2  // -32
    debug 2.8 lsh 0 // 2

The synonym __<<__ does exactly the same thing.



### MAIN - _indicates object should be instantiated at runtime_ - keywords - ^main

When using the compiler, native Javascript files of objects created with **main** will automatically
instantiate a single copy of the object when the file is required.

    object [objectname] main [objectversion]

In other words, when the `.js` file is required, in addition to defining a prototype, an object is
also instantiated (which causes any **Instantiate** task to run, thus conceivably launching a program).

Main also sets a flag in the **isof** property of the object, indicating it is the main object.

Have a look at the `bin` folder for `runner.sai` which uses the __main__ keyword to indicate it is
a program that should be run rather than just an object prototype.



### NaN - _not-a-number_ - keywords - ^NaN

**NaN** (capitalization matters) means Not a Number.

    .. NaN

**NaN** is returned from some library calls on failure to convert a value into a
number.  (The **number** operator returns 0 instead.)

    debug ~parseInt('The one ring.')
    > NaN

    debug number 'The one ring.'
    > 0

The _only_ way to test for **NaN** is to use the **isNaN** operator.

    debug NaN = ~parseInt('The one ring.')
    > false  // !

    debug NaN is ~parseInt('The one ring.')
    > false  // !!!!

    debug isNan ~parseInt('The one ring.')
    > true



### NAND - _not-and logical_ - operators - ^nand

Checks two or more values; returns _false_ if all of the values are _truthy_. Otherwise
returns _true_.

    .. [expr] nand [expr]
    .. nand [list of expressions]

A semantic simplification of `not ([expr] and [expr])`.

    debug 0 nand 0 // prints 'true'
    debug 1 nand 0 // prints 'true'
    debug 0 nand 1 // prints 'true'
    debug 1 nand 1 // prints 'false'

These are logically the same

    debug a nand b
    debug not ( a and b )

For syntax of the list-based version of __nand__ please review keyword __and__.



### NEW - _object instantiation_ - operators - ^new

Instantiates a new object with the given prototype.

    .. new [prototype] [parameters]

If parameters are supplied, passes them to the object’s constructor.

**New** is used for traditional Javascript objects; objects where you have in-hand the prototype
used to fabricate an instance that object. **New** trusts that the code to create that object
has already been located and compiled.

**Create** is used for SAI objects; objects where you have in-hand an object name (as a string).
**Create** doesn't assume pre-compiled prototypes; if the prototype isn't cached, it will attempt
to load it via the `SAI.config.Loader` function.

    reference:
      express require('express')

    object HelloHTTP 1.0.0

    Instantiate task
      set @app express()

      @app.get '/', task given req, res
        res.send 'Hello HTTP!'

      set @server !@app.listen 3000, 'localhost', task
        with @server.address()
          debug 'Example app listening at http://${.address}:${.port}'

You ordinarily need to use the **~** global scope prefix when creating Javascript built-in objects
however `Error` has been promoted to SAI global so you don't have to:

    if crocodiles
      throw new Error "Why do we even have that lever?"

Notice here that **new** is not expecting any parameters to be wrapped in parentheses; in this way it
works like **from**.

See also __create__ which is used to instantiate SAI objects by name, and __singleton__ which is
used to create singleton SAI objects by name.



### NOP - _no-operation statement_ - keywords - ^nop

No operation; no data; do nothing.

    nop

This statement (or one like it) is necessary as a syntactical placeholder when a white-space
indent is expected but you do not wish to put code in it.

    if x>26
      nop
    elsif x>13
      set x - 13
    elsif x>0
      set x + 13



### NOR - _not-or logical_ - operators - ^nor

Checks two or more values; returns true only if _all_ of them are _falsy_. Otherwise
returns true.

    .. [expr] nor [expr]
    .. nor [list of expressions]

Returns **true** only if left or right expression are both _falsy_. Otherwise returns **false**.

A semantic simplification of `not ([expr] or [expr])`.

    debug 0 nor 0 // prints 'true'
    debug 1 nor 0 // prints 'false'
    debug 0 nor 1 // prints 'false'
    debug 1 nor 1 // prints 'false'

These are the same:

    if not ( a or b )
    if a nor b
    unless a or b

For the syntax related to the list-based version of 'nor' review keyworcd __and__.



### NOT - _logical not_ - operators - ^not

Performs the logical not operation.

    .. not [expr]

Returns **false** if the right expression is _truthy_, otherwise returns **true**.

    debug not false  // prints 'true'
    debug not 0      // prints 'true'
    debug not 'Sam' // prints 'false'
    debug not empty  // prints 'false'

These are the same:

    if not a
    unless a



### NOTB - _binary not_ - operators - ^notb

Performs a bitwise logical not on a 32-bit signed integer.

    .. notb [expr]

For example:

    debug notb -8  // prints '7'

     -8 in binary: 11111111111111111111111111111000
     +7 in binary: 00000000000000000000000000000111



### NULL - _a value that is no value_ - keywords - ^null

An empty value.

    .. null

Null is:

  - _falsy_
  - not `undefined`

I don’t have any example code for this.



### NUMBER - _numeric coercion_ - operators - ^number

Attempts to convert the following expression into a numeric value.

    .. number [expr]

If it cannot, the result is 0.

    debug number '12'
    debug number 'ralph'
    > 12
    > 0

It is always safe to use __number__ in that it will never return a non-number, and it will never
throw an error. It's sole failure mode is to return 0.



### OBJECT - _object declaration_ - keywords - ^object

Begins the definition of an object.

    object [identifier] (main) [version]
    ...

Only one object definition is permitted per file.

In an object definition, the following sections are supported. See each keyword for more details.
Also review the _Defining an Object_ document.

    reference:
      [globally defined references]

    object [identifier] (main) [version]

    inherit:
      [list of objects to inherit from]

    contract:
      [list of traits that child objects must provide]

    given:
      [declaration of immutable object traits]

    instance:
      [declaration of initial trait values for each instance]

    get [trait name to implement dynamically]
      [code]
    set given [value]
      [code]

    [name] task/process/promise
      [code that implements this task/process/promise]

When a SAI object is created, the **Instantiate** task is executed on that obejct, allowing you to
perform instance-level initialization code. Notice the caps; by convention SAI methods are
capitalized, while attributes are lowercase.

If the **main** clause is included, the object is marked to be instantiated automatically when a
compiled `.js` version of the object is required. See **main** for slightly more detail.



### | OBSERVE - _inspect a value without changing it_ - pipers - ^observe

Evaluates the right expression using the left expression value as the **it** pronoun;
however, **observe** always returns the original left hand expression, no matter the result
of the right expression.

    ... | observe [expr]
    ... | observe (AS var1, var2...) [indent code block]
    ... | observe USING [function reference]
    

For example:

    set b to 'Fred'
    set c to b observe debug '${it.length} letters.'
    debug c

    > 4 letters.
    > Fred

See the example for __audit__ for a more interesting reason why __observe__ is nice.

A warning: while you can **observe** an iterable expression, all you will see is a function.
Take care not to invoke it, lest you drain it inadvertently.
Heisenberg's uncertainty principle is very much at play with iterables:
you can either have it or know what's in it.

N.B. **observe** very useful in **chain** expressions.



### | OR - _explores a collection_ - pipers - ^or

Examines every item in a collection, returning the first one found _truthy_.

    ... | or  
    

For example:

    set t: undefined, 9, true
    set f: 0, null, false

    debug t | or
    debug f | or

    > 9
    > undefined

Rules for source data:

- __undefined__: returns `undefined`.

- __value__, returns the value.

- __array__, returns the first _truthy_ element found in the array, otherwise `undefined`.
The array is searched starting at index 0.

- __traits__: returns that value if _any_ value in the collection is _truthy_,
otherwise `undefined`. The collection is searched in no defined order.

- __iterable__: yields the _first_ truthy value returned by the iterator.
Yields `undefined` if the iterator ends before one is found.
Will lock up if an infinite iterator never yields a truthy value.

If given an iterator, __or__ returns an iterator that will yield one value (or lock up).



### OR - _logical or_ - operators - ^or

Checks two or more values; returns the first one examined that is _truthy_. Otherwise
returns the last value checked.

    .. [expr] or [expr]
    .. and [list of expressions]

Examples:

    debug 0 or 0  // prints '0'
    debug 1 or 0  // prints '1'
    debug 0 or 2  // prints '2'
    debug 1 or 2  // prints '1'

__Or__ also works with a list. Please review the __and__ keyword for details on
syntax.



### ORB - _bitwise-or_ - operators - ^orb

Performs a bitwise or on two 32-bit integers.

    [expr] orb [expr]

Example:

    debug 5 orb 11 // prints '15'

     5 in binary: 00000000000000000000000000000101
    11 in binary: 00000000000000000000000000001011
    15 in binary: 00000000000000000000000000001111



### ORPHAN - _rescoping this_ - keywords - ^orphan

**Orphan** causes the __@__ scoping prefix within the function to refer to the context
of the function call, instead of the context of the function definition.

    orphan  
    

You probably want to use this in combination with **local** variable definitions.

For clarifications and example code on this, see **task**.

To do this on a case-by-case basis, use the __@@__ scoping prefix (which see).



### PLY - _iterate over an array-like collection_ - constructs - ^ply

The **ply** iterator sequentially steps through all elements in an _array-like_ collection;
it works on any object that has a **length** trait.
It accesses numeric traits from 0 to **length**-1, sending each trait value to the code
block or function. If **length** is 0, the **else** clause is invoked instead.

    ply [expr] USING [function reference]
    ply [expr] (AS var1, var2...) [indent code block]
    
    else [indent code block]
    

The trait value is captured in the **it** pronoun, and the trait number is captured as **key**.

    ply fruit
      debug '${key}: ${it}'
    else
      debug 'There is no fruit.'

    > 0: Apple
    > 1: Banana
    > 2: Citron

#### ply ... using

**Ply** can also call out to a function with the **ply using** variation.

  set handler to task given value, field, collection
    debug `${field}: ${value}

  ply fruit using handler

The function is called for each element of the array with three parameters:

 - element value (__it__)
 - element index # (__key__)
 - a reference to the array itself

You can use __break__ to exit out of the loop prematurely, and __continue__ to shortcut to the start.
See the documentation on these terms for more.



### PROCESS - _generative function definition_ - keywords - ^process

Creates a function that is expected to **yield** one or more values.

    [identifier] process ( as [parameter list] )
      [yielding code block]
    
    .. process ( as [parameter list] )
      [yielding code block]

This is an ES6 feature. **Process** does exactly the same thing as **task** except the generated code
uses `function*` instead of `function`.

If you're not familiar with generators/yielding, here is a very simplified overview.

  set Candidates to process
    count 1 to 100 as x
      count 1 to 100 as y
        if 1<x and x<y and x+y<100
          yield: x x, y y, s x+y, p x*y

The Candidates process, when invoked, runs all of the code in the process up until the
first **yield**, then returns, handing you a process object, here stored in the variable `iter`:

  set iter Candidates()

That object is an _iterator_; it is a stateful representation of a `Candidates` process.
Each time you call a process, you get a new iterator. Once you have an iterator, you can _iterate_
through it. Each iteration returns the next value _yielded_ by the process.

Iteration takes place by calling the **.next** task on the iterator.

    debug iter.next()

    > { value: { x: 2, y: 3, s: 5, p: 6 }, done: false }

You can see that **.next** returns a simple object with two fields, **.value** and **.done**.
(In our iterator, the value is the first qualified candidate represented by a simple object with
four fields: x, y, s and p.)

**.value** holds whatever was **yield**ed. **.done** is a boolean flag that indicates whether the
iteration is complete; that is, whether another call to **.next** would result in a newly generated value.

Each time you call **.next** you will get a new value.

    debug iter.next()
    debug iter.next()
    debug iter.next()

    > { value: { x: 2, y: 4, s: 6, p: 8 }, done: false }
    > { value: { x: 2, y: 5, s: 7, p: 10 }, done: false }
    > { value: { x: 2, y: 6, s: 8, p: 12 }, done: false }

Here is a bit of code that will keep calling **.next** until the **.done** flag is set, saving
the result in a four item list.

    set cache to empty            // empty array
    dountil result.done           // check .done at the end of each loop
      set result iter.next()      // next iteration to result
      cache.push result           // save result in cache
    debug cache | limit -4        // print last four rows

    > [ { value: { x: 48, y: 50, s: 98, p: 2400 }, done: false },
        { value: { x: 48, y: 51, s: 99, p: 2448 }, done: false },
        { value: { x: 49, y: 50, s: 99, p: 2450 }, done: false },
        { value: undefined, done: true } ]

Once the **.done** flag is set, the iterator is said to be _exhausted_. Notice that **.value** is
*undefined* when the **.done** flag is set.

Processes, generators and iterators are very powerful tools because they allow computations to be
*lazy*, that is, for data to be generated only as it is needed, thus vastly reducing memory
requirements. (The Python language is very useful for scientific computing because it is a primarily
lazy language because large data sets can be manipulated with modest resources.)

SAI has many affordances for processes and iterators, including native support with all
comprehensions. As a very simple example, all of the above code could be replaced with this
simple expression:

    debug Candidates() | limit -4

    > [ { x: 48, y: 49, s: 97, p: 2352 },
        { x: 48, y: 50, s: 98, p: 2400 },
        { x: 48, y: 51, s: 99, p: 2448 },
        { x: 49, y: 50, s: 99, p: 2450 } ]

 (Notice how the limit comprehension itself deals silently with **.next** and **.done**, and
 automatically gives you just a list with only the **.value** of each iteration.)



### PROMISE - _declare a Promise-producing function_ - keywords - ^promise

Wraps the code block in a Promise-like function shell.

    object
    [identifier] promise ( as [parameter list] )
      [code block]
    
    .. promise ( as [parameter list] )
      [code block]

Along with **resolve** and **reject**, forms a convenient bit of syntactic sugar for making
Promise-like functionality.

Here is some sample code:

    set
      willIGetNewPhone promise given isMomHappy
        if isMomHappy
          resolve:
            brand 'Wangdoodle'
            colour 'paisley'
        else
          reject new ~Error 'Mom is not happy.'

      showOff promise given phone
        with phone
          debug 'Hey friend, I have a new ${.colour} ${.brand} phone'

      askMom task given happiness
        chain willIGetNewPhone(happiness)
          then showOff
          catch promise given e
            debug '${e} -- No phone for you.'

    askMom true
    askMom false

    > Hey friend, I have a new paisley Wangdoodle phone
    > Error: Mom is not happy. -- No phone for you.

The way **promise** works is best explained by just showing you what happens when you use it. We
wrap the code block in a Promise constructor, as follows:

    set doThing to promise given url
      HeyServer url, task given request, result
        if result.success
          resolve result
        else
          reject result
    ..
    debug doThing.toString()

    > function (p) {
    >   return new Promise(function($_resolve, $_reject) {
    >     var $url = p;
    >     $HeyServer($url, function(p, $result) {
    >       var $request = p;
    >       if (($56 = ($result.success))) {
    >         $_resolve($result);
    >       } else {
    >         $_reject($result);
    >       }
    >     });
    >   });
    > }

So basically it throws a **Promise** wrapper around the function and allows you to use
**resolve** and **reject** as statements. (The $56 in there is housekeeping for the **trial** pronoun;
V8 optimizes unused assignments like this away.)



### PROMISING - _asynchronous flow control for Promises_ - constructs - ^promising

The __promising__ construct lends clarity to asynchronous operations using `promise`-based functions.

    promising [promise]
      resolve/reject [parameters]
     - or -
    promising
      [code that is turned into a promise]
      resolve/reject (parameters)
     - or -
    promising // with nothing following
    
    ... followed by one or more of ...
    
    then [promise]
     - or -
    then (promise parameters)
      [code that is turned into a promise]
      resolve/reject (parameters)
    
    catch [promise]
     - or -
    catch (promise parameters)
      [code that is turned into a promise]
      resolve/reject (parameters)
    
    finally [promise]
     - or -
    finally (promise parameters)
      [code that is turned into a promise]
      resolve/reject (parameters)
    
    any [array of promises]
    
    all [array of promises]
    
    rejected (expression)
    
    resolved (expression)
    
    finalize
    

In one sense __promising__ is just a bit of syntactical sugar for using `chain`
to connect `then` and `catch` etc in a series of chained method calls. And indeed,
that's what it does behind the scenes. But simplifying syntax is not a bad thing,
especially if it eases working with a more hat can be quite confusing.
And Promises are certainly that.

In order to make this construct work, you need to know what each clause
requires, not only syntactically, but from a code point of view.
We'll take each clause one by one.

Most clauses in __promising__ are either a single line, which accept either
a value that will be passed on to the next clause immediately, or an active
promise (a _thenable_) that will be resolved before the next clause; or are
multi-line, accepting a block of code that it will wrap in a Promise,
as if it were the body of a function.

First things first: the __promising__ clause must be the first clause in
the construct, and you can only use it once. (You can start with either form
of the __promising__ clause.) You can mix and match the other clauses in
any order once you've started the __promising__.

The final clause in the construct must be either __catch__ or __finally__
to ensure that errors are properly caught. However, you can use either of
these multiple times in the same construct, in order to control execution flow
between error handlers and the normal flow of code.

#### promising

    promising [a value or a promise]
     - or -
    promising
      [code block that will be wrapped as a Promise]

__Promising__ starts the clause. It expects an active Promise -- an object
with `.then` and `.catch` ready for use. If it isn't a promise, it's just a
value that will be passed forward.

In this example, `db.listDatabases` is a function, and we invoke it with __from__
so it will return an active promise.

    promising !db.listDatabases

In this form, the function you are promising must have been declared as a __promise__, or
been created in or wrapped in a _Promise_ wrapper by a library or helper.

In multi-line form, you're crafting the body of a __promise__ function, and you'll
use __reject__ and __resolve__ to pass along asynchronous results to the next
clause of the construct.

    promising
      https.get url, task
        set body ''
        $setEncoding 'utf8'
        $on 'data', task
          set body + $
        $on 'end', task
          resolve body
        $on 'error', task
          reject $

Of course you could just take that bunch of code and wrap it in a __promise__
yourself, perhaps as part of some global object. But more likely you'd just find
a package on npm that offers promisified fetchers ai Because you're smart.

##### promising with no block or parameter

If you have an array of promises that you'd like to
use with __all__ or __any__ then just start the structure with
__promising__ with no parameter or block:

    promising
    all promiseArray
    catch
      debug "uh oh"

#### then

    then [value or promise]
     - or -
    then (optional [GIVEN parameter list])
      [code block that will be wrapped as a Promise]

The __then__ clause continues the chain of asynchronous execution. Whatever
you __resolve__ in the previous clause is given to the next __then__ clause as
one (or more) parameters. (You can use the pronoun __$__ to refer to the first
parameter passed without giving it a name.)

    then !db.dropDatabase dbName

Which, by the way, does the exact same thing as this:

    then
      resolve !db.dropDatabase dbName

The block takes the same form and acts the same way as the one in __promising__.

Here's a fun note: when coding these _block form_ clauses, there is an automatic
__resolve__ applied at the end of the code block, so execution carries onwards without
you having to be explicit about it. So you can  do this:

    promising
      debug "First this"
    then
      debug "Then this"
      reject "Ninja!"
    then
      debug "But not this."
    catch
      debug $

Which prints:

    First this
    Then this
    Ninja!

Notice how `Ninja!` is transferred by passing the message to the __catch__ clause
via __reject__.  And also note the __$__ pronoun. The __catch__ clause could have
been written either of these ways too.

    catch given msg
      debug msg

    catch debug $

#### catch

    catch [value or promise]
     - or -
    catch (optional [GIVEN parameter list])
      [code block that will be wrapped as a Promise]

As you'd expect __catch__ works just like the other line or block form clauses,
except that it is only executed if a previous clause __rejects__ something. As
illustrated in the above text!

If there is a __then__ or __finally__ clause after __catch__ in the construct,
it will be executed, unless you __reject__ again.

#### finally

    finally [value or promise]
     - or -
    finally (optional [GIVEN parameter list])
      [code block that will be wrapped as a Promise]

This clause captures both main and error code paths in the Promise pseudo-thread,
thus it is always executed regardless of whether the previous clause ended with a __reject__ or __resolve__.

Support for __finally__ is dependent on whether the Promises library you are using
supports it; SAI does not shim it for you. As of this writing, `Promise.finally`
has not been ratified for inclusion in ES6, and node.js does not support it.

#### all

    all [expression yielding an array of promises]
     - or -
    all

The __all__ clause, along with __any__ is different than the other clauses. __All__ is
a simple way of waiting for an array of promises to _all_ be resolved. It takes a single
parameter -- an array -- and waits for each Promise in the array to be resolved.
It uses the `Promise.all` helper to do this.

The stand-alone version of all, that takes no expression, assumes the array has been
sent to it from the __resolve__ in the previous clause. The following two lines are identical:

    all       // all (implicit)
    all $     // all (explicit)

The __all__ clause is great to use when you need to fetch multiple resources all at
once and need to know when they're done. The following two line snippet fetches a list of
databases (asynchronously) and then passes the resulting list __thru__ a function that
creates multiple requests for more information about each database. The result is
an array of promises that are used as a parameter to __all__.

    promising db.listDatabases
    all $ thru db.get(it, '/')

__All__ resolves either with a list of the __resolve__ values of every promise in the
array, or a _single_ value that is the _first_ rejection of any of those promises.
In other words, __all__ will wait to __resolve__ until all of it's work done, but the
instant something breaks, it __rejects__ everything and gives up.

#### any

    any [expression yielding an array of promises]
     - or -
    any

The __any__ clause is very similar to __all__, except that it either __rejects__ or
__resolves__ based on the first event in all of the promises in its array. So while __all__
will wait to resolve for everything to be finished, __any__ will resolve when the first
Promise it is monitoring does so. Like __all__, however, it __rejects__ on the first Promise to do so.

#### rejected (only within a __promise__ function)

    rejected [expression]
     - or -
    rejected

So you might be wondering how do you pass the results of a __promising__ construct to a
Promise that contains it. After all, you cannot __resolve__ or __reject__ an outer promise
from an inner one -- the rules of scoping forbid it. In this case, the last three clauses help you out.

__Rejecting__ is internally equivalent to a __catch__ clause, in that any error conditions
are caught by it. However, it then marks the Promise _containing_  the __promising__ construct as rejected.

The bare word version of __rejected__ sends the error value it received to the containing
Promise, while the version with an expression allows you to customise it.

#### resolved (only within a __promise__ function)

    resolved [expression]
     - or -
    resolved

Similarlly, __resolved__ will resolve a containing Promise with either an expression
or a passed-on value.

#### finalized (only within a __promise__ function)

    finalized

And, most useful, the __finalized__ clause will take the current state of the __promising__
clause it is a part of and transfer it to the containing promise, kind of like a `return` statement.

Finalized doesn't take a value because it passes on whatever value the last promise state has. If you
need to override your return values you'll need to do so with rejected and/or resolved.



### | REDUCE - _collection reduction_ - pipers - ^reduce

__Reduce__ transforms a collection of items into a single item by giving a function two items and
asking it to produce a single item in response. This is repeated over the entire collection.

    ... | reduce [expr]
    ... | reduce USING [function reference]
    ... | reduce (AS var1, var2...) [indent code block]
    

Let's say you have an array with four numbers:

    set b to: 4, 7, 12, 34

    set result to b | reduce as a, b
      debug "a:${a} b:${b}"
      return a+b

    debug "result: ${result}"

The __reduce__ operator is given a block of code that accepts two items, a and b. It prints them
both out, then returns their sum. This prints:

    > a:4 b:7
    > a:11 b:12
    > a:23 b:34
    > result: 57

Since there were four items in the list, the code block was called three times. The first time
with the first two elements in the array. Subsequently, it was called with the previous result
and the next element in the array.

If the collection given to __reduce__ only has one element, that element is returned without
calling your code; since there was only one item, there is no way to combine it with another.
If you give __reduce__ an empty collection, the result is __undefined__.

__Reduce__ is a classic operator for transforming sets of data, and there are far better
explanations of how it works and what it is good for to be found elsewhere. The rest of this
documentation will just show examples.

*Note that if you are looking for a reduce-like operator where you provide a starting value for
the accumulator and are given each item in the collection in turn, then look at __into__ which
does exactly what you want. __Reduce__ is kind of a different animal.*

#### reduce inline

The inline form of reduce gets two pronouns, __sum__ and __it__.

    set result to b | reduce sum+it

#### reduce block

A __reduce__ code block has the two available pronounts __sum__ and __it__, which you can
rename with an __as__ clause, as shown in the above example.

#### reduce using

The __using__ clause is available with __reduce__. You're passed two parameters, the sum
and the next element to consider.

    set Adder to task given a, b
      return a+b

    set result to b | reduce using Adder



### REFERENCE - _declare global values_ - keywords - ^reference

Import/declare global variables at the top of a **.SAI** source file.

    reference:
      [name] [expr]
      ...

This is the only way to make global variables; inside a reference declaration. The syntax
is the same as a **fields** structure definition, with name/value pairs separated by commas or newlines.

    reference:
      MIN 0, MAX 100
      express require('express')
      Vector2D 'Vector2D ^1.0.0'

    count to MAX
      debug key
    ..
    set @app express()
    ..
    set origin to create Vector2D 0, 0
    ..

Note: you cannot assign to reference variables or re-use them as locals. The following lines would
produce compile errors given the above references:

    local Vector2D
    set MIN -50



### REJECT - _mark a Promise as having failed_ - keywords - ^reject

Call the failed potential outcome for a function declared with **promise**.

    reject [expr1 (, expr2, ...)]
    reject  
    

This does not implicity end execution, however, the way **return** does.

For an example, see **promise**.



### REJECTED

_See: promising_



### | REPLICATE - _create a list by copying an element_ - pipers - ^replicate

Replicate sucks, it should be removed.

    ... | replicate [expr]
    

What it does:

    set b 'a' | replicate 3
    debug b

    > [ 'a', 'a', 'a' ]

I dunno, this doesn't feel meaty.



### RESOLVE - _mark a Promise as succeeding_ - keywords - ^resolve

Call the successful potential outcome for a function declared with **promise**.

    resolve [expr1 (, expr2, ...)]
    resolve  
    

Doesn't implicitly end execution the way **return** does, so make sure you mind the code path.

For an example, see **promise**.



### RESOLVED

_See: promising_



### RETURN - _exit a function, returning a value maybe_ - keywords - ^return

Return a value to the caller of a **task**.

    return [expr1 (, expr2, ...)]
    return  
    

Works just like Javascript.

    set multiply to task given a, b
      return a*b

    debug multiply(2, 4)

    > 8



### RSH - _signed bitwise right shift_ - operators - ^rsh

Convert the expression to a 32 bit signed integer, then shift it right bitcount times,
maintaining the sign of the expression.

    .. [expr] rsh [bitcount]
    .. [expr] >> [bitcount]  (synonym)

As in:

    debug 8 >> 1   // 4
    debug -32 rsh 2 // -8

There's also an unsigned variant __>>>__/__ursh__.



### | SELECT - _multi-attribute query_ - pipers - ^select

Returns a new collection that is the subset of the original collection
identified by the provided list of keys/indices.

    ... | select [expr]
    

Example:

    debug fruits | select: 2, 0;

    > [ 'Citron', 'Apple' ]

    debug friends | limit 3 | thru <- it | select list name, age

    > [ { name: 'Sara', age: 32 },
        { name: 'John', age: 19 },
        { name: 'Ellie', age: 23 } ]



### SELF - _pronoun for set statements_ - pronouns - ^self

A pronoun used only in a **set** statement that contains the original value of the variable
that is being set/modified.

    set [var] .. self ..

The following lines are equivalent; one of them is easier to read than the other.

    set totalskey to totalskey ? 0 + amount
    set totalskey to self ? 0 + amount



### | SET - _replacement operator_ - pipers - ^set

A chainable comprehension operator that allows direct reference and replacement of the incoming dataset within an expression or code block, using the  **it**  pronoun.

    ... | set [expr]
    ... | set (AS var1, var2...) [indent code block]
    ... | set USING [function reference]
    

**Set** can be used with an expression:

    debug 4 | set 5*it+2 | set it/7

    > 3.142857142857143

**Set** can use an indented code block:

    debug friends by .age | set
      set .length to 3

    > [ { name: 'Doug', age: 18, province: 'ON' },
    >    { name: 'John', age: 19, cat: true, dog: true, province: 'ON' },
    >    { name: 'Marshal', age: 21, dog: true, province: 'ON' } ]

_If you don’t specifically **return** a value or object from within an **set** code block, the original value will be used (as in the example above). In other words, there is an implicit `return it` at the end of every **set** block._

**Set** supports the **using** clause, in which case the function specified receives the original value as its first parameter, and the return value is passed forward. The two debug statements below are equivalent

    set ExtractFirst to task
      return $[0]

    debug friends #cat | set Extract(it)
    debug friends #cat | set using Extract

    > { name: 'Sara', age: 23, cat: true, province: 'ON' }
    > { name: 'Sara', age: 23, cat: true, province: 'ON' }

You must specifically return a value in the function called by **set using**.



### SET - _variable assignment_ - keywords - ^set

Set is a busy keyword used in many situations where a result is calculated and then stored.

    see below for syntax reference

#### set dynamic trait declaration

    [identifier] set ( as [ident] )
      [code block]
    ( get
      [code block] )

Declare a _setter_ for a dynamic object trait. Cannot be used inside a function body.

This example object implements *Distance*, storing the value normalized to meters. You can get and set the value in centimeters and miles through the use of dynamic traits.

    object Distance 1.0.0
    instance: meters 0

    centimeters set given val
      set meters to val/100
    get
      return meters * 100

    miles set given val
      set meters to val * 1609.344
    get
      return meters / 1609.344

 And in use:

    set trip to create 'Distance'
    set trip.meters to 500
    debug trip.meters       // > 500
    debug trip.centimeters  // > 50000
    debug trip.miles        // > 0.31068559611867
    set trip.miles to 10
    debug trip.meters       // > 16093.44

#### set value assignment

    set [ident] to [expr]
    set [ident] [expr]  // the TO keyword is generally optional but it's a good idea to use it
    set [ident] ![function] ( [parameters] )
    set [ident] from [function] ( [parameters] )
    set [ident] [operator] [expr]
    set [ident] [unary operator]

Assign a value to an identifier. That's right, you don't use the equals sign for assignment.
Ugh, whose idea was that anyway?

    set a to 2
    set a from Math.pow self, 2
    set a Math.sqrt(a)
    set a * 4
    set a -
    debug a

    > -8

#### set multiple array value assignment

If you separate multiple identifiers with commas on the left, the assignment will assign each array
element on the right, starting at 0, to each identifier. As example:

    set a, b, c to: 1, 3, 5

For a fruity example:

    set a, b, c to fruit
    debug b
    > Banana

This is useful when dealing with small tuples or parsed data:

    GetPixel task given x,y
      return buffer.slice( (x+y*width)*4, 4 )

    set r, g, b, a to GetPixel(x,y)

This compiles to a Javascript construct similar to the following:

    var $_=GetPixel(x,y);
    $r=$_[0]; $g=$_[1]; $b=$_[2]; $a=$_[3];

#### Scoping and Set

All un-decorated, e.g. bare (`a` as opposed to `$a`), variables are scoped to the object method they're **set** in. For tighter scoping, you can use **local** in place of **set**, this causes the variable to be declared in-place using the Javascript keyword `let`.  _Be careful with variable scoping._

    set a 1
    if a is 1
      local a 2
      debug a
    debug a

    > 2
    > 1

#### set pipe operator

Documentation under separate cover.



### SINGLETON - _singleton object access_ - operators - ^singleton

Creates one instance of SAI object by name.

    .. singleton [expr] [parameters]

Creates one instance of SAI object by name. If the object has already been created, returns a
reference to it. The scope is that maintained by the runtime library.

Like __create__, __singleton__ will attempt to find the object’s source by using the `SAI.config.Loader`
function, which defaults to `SAI.GetSourceFromPaths`, which tries to find a file named `[expr].sai`
in the provided paths.

    reference:
      Tally 'Tally ^1.0.0'
    ..

    set inventory to singleton Tally

(The example follows best practices of placing object names in a **reference** section, aliasing
versioned names into literals.)

Singleton objects are useful for library functions, APIs to external resources, tallies, caches,
message managers and so on.

Since the reference to the singleton object is maintained by the library, singleton objects are
never garbage collected (and cannot be destroyed) once created. If you might need to release resources
held by a singleton before the end of the application, you must make allowances for that in your
object's API; e.g. by crafting a `.Cleanup` task.

See also __new__, which is a direct link to Javascript's `new`, and __create__, which will make a new
object each time.



### STATE - _asynchronous finite state machine_ - constructs - ^state

The __state__ construct creates an asynchronous state machine (or finite automata) that can
be used for many different kinds of processes, from making requests or managing other machines,
to controlling and responding to near-realtime events.

    state [expr] (AS var1, var2...) [indent code block]
    state [variable]
    

Each declared __state__ is given a name (the value), and has an associated block of code.
Each block is a function, with optional parameters. These functions are invoked with
the __goto__ verb. The first parameter of __goto__ is the name of the state; any additional
parameters are passed in to the state function.

    state [value1] (given [parameter list])
      ... code ...
      goto [value] (, [parameters for next state])
      ... code ...
    state [value2] (given [parameter list])
      goto etc...
    ... repeats for as many states as supplied

The uppermost defined __state__ in the construct is the starting state by convention,
and it is invoked first. When you __goto__ a new state, you'll just be scheduling the next
state to occur next. You must `return` if you want its execution to stop immediately. If you
do not __goto__ another state, the machine ends (unless a callback into to a state happens
asynchronously). State machine context is preserved until there is no more opportunity for a callback.

*Note*: The __state__ construct runs asynchronously. Synchronous code execution passes the
state machine definition instantly, and the first state executes on the next event loop
tick via node's `setImmediate`. Each time you __goto__ a new state, that state is also
scheduled asynchronously.

While the event loop is quite fast (perhaps 100k state transitions
per second on a laptop), you will want to avoid using the __state__ construct for applications
that require high performance and/or that do not benefit greatly from asynchronous response.
In these cases, a `while` loop around a `switch` statement is a good place to start.

Context is preserved with the state machine, including the _current_ (this) object. You have
access to all member variables/methods of the object instance that invoked the __state__ construct.
Variables you `set` within any state are available to all states. However, `local` variables are
restricted to the state they're defined in. (Examine the generated Javascript code for clarity.)

Here is a simple example of a state machine, a Turing machine that adds two unary (bitcount)
numbers starting at the read head, extending right and separated by a single 0 digit.

    set Readout to task  // display Turing tape and current head position
      debug tape | into '' sum + ((key is head) ?? '[${it}]' :: ' ${it} ')

    state 'start' // turing machine to add two numbers, in this case 3 & 4.
      set tape list 0, 1, 1, 1, 0, 1, 1, 1, 1, 0
      set head 1
      goto 'a'

    state 'a'
      Readout
      if tapehead       // seek end of first number
        set tapehead 1
        inc head
        goto 'a'
      else               // set bit between numbers
        set tapehead 1
        inc head
        goto 'b'

    state 'b'
      Readout
      if tapehead       // seek end of second number
        set tapehead 1
        inc head
        goto 'b'
      else
        set tapehead 0  // rewind to end of second number
        dec head
        goto 'c'

    state 'c'
      Readout
      if tapehead       // clear bit at end of second number
        set tapehead 0
        dec head
        goto 'd'
      else
        debug "Should not be able to get here."
        goto 'halt'

    state 'd'
      Readout
      if tapehead       // seek back to the beginning of the result
        set tapehead 1
        dec head
        goto 'd'
      else
        set tapehead 0  // return to first set bit and halt
        inc head
        goto 'halt'

    state 'halt'
      Readout
      debug "Run complete."

    debug "State machine started." // appears first because STATE is asynchronous

The output is:

    State machine started.
     0 [1] 1  1  0  1  1  1  1  0
     0  1 [1] 1  0  1  1  1  1  0
     0  1  1 [1] 0  1  1  1  1  0
     0  1  1  1 [0] 1  1  1  1  0
     0  1  1  1  1 [1] 1  1  1  0
     0  1  1  1  1  1 [1] 1  1  0
     0  1  1  1  1  1  1 [1] 1  0
     0  1  1  1  1  1  1  1 [1] 0
     0  1  1  1  1  1  1  1  1 [0]
     0  1  1  1  1  1  1  1 [1] 0
     0  1  1  1  1  1  1 [1] 0  0
     0  1  1  1  1  1 [1] 1  0  0
     0  1  1  1  1 [1] 1  1  0  0
     0  1  1  1 [1] 1  1  1  0  0
     0  1  1 [1] 1  1  1  1  0  0
     0  1 [1] 1  1  1  1  1  0  0
     0 [1] 1  1  1  1  1  1  0  0
    [0] 1  1  1  1  1  1  1  0  0
     0 [1] 1  1  1  1  1  1  0  0
    Run complete.

There are many easier ways of programming a Turing machine without hardcoding everything
like this. This one does show off the __state__ construct fairly nicely, however.

#### goto

Within the __state__ construct, the variable `goto` is defined as a function that schedules
execution of the next state.  (This trickery should be essentially invisible, but just in case you
need to know how, this is how.)

##### Parameters with __goto__

__goto__ will pass any provide parameters on to the state function:

    state 'start'
      debug "You're lost in a cave!"
      dountil maze\pos is 'empty'
        set pos !Rand size
      goto 'move', pos            // we're passing the new position here as POS

    state 'move' given newpos        // and it is recevied here as NEWPOS
      inc moves
      set position !Valid newpos
      debug " move ${moves} ... now in room ${position}"
      goto maze\position

#### then

Similarly, __then__ is a function that _creates a function_ that immediately jumps to the next
state rather than rescheduling another state transition. In other words, __then__ is a callback
creator.

Use __then__ like this:

    state 'empty'
      ply array position-1, position+1 as adjacent
        each features as dsc, feat
          if feat is maze[from Valid adjacent]
            debug dsc

      Timer 800, !then 'step'

    state 'step'
      goto 'move', position + !Step

This example does some housekeeping, delays for 800ms, _then_ the timer callback jumps to the
next state.

##### Parameters with __then__

Because __then__ creates a callback function, there are _two_ opportunities for arguments to be
passed to the next state.

1. When __then__ is executed to create the callback.
2. When the callback is executed some later time.

In the above example,

    Timer 800, !then 'step'

This is the first opportunity for parameters to be passed.

To make it clear, let's add one:

    ...
      Timer 800, !then 'step', !Step

    state 'step' given stepValue
      goto 'move', position + stepValue

Parameters added at callback creation time are resolved immediately, even though they're not
used until later. These parameters are invisibly bound into the callback function that is
created. In the above example, `stepValue` is calculated 800ms before the state change to `step`
occurs; this step value waiting in the callback defined when the `Timer` function is invoked.

The second opportunity is when the callback is actually made. In our example, let's say the timer
wishes to pass the real time it was resolved. And we want that data. But we also want our
`stepValue`, which was passed in earlier.

Fortunately, we can have both pieces of data. The callback function that __then__ creates will
append any arguments it receives _as a callback_ to the arguments bound to it _on callback
creation_. So we now have two parameters to our `step` state.

    state 'step' given stepValue, resolvedTime
      debug "Timer resolved at ${resolvedTime}"
      goto 'move', position + stepValue

Just to make it clear: `stepValue` was calculated and passed into the callback generator when we
started the timer, and `resolvedTime` was calculated and passed into the callback when
the timer resolved. The callback concatentated them into one set of arguments for the call to
the `step` state.

If you unroll this, it looks something like this:

    then 'step', stepValue
     .. becomes ..
    callback invoking 'step' with stepValue
     .. which _later_ is invoked as ..
    callback resolvedTime
     .. which becomes ..
    invoke 'step' with stepValue, resolvedTime

This works with any number of arguments provided at callback creation and resolution. Just be
sure you know how many of each there are when you pick them up in the _state handler_.

I hope that's clear. And useful!



### SUM - _reduction pronoun_ - pronouns - ^sum

A pronoun active only within a **into** clause or code block.

    .. sum

Represents the static value that accumulates changes during **into** iteration over a data set.

    debug friends | into 0
      set sum + .age

    > 185

**Sum** is initialized with the value following **into**.

    debug friends | into blank
      set sum[.province] to (self default 0)+1

    > { ON: 5, QC: 3 }



### SUPER - _superclass function invocation_ - keywords - ^super

Call the previous ancestral version of the current object method.

    super ( [ parameters ] )
    .. super ( [ parameters ] )

This doesn't happen by default; if you want to chain backwards up the inheritance tree you must do it
with **super**.

Note there is *no other way* to access an overridden ancestral object method than by
using **super** within that specific overriding method itself. SAI is very strict about inheritance
that way. Don't even bother exploring the prototype chain.

    object Parent
    instance: name 'unknown'
    Instantiate task given name
      set @name to name

    object Child
    inherit: 'Parent'
    instance: age 'unknown'
    Instantiate task given name, age
      super name
      set @age to age

    set billy to create 'Child' 'Billy', 12
    debug billy

    > { name: 'Billy', age: 12 }

Contrary to what you might expect, **super** _does not_ use the **@** scoping prefix; that's
because super _always and only_ refers to the current object. You cannot call **super** on any other object.

If you want to pass arguments to a **super** method without specifying them discretely, the following
really ugly idiom gets the job done.

  super.apply @ $$



### SWAP - _value swapper_ - keywords - ^swap

Exchanges the values.

    swap [lvalue1] [lvalue2]

Intended as syntactic sugar, collapsing three ugly lines into one simple line.

    swap a b

This is functionally equivalent to the following Javascript:

    var temp1=a;
    var temp2=b;
    b=temp1;
    a=temp2;



### SWITCH - _choice-based conditional_ - constructs - ^switch

Choose among alternatives based on expression equality.

    switch [expr] (AS var1, var2...)
    
    case [expr1 (, expr2, ...)] [indent code block]
    
    else [indent code block]
    

The expression under evaluation is available to all codepaths
as **trial** (which can be renamed with the **as** clause).

Unlike the native Javascript `switch` these __case__ clauses do not fall through;
the break is implicit.  (Though you can break out early.)

    switch ~System.IO.Keypress() as key
    case 'n', 'N'
      Move 0,-1
    case 's', 'S'
      Move 0,1
    case 'e', 'E'
      Move 1,0
    case 'w', 'W'
      Move -1,0
    case ' '
      Jump
    case '?'
      Help
    else
      Emit 'Key [${key}] isn't used; type ? for help.'

The compiler will insist on an __else__ clause as a matter of good programming hygeine.



### TASK - _define a function_ - keywords - ^task

Define a block of code as an object trait or anonymous function.

    [identifier] task ( given [parameters] ) / ( expects [parameters] )
      [code]
    
    .. [task] ( given [parameters] ) / ( expects [parameters] )
      [code]

It’s probably best to explain this by showing what Javascript is made.

#### task trait

The first example is a task trait on an object. It takes two standard parameters, name and value.

    Instrument task given name, value
      debug `${@context} ${name}: ${value}

Generated code:

    function (p, $value) {
      var $name = p,
        $ = this;
      console.log('' + $.context + ' ' + $name + ': ' + $value);
    }


You’ll note that the first parameter in a SAI-generated function is always `p`, which
is explained below. More importantly, however, note the assignation `$ = this`.

In SAI-generated code, the `$` variable is used as a buffer for the _this_ context.
When executing a task trait, SAI captures the current _this_ with `$=this` to
provide a reliable context for anonymous functions.

#### anonymous task

Here’s the same task but for anonymous use:

    set anon to task given name, value
      debug `${@context} ${name}: ${value}

Generated code:

    function (p, $value) {
      var $name = p;
      console.log('' + $.context + ' ' + $name + ': ' + $value);
    }

Notice how the anonymous task doesn’t capture `this.` into the `$` variable the
way the trait task does.

Thus, anonymous tasks automatically bind to the context that created them. This is usually
what you want when creating anonymous tasks, and is why the `var self=this` idiom has so
much traction in Javascript. SAI builds this idiom into the language.

However, if you don’t want this behaviour for a particular anonymous task, include
the **orphan** statement in it.

    set anon to task given name, value
      orphan
      debug `${@context} ${name}: ${value}

Generated code:

    function (p, $value) {
      var $name = p;
      var $ = this;
      console.log('' + $.context + ' ' + $name + ': ' + $value);
    }

Orphan anonymous tasks bind to the _calling_ context, rather than to the context that created them.

#### positional vs. named parameters

The second example is a task which expects two named parameters, $angle and $magnitude. As shown above, the first parameter in generated code is always `p`. Named parameters are passed as traits within `p`.

    SetPolar task expects $angle, $magnitude
      set x to $magnitude * Math.cos($angle)
      set y to $magnitude * Math.sin($angle)

Generated code:

    function (p) {
      var $ = this;
      _$AI.expectsThrow(p, {
        "angle": true,
        "magnitude": true
      }, 'SetPolar');
      $.x = (p.magnitude * Math.cos(p.angle));
      $.y = (p.magnitude * Math.sin(p.angle));
    }

When you use **expects**, a call to _expectsThrow_ is included to validate your assumptions.

This task is called by naming the parameters:

    SetPolar angle 45o, magnitude 3

Which generates this code:

    $.SetPolar({
      angle: 0.7853981633974483,
      magnitude: 3
    });

Notice how named parameters are encapsulated in a plain JS object and
passed in the first function call argument (which is always named `p`).

It is not necessary to use the **expects** clause to used named parameters. All **expects** does
for you is check to see if the names (and types) are as expected. Here is the function without it:

    SetPolar task
      set x to $magnitude * Math.cos($angle)
      set y to $magnitude * Math.sin($angle)

Generating this:

    function (p) {
      var $ = this;
      $.x = (p.magnitude * Math.cos(p.angle));
      $.y = (p.magnitude * Math.sin(p.angle));
    }

The use of named parameters with the **$** scoping prefix generates code that assumes the
first argument `p` will have the expected named traits.

Refer to the entry on **expects** for more on what it does.



### THEN

_See: promising_



### THROW - _generate an exception_ - constructs - ^throw

Trigger exception handling.

    throw [expr1 (, expr2, ...)]
    

Example:

  try
    throw new Error 'Oh no!'
  catch
    return error.message

You should probably look at the Javascript documentation.



### | THRU - _transform a collection with a map-like operation_ - pipers - ^thru

Pass each element of a collection “thru’ an expression, code block, or previously defined
function. The result of the expression becomes the new value in a copy of the collection.

    ... | thru [expr]
    ... | thru (AS var1, var2...) [indent code block]
    ... | thru USING [function reference]
    

__Thru__ returns the same type of collection it is given. An array yields an array, an object
an object, and an iterator another iterator. (There are other pipers for transforming
between types of collection.)

Conversion to uppercase:

    debug fruit | thru .toUpperCase()

    > [ 'APPLE', 'BANANA', 'CITRON' ]

A more complex formatting that could be an expression but I needed a block example:

    debug friends | has .cat | thru
      return '${key+1}) ${.name}, age ${.age}, lives in ${.province}'

    > [ '1) Sara, age 23, lives in ON',
         '2) Jon, age 19, lives in QC',
         '3) Ann, age 23, lives in QC' ]

Passing values **thru** a function:

    set rot13 to task
      set out to ''
      count $length
        set char to $charCodeAt(key)
        switch char >> 5
          case 2,3
            with char andb 31
              if it > 26
                nop
              elsif it > 13
                set char - 13
              elsif it > 0
                set char + 13
        set out + ~String.fromCharCode(char)
      return out

    debug fruit | thru using rot13

    > [ 'Nccyr', 'Onanan', 'Pvgeba' ]

The function called by the **using** variant receives three parameters for every iteration:

 - item value
 - item key
 - reference to the entire collection



### TO - _set clause syntax_ - keywords - ^to

__To__ is used in __set__ statements to separate the value being set from the value itself.

    set [lexpr] to [rexpr]

It is almost never necessary to actually use __to__ because the parser can almayst always figure
out what's going on.  Still, it looks clearer, so you should use it.

    set a to 5
    set a 5

Here's the only common case where there is confusion in the parser:

    set a - 5

What does that mean?

    set a to -5
    set a self - 5

The compiler complains about this construct specifically, and makes you specify.



### | TOTAL - _reduction with addition/concatenation_ - pipers - ^total

__Total__ is very like __into__ however the emphasis is on addition.

    ... | total [expr]
    ... | total USING [function reference]
    ... | total  
    

__Total__ is a reduction operator that is specialized for adding numbers, or concatenating strings.

    debug list a,b,c; | total

    > abc

Here, total has iterated through the three elements of the `list a, b, c` and added them together.
Because they are strings, the result is a concatenated version of the array of strings.

    debug array 5, 10, 15, 20 | total

    > 50

Similarly, total has added up the numbers.

You can pass an expression (or function) to __total__ just like with __into__, in which case the
addition is whatever value the expression returns on each iteration.

    debug fruit | total .length

    > 16

The length of the three strings in the fruit array.

#### total using

The addition of **using** lets you call an external function.  The function must
always `return` the value you wish to be added. You get two parameters, the value, and
the key.

    set ageTotal to task given row, id
      return row.age

    debug friends | total using ageTotal

    > 185



### TRAITS - _declare a structure of literal strings_ - keywords - ^traits

Used to specify the creation of a plain object with a set of key/term pairs.

    .. traits [key] [term], [key] [term], ... (;)
    .. traits
      [key] [term], [key] [term], ...
      [key] [term]
      ...

(Contrast with **fields**.)  When you want to be specific about creating a plain object
from a set of of keyed values & literal terms, use **traits**.

The **key** is an identifying word or other string, specified without quotes (although
quotes may be used if desired/necessary). If a **#** preceeds the key (a hashtag),
the key will be assigned a value of **true**. The **term** is any valid
term (see **list** for a description of valid terms).

See **fields** for examples.



### TRIAL - _pronoun for conditionals and switch_ - pronouns - ^trial

A pronoun set to the value tested in an **if/exists** or **switch** statement.

    if [expr]
      .. trial ..
    
    switch [expr]
      case [match]
        .. trial ..
      default
        .. trial ..

In an **if/exists** statement, **trial** is only valid in the body of the first code block.

    exists readline()
      // trial is available here
    else
      // trial is undefined here

In a **switch** statement, **trial** is available through all **case**s and the **default**.

    switch Keypress.toUpperCase()
      case 'N'
        Move 0,-1
      case 'S'
        Move 0,1
      default
        debug 'I don't know what ${trial} means.'
    ...

You can grant a specific name to the tested value with the **as** clause:

    if Keypress as key
      switch key.toUpperCase()
    ...

Note that **trial** receives the tested value; the final result of the **if** or **switch** expression, not the value of any component:

    if Keypress>0
      debug trial

    // the debug statement can only ever print 'true'

Using the parenthetical **as** is one solution to this problem:

    if ( Keypress as key) > 0
      debug key

    // reports the actual value of key



### TRUE - _boolean value true_ - keywords - ^true

The value TRUE, as in truthy, or not false.

    .. true

This is what all those __if__ statements test for, the holy grail itself.



### TRY - _handle exceptional errors_ - constructs - ^try

Exception handling construct.

    try [indent code block]
    
    catch (AS var1, var2...) [indent code block]
    
    finally [indent code block]
    

In addition to the standard Javascript stuff, SAI's "try" uses the
__error__ pronoun within the __catch__ clause to expose the caught error,
as seen in the example below.

    set file to new File 'output.log'
    try
      file.Open
      file.Write 'Hey, it's a log'
    catch
      return error.message
    finally
      file.Close

For details, see the Javacript exception documentation.



### TYPEOF - _javascript type disclosure_ - operators - ^typeof

Returns the Javascript-native type of an expression.

    .. typeof [expr]

See e.g. [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof][2] for details.



### UNBOUND - _mark a method as context-free_ - keywords - ^unbound

An __unbound__ function is not 'attached' in any way (other than by name) to any instance of its
object.

    object ObjectName
    
    [name] unbound task
    [name] unbound process
    [name] unbound promise

When you declare an object function as __unbound__ the function no longer checks to see if it
has become orphaned in execution -- that is, if it's _this_ object is no longer
what it is supposed to be -- on a call to that function. Indeed, the _this_ context is specifically
undefined in an __unbound__ function.

__Unbound__ functions  cannot reference bareword (unqualified) instance or given variables,
or normal (bound) object functions. (They can access them with direct context, see the example
below.) They can also call other unbound functions.

    object Thing
    instance: name 'Fred'

    Bound task
      debug name    // Fred
      Unbound
      Unbound2 @
      Unbound3 @

    Unbound task
      debug name    // COMPILE ERROR, cannot use bareword instance variable within unbound task

    Unbound2 task given o
      debug o.name  // This is an access with direct context: the variable o. This prints 'Fred'

    Unbound3 task given o
      Unbound2 o    // This is okay, calling an unbound task within an unbound task
      Bound         // COMPILE ERROR, cannot call bareword bound function from an unbound task
      o.Bound       // But this is okay, because it's got a direct context.

So the question is why the heck would you ever mark a function __unbound__ and the answer is
sometimes when you're using callbacks, you might not be able to pass in a bound function.
Also, depending on your JS compiler, there may be a slight performance gain in marking small,
often used utility functions as __unbound__ so there is no need to perform binding checks.

It is reasonably safe to just declare things __unbound__ if you think you might want the
benefits; the compiler will holler if it thinks you're making a mistake.



### UNDEFINED - _the absence of a place_ - keywords - ^undefined

A literal indicating there is no variable, or no place for one.

    .. undefined

This compiles directly to Javascript’s `undefined`.



### UNLESS - _conditional flow control_ - constructs - ^unless

If the expression is _falsy_, the code directly after the **unless** is executed.
Otherwise, perform additional tests if specified by any **elsif**, **elsexists** or **elsunless** clauses,
or failing those, perform the code after the optional **else** clause.

    unless [expr] (AS var1, var2...) [indent code block]
    
    elsif [expr] (AS var1, var2...) [indent code block]
    
    elsunless [expr] (AS var1, var2...) [indent code block]
    
    elsexists [expr] (AS var1, var2...) [indent code block]
    
    else [indent code block]
    

See __if__ for more details on th if/exists/unless constructions.

Values that trigger an __unless__ clause are those that are _falsy_, that is:
`false`, `null`, `undefined`, `0`, `NaN`, `''` (empty string).

Objects are generally _truthy_, including empty arrays and blank traits.

Another JS trap, the following is false:

    debug NaN is NaN
    > false

    The only way to check for NaN is to use isNan:
    debug isNaN NaN
    > true



### UNTIL - _loop over a block of code while an expression is false_ - constructs - ^until

Executes the code block repeatedly, as long as the expression is false. This is essentially
a **while** statement with the test inverted.

    until [expr] (AS var1, var2...) [indent code block]
    

The basic **until** variation performs the test first, so there is a chance the code will not execute.
The **dountil** variation executes the block first, then performs the test.

    until true
      debug 'You will never see this.'

    dountil true
      debug 'You will see this once.'

**Until** _does not_ make its test value available for use as **it**. Because the code block
only executes when the test value is _falsy_, there’s really no point.

You can use __break__ to exit out of the loop prematurely, and __continue__ to shortcut to the start.
See the documentation on these terms for more.



### | UPDATE - _multi-attribute update_ - pipers - ^update

Creates a new collection that is a composite of a copy of the left collection with all
of the values in the right collection overlaid. If discrete keys are available in the
left or right collection, they will be used intelligently.
Undefined values on the right will not be assigned.

    ... | update [expr]
    

Examples

    Sample data

    set list1 to list Apple, Banana, Citron
    set list2 to list Kiwi, undefined, Mango
    set traits1 to: a 1, b 2, c 3
    set traits2 to: '1' 4, d 5

    debug list1 | update list2
    > [ 'Kiwi', 'Banana', 'Mango' ]

    debug list1 | update traits1
    > [ 'Apple', 4, 'Citron', d: 5 ]

    debug traits1 | update traits2
    > { '1': 4, a: 1, b: 2, c: 3, d: 5 }

    debug traits1 | update list2
    { '0': 'Kiwi', '2': 'Mango', a: 1, b: 2, c: 3 }

__Update__ also works with iterators and treats them like arrays.
If the left side collection is **undefined**, it will be initialized **blank**.

__Update__ is handy when used in __set__ statements.

  set [variable] | update [collection]

Update a collection variable with a set of keys/values. When used like this in a __set__ statement,
the original data is updated in-place (maybe). Works on lists and traits, and accepts lists, traits
and iterators for update data.

Updating a list:

    debug fruit

    > [ 'Apple', 'Banana', 'Citron' ]

    set fruit update: '1' 'Pear', '3' 'Guava'
    debug fruit

    > [ 'Apple', 'Pear', 'Citron', 'Guava' ]

    set fruit update list Grape, undefined, Melon
    debug fruit

    > [ 'Grape', 'Pear', 'Melon', 'Guava' ]

Updating traits:

    set friend to friends.1
    debug friend

    > { name: 'John', age: 19, cat: true, dog: true, province: 'ON' }

    set friend update: name 'Jon', province 'QC'
    debug friend

    > { name: 'Jon', age: 19, cat: true, dog: true, province: 'QC' }

    set friends update: undefined, friend
    debug friends

    [ { name: 'Sara', age: 23, cat: true, province: 'ON' },
      { name: 'Jon', age: 19, cat: true, dog: true, province: 'QC' },
      { name: 'Ellie', age: 22, province: 'QC' },
      { name: 'Marshal', age: 21, dog: true, province: 'ON' },
      { name: 'Doug', age: 18, province: 'ON' },
      { name: 'Ann', age: 23, cat: true, province: 'QC' },
      { name: 'Harry', age: 31, province: 'QC' },
      { name: 'Jenna', age: 28, dog: true, province: 'ON' } ]

If the left-side collection is undefined, **update** initializes it to **blank** before merging.



### URSH - _unsigned bitwise right shift_ - operators - ^ursh

Convert the expression to a 32 bit unsigned integer, then shift it right bitcount times,
Zero bits are added on the left side (msb), which does not preserve negative sign.

    .. [expr] ursh [bitcount]
    .. [expr] >>> [bitcount]   (synonym)

This is the difference:

    debug -32 rsh 2 // -8
    debug -32 ursh 2 // 1073741816

You want this one if you're working with bitmap data, for example.

Compare with __rsh__.

The synonym __>>>__ does the same thing as __ursh__.



### USING - _function reference clause_ - keywords - ^using

Indicates in many looping constructs that logic is to be provided by a separate callback function.

    .. using [function reference]

Many pipe operators and loops provide a __using__ variant.

Have a look on the specific constructs to see how it's used.



### | VALUES - _return a list of collection values_ - pipers - ^values

Returns the values of a collection's elements.

    ... | values  
    

__Values__ returns a list of all of the values in a collection.

If you give it an object/traits, you get the the values.

    debug friends | first | values
    > [ 'Sara', 23, true, 'ON' ]

Given an array, you get a copy of the array.

    debug fruit | values
    > [ 'Apple', 'Banana', 'Citron' ]

With an iterator, it returns that iterator; that is, it does nothing.



### WHILE - _loop over a block of code while an expression is true_ - constructs - ^while

Executes the code block repeatedly, as long as the expression is true.

    while [expr] (AS var1, var2...) [indent code block]
    

The basic **while** variation performs the test first, so there is a chance the code will not execute.
The **dowhile** variation executes the block first, then performs the test.

    while false
      debug 'You will never see this.'

    dowhile false
      debug 'You will see this once.'

**While** makes its value available for use as **it**, as below.

    while file.NextLine()
      @story.push it

**Dowhile** _does not_ use **it**, because the expression is not evaluated until after the first pass
through the code, thus the first **it** result would always be **undefined**.

You can use __break__ to exit out of the loop prematurely, and __continue__ to shortcut to the start.
See the documentation on these terms for more.



### WITH - _block-level pronoun assignment_ - constructs - ^with

Allows the use of the **it** pronoun (and the `.` scoping prefix) within an arbitrary block of code.

    with [expr] (AS var1, var2...) [indent code block]
    

For example:

    with customer
      set label to '''
        ${.name}
        ${.address1}
        ${.address2}
        ${.city} ${.region} ${.postcode}

Another example, this time using an assigned pronoun:

    with category\document\page as p
      set precis:
        title p.title
        authors join!p.authors ', '
        summary p.abstract ? p.summary

Though that is much the same as this:

    local p category\document\page
    set precis:
      title p.title
      authors join!p.authors ', '
      summary p.abstract ? p.summary

__WITH__ can make things tidier, but mind what your pronouns are.



### XOR - _logical exclusive-or_ - operators - ^xor

If both expressions are _truthy_, or both expressions are _falsy_, return `false`. Otherwise return the expression that is _truthy_.

    .. [expr] xor [expr]

Example:

    debug 'Fred' xor 'Daphne'
    debug 'Shaggy' xor 0
    debug 0 xor 'Scooby'
    debug 0 xor 0

    > false
    > Shaggy
    > Scooby
    > false

Maybe not too often used, but compared to:

    if (a and b) or not (a and b)



### XORB - _binary exclusive-or_ - operators - ^xorb

Performs a bitwise XOR operation on two 32-bit integers.

    .. [expr] xorb [expr]

Example:

    debug 3 xorb 6 // prints '5'

    3 binary: 00000000000000000000000000000011
    6 binary: 00000000000000000000000000000110
    5 binary: 00000000000000000000000000000101

Favourite of cryptographers everywhere. And data storage architects.



### YIELD - _process product_ - keywords - ^yield

Produces the _next_ value in a __process__.

    yield [expr1 (, expr2, ...)]
    

Used with functions defined as **process**; see that keyword in this documentation,
and the EcmaScript 6 documentation for details.

    set OddNumbers to process
      set i to 1
      while true
        yield i
        set i + 2

    set myOdds OddNumbers()
    debug myOdds.next
    debug myOdds.next
    debug myOdds.next

    > { value: 1, done: false }
    > { value: 3, done: false }
    > { value: 5, done: false }

    iterate OddNumbers() | limit 4
      debug it

    > 1
    > 3
    > 5
    > 7



### YIELDING - _process inclusion_ - keywords - ^yielding

Yields to another process until that process is done yielding.

    yielding [expr1 (, expr2, ...)]
    

Equivalent to Javascript’s `yield *` syntax.
Essentially, **yielding** calls another process given a subroutine.

    // The Mirror process yields its first argument
    // then reverses it (in ASCII), yields that
    // then terminates

    set Mirror to process given str
      yield str
      yield str.split('').reverse().join('')

    // FruitSalad process is yielding an invocation of Mirror
    // for each fruit, then terminates

    set FruitSalad to process
      ply fruit
        yielding Mirror(it)

    // access each generated value in FruitSalad in turn
    iterate FruitSalad()
      debug it

    > Apple
    > elppA
    > Banana
    > ananaB
    > Citron
    > nortiC

In the example, Mirror yields twice, and FruitSalad yields to Mirror three times (once for each fruit), so the final iteration result is six values.



