Skip to content

Latest commit

 

History

History
363 lines (291 loc) · 12.3 KB

expressions.md

File metadata and controls

363 lines (291 loc) · 12.3 KB

Expressions

Expressions produce values. Statements such as assignments and void calls do not supply placeholder values.

Collected queries and text patterns

collect query ... end query produces a typed array from a source array, with optional filtering, stable ordering and pagination before projection. See collected queries for both Ny and Matrix syntax and evaluation rules. Named text patterns are immutable text-source declarations consumed by the shared pattern library.

Literals

Integer Literals

42          # i32
42 as i64   # explicit width
0xFF        # hex
2147483648  # inferred i64

Decimal literals infer i32 or i64 by representable range. Hexadecimal literals through 0xFFFFFFFF retain 32-bit mask semantics. Out-of-range integers are rejected before code generation; see the integer width contract.

Float Literals

3.14        # f64
3.14 as f64
1e3         # f64, even without a decimal point
1.5E-3      # 0.0015
5e-324      # smallest positive f64, rounded from decimal

Decimal literals containing a fractional part or an e/E exponent infer f64. An exponent may have a + or - sign and must contain at least one digit. Leading signs are unary operators. Hexadecimal integers such as 0xDEAD retain their integer meaning.

Conversion is independent of the host locale and accepts finite normal and subnormal results. Overflow and nonzero literals that round to zero are compile errors, including during editor analysis. Exact zero remains valid with any exponent magnitude; unary minus preserves its negative sign. These rules apply to Ny and Matrix and to textual/binary NIL loading.

String Literals

"Hello, World!"
"Multi-line
string"

Ny text literals decode \", \\, \n, \r, \t, \v (vertical tab), \f (form feed), and \0. Native text does not support embedded NUL. Other escape spellings are unsupported; current diagnostic limitations are tracked in F20. Matrix text uses raw literals and named constants instead of Ny escape syntax.

Character Literals

'a'
'\n'        # newline

Integer/float suffixes such as 42i64 and 3.14f32, and hexadecimal character escapes such as '\xFF', are not implemented syntax.

Boolean Literals

true
false

Arithmetic Operators

let sum = a + b
let diff = a - b
let prod = a * b
let quot = a / b
let mod = a % b
let neg = -x

Comparison Operators

a == b      # equal
a != b      # not equal
a < b       # less than
a > b       # greater than
a <= b      # less or equal
a >= b      # greater or equal

Logical Operators

a and b     # logical and
a or b      # logical or
not a       # logical not

Bitwise Operators

a & b       # and
a | b       # or
a ^ b       # xor
~a          # not
a << b      # left shift
a >> b      # right shift

Range Expressions

for index in range(1, 5)
    println(index)
end for

The loop above visits 1 through 4. range(end) starts at zero. Standalone range values and inclusive ... syntax are not implemented.

Member Access

object.field           # field access
object.method()        # method call
array[0]               # index

Function Calls

let result = foo(arg1, arg2)
let result = obj.method()

Control Flow Expressions

If Expression

let x = if condition then value1 else value2 end if

# Or as statement
if x > 0 then
    println("positive")
else
    println("non-positive")
end if

Match Expression

let message = match value {
    1 -> "one";
    2 -> "two";
    _ -> "other";
}

Expression matches require a final unguarded _ arm and one value-producing expression per arm. Void calls, assignments, and statement blocks cannot supply that value. Guards use pattern when condition -> value. A parenthesized match used as an expression statement discards exactly its selected result.

Native control-flow joins preserve pending expression operands and selected values, including nested if/match expressions and later call arguments. Incoming branches must agree on stack height and exact ABI type; mismatched raw NIL fails explicitly. Statement-form matches have a separate contract.

do blocks do not provide expression values. Use an explicitly returning function when a computation needs several statements.

Switch Expression

switch can run statements and fall through cases before producing a value. Ny uses break value; Matrix uses stop switching with value. Every normal exit must provide a compatible result, and a default is required. See the switch reference for both surfaces and their exit rules.

Formatted text

An explicit formatted string evaluates expressions inside braces:

let count = 3
let offset = -1.6
let message = $"Count: {count + 1}; offset: {offset}"
let braces = $"{{literal braces}} and {count}"

Each expression uses ordinary Ny syntax, including calls, member access, conditionals and nested quoted strings. Expressions are evaluated exactly once, from left to right. The result is text. A hole must produce text, bool, i32, i64, u8 or f64; convert other values explicitly with an appropriate library function or method. Numeric text is independent of the current locale, and the same conversion is used by the interpreter and native compiler. Native text retains its existing NUL-free restriction; formatted text does not change the text storage ABI or permit embedded NUL constants natively.

Ny's multiline form opens with $""" at the end of its source line, apart from spaces or tabs; content starts on the following line. It closes with the first line whose non-indentation content begins with """. Lexing resumes after that delimiter, so a block can sit inside a call:

println($"""
    <p>Signed in as {who}</p>
    <p>{count + 1} projects</p>
""")

A block is raw: unlike the quoted form, its literal segments carry no backslash escapes, which is what makes a path, a regular expression or embedded JSON writable without doubling anything. The block's common leading indentation is removed and deeper indentation is kept, leading and trailing blank lines are dropped, and indentation removal touches literal segments only, so every hole keeps its original file coordinates.

{{ and }} insert literal braces. Ny's normal backslash escapes still apply to the literal portions of a quoted formatted string, so \n inserts a newline in the result. Embedded expressions keep their own string delimiters; no extra escaping is needed for $"Result: {choose("first", "second")}".

A quoted explicit string, including its expressions, must fit on one source line. Both surfaces have a block form that spans lines, and a single hole still stays on one of them. Empty holes, trailing tokens, unmatched braces and missing quotes are errors. Formatting flags and precision specifiers are not part of this syntax; use an explicit formatting function inside a hole when needed.

Legacy ordinary strings such as "Hello {name}" retain identifier-only interpolation for compatibility. Use the explicit form for expression interpolation and editable source locations inside holes. Existing literal "{count + 1}" text does not acquire new expression semantics.

Matrix uses the same semantics with a contextual word:

value count is 3
value offset is negative 1.6
value message is formatted "Count: {count plus 1}; offset: {offset}"

Ordinary Matrix quoted strings and begin text blocks remain raw. Within formatted Matrix text, backslashes remain ordinary characters; use the named newline, tab and quote values where needed, such as formatted "First{newline}Second". Braces delimit ordinary Matrix expressions, including named calls such as {choose with first being "one"}.

formatted in front of begin text opts a raw block into interpolation:

value page is formatted begin text
    <p>Signed in as {who}</p>
    <p>{count plus 1} projects</p>
end text

The block keeps every raw-block rule — a line-anchored end text terminator, removal of the common leading indentation, retained deeper indentation, dropped leading and trailing blank lines, and no escape sequences — and adds the holes. Indentation removal applies to literal segments only. Every hole retains its original file coordinates, so definition, completion, signature help and local rename behave inside a block exactly as they do inside a quoted formatted literal. A block and a quoted literal produce the same interpolation AST, the same shared conversion and the same lowering on both execution routes.

Markup literals

A markup literal holds a document — elements, attributes, text and holes — and its own control flow, so a generated page is written as one unit instead of assembled from concatenated fragments. Matrix opens one with begin markup, Ny with $markup, and both close with the block's own terminator:

import nil.std.markup.escaping

fn page(signed_in: bool, who: text, names: array<text>) -> document
    return $markup
        <nav>
          {if signed_in}
            <a href="/logout">Log out, {who}</a>
          {else}
            <a href="/login">Log in</a>
          {end if}
        </nav>
        <ul>
          {for name in names}
            <li class="{name}">{name}</li>
          {end for}
        </ul>
    end markup
end fn

The directive words are each surface's own: Ny writes {if}, {elseif}, {else}, {end if}, {for x in xs} and {end for}, while Matrix writes {when}, {otherwise when}, {otherwise}, {end when}, {repeat for each x in xs} and {end repeat}. Everything else is shared, including the parsing of the document, the checks, the escaping and the value.

The literal segments are parsed as markup at compile time. Unbalanced or unclosed elements, an unterminated directive, an arm that opens an element it does not close, and a hole that would name an element or an attribute are compile errors. Element and attribute names are fixed; that is what keeps the document checkable. Self-closing syntax is limited to HTML void elements such as <br/>; other elements need a closing tag. The initial profile uses HTML tables, without SVG or MathML namespace semantics.

Ordinary holes accept text, bool, i32, i64, u8 and f64, escaping them for their position. A nil.std.markup.document also composes into element content without being escaped again. Arrays and optional values need explicit loops or conversions; they do not splice or omit attributes automatically.

A whole URL hole uses a limited executable-scheme filter, while a component hole needs a fixed safe URL prefix. Directives inside URL attribute values and ordinary holes in code-bearing or URL-list attributes are rejected. See the nil.std.markup escaping contract for the exact policy. {raw ...} explicitly trusts its input and bypasses escaping; it is not a sanitizer.

The block evaluates to a document record containing serialized text. render returns that text; it does not walk a runtime tree. XML serialization and a compact renderer are not implemented.

Inside <script> and <style> a brace is an ordinary character, so CSS and JavaScript paste in unaltered; a body that is exactly one hole must be {raw ...}. Elsewhere {{ and }} are literal braces, as in formatted text.

$markup must be the last thing on its line apart from spaces or tabs. Ny's terminator begins a line after indentation, and lexing resumes after end markup, allowing the surrounding expression to continue. Matrix's end markup occupies its own line. Both surfaces keep markup and raw usable as ordinary names outside these constructs.

Lambda / Anonymous Functions

let add = fn(a: i32, b: i32) -> i32
    return a + b
end fn

Noncapturing lambda invocation is covered on interpreted routes. Captures, shorthand lambdas, and native indirect calls are not supported by this example.

Type Cast

let n: f64 = 42 as f64

See types for the scalar conversion contract. Legacy interpreted text casts are not evidence of equivalent native conversion behavior.