Expressions and operators#
Expressions combine values into a result. Parentheses make grouping explicit, and pipe flows let a sequence of transformations read from top to bottom. The tables below give precedence and accepted operand types.
Precedence and grammar#
Rows are ordered from highest to lowest precedence.
| Form | Associativity and restriction |
|---|---|
Member access ., type application or list indexing [...], call (...), propagation ? | Left to right; brackets specialize declarations or index lists |
Prefix +, - | Right to left |
*, /, % | Left to right |
+, - | Left to right |
Range .. | Non-chainable; Int bounds, excludes the end; see loops |
<, <=, >, >=, ==, != | One comparison of either kind; cannot be chained or mixed without parentheses |
not | Right to left; its operand includes comparisons |
and | Left to right, short circuit |
or | Left to right, short circuit |
if c { a } else { b } | A primary expression; its branches are full expressions; else if chains |
Pipe | | Left to right; lowest precedence, see pipe flows |
Expression = Pipe ;
Pipe = OrExpression, { "|", PipeStep } ;
PipeStep = ( Name, { ".", Name }, [ CallArguments ] [ "?" ] | Postfix-from-dot ) ;
OrExpression = AndExpression, { "or", AndExpression } ;
AndExpression = NotExpression, { "and", NotExpression } ;
NotExpression = "not", NotExpression | Comparison ;
Comparison = Range, [ ("<" | "<=" | ">" | ">=" | "==" | "!="), Range ] ;
Range = Sum, [ "..", Sum ] ;
Sum = Product, { ("+" | "-"), Product } ;
Product = Prefix, { ("*" | "/" | "%"), Prefix } ;
Prefix = ("+" | "-"), Prefix | Postfix ;
Postfix = Primary, { ".", Name | TypeArguments | "[", Expression, "]" | CallArguments | "?" } ;
CallArguments = "(", [ Argument, { ",", Argument }, [ "," ] ], ")" ;
Argument = [ Name, ":" ], [ "var" ], Expression ;
Primary = IntLiteral | FloatLiteral | DecimalLiteral | StringLiteral
| "true" | "false" | "void" | "self" | Name
| "(", Expression, ")" | ListLiteral | MapLiteral | FunctionExpression | MatchExpression | IfExpression ;
ListLiteral = "[", [ Expression, { ",", Expression }, [ "," ] ], "]" ;
MapLiteral = "{", [ MapEntry, { ",", MapEntry }, [ "," ] ], "}" ;
MapEntry = Expression, ":", Expression ;
FunctionExpression = "fn", [ Name, { ",", Name } ], FunctionSuite
| "fn", "(", [ CallbackParameters ], ")", [ Type ], FunctionSuite ;
IfExpression = "if", Expression, ":", Expression, "else", ( ":", Expression | IfExpression ) ;
MatchExpression = "match", Expression, ":", NEWLINE, INDENT,
MatchArm, { MatchArm }, DEDENT ;Postfix-from-dot in PipeStep is a chain starting with ., such as .trim() or .items[0].name.
a < b == c,a == b == c, anda < b < care syntax errors;(a < b) == flagis ordinary Bool equality.not a == bmeansnot (a == b).read()? + 1means(read()?) + 1; write(expression)?to propagate a larger expression.- Brackets after a generic declaration supply types (
identity[Int],Box[String]); after a list value they look up:values[index]returns aT, accepts negative indexes, and faults when the index is out of range.values[index] = xandvalues[index] += xare thesetmutator (values.set(index, x)); the receiver must be avar. Slicing is unsupported. - Calls take positional arguments and optional labels (call rules
). Single-payload constructors may omit the label:
Box(3),ok(3). An interface is never constructed; see interface conversion .
Pipe flows#
lhs | step passes lhs to the step. The parser rewrites each step into the ordinary call it names.
| Step | Means |
|---|---|
x | f | f(x) |
x | f(a: 1) | f(x, a: 1): x becomes the first positional argument |
x | m.f(2) | m.f(x, 2) |
x | .m(2) | x.m(2): a method, field, or index chain on the value |
x | f? | f(x)?: propagate the step’s error |
x | .m()? | x.m()? |
Save as port.ms and run ms run port.ms:
fn port_number(text String) Int! {
port := (
text.trim()
| .parse_int()
| ok_or(Error("expected a port number"))?
)
return ok(port)
}
fn main() Int {
if port := port_number(" 8080 ") {
print(port)
return 0
}
return 1
}8080|has the lowest precedence:a + b | fisf(a + b). Parenthesize a pipe used as an operand:(x | f) == y. A?binds only the expression before it:read(path: path)? | f.- A step is a name or member path, optionally with one argument list, or a
.chain. Literals, function expressions, and calls inside the path are not steps; bind the function to a name first. x | f(...)always insertsxas the first positional argument; it cannot apply a function thatf(...)returns.- A trailing
?on a step unwraps its result under the propagation rules . Without?, a Result passes through unchanged. A flow may have several?steps. .member, call, or index directly after a step applies to its result:x | f(a: 1).size()isf(x, a: 1).size(). A.memberon the next line is not part of the step: usex | .size()?to propagatex.size().- A line starting with
|or.continues the statement;ms fmtindents it one level past the statement’s first line.
Operand and result types#
| Operator | Accepted operands | Result |
|---|---|---|
Unary +, - | Signed integer or float widths, Decimal, or BigInt; unary + also accepts unsigned integers | Same numeric type |
+, -, *, / | Matching integer or float types, both Decimal, or both BigInt | The common operand type |
+ | Both String | String |
% | Matching integer types, or both BigInt | The common operand type |
.. | Both Int | List[Int]; a direct for uses a counter loop |
<, <=, >, >= | Same exact type satisfying Comparable
: integer and float types, Decimal, BigInt, String, Duration, Instant, Timestamp, a type with its own compare, or a type parameter bounded by Comparable | Bool |
==, != | Same exact type satisfying Equal | Bool |
not | Bool | Bool |
and, or | Both Bool | Bool |
postfix ? | Result[T, E], with a compatible enclosing Result error type | T on success; propagates E on failure |
Decimal, BigInt, Duration, Instant, and Result rows apply only to the standard declarations; a local type with the same name does not enable them.
- String ordering is lexicographic by Unicode scalar value, with no normalization, case folding, or collation.
- Mixed numeric arithmetic, numeric truthiness, and operator overloads do not exist:
1 + 0.5,"a" + 1, andnot 1fail checking. Convert or interpolate instead. - Duration and Instant have no arithmetic operators; use their methods (
add,subtract,shift,difference). Only the ordering operators apply to them, and Instants must share a clock domain. - Bool, lists, maps, nullables, enums and records without their own
comparehave no order:true < falseand[1] < [2]fail checking.
See equality and hashing , type rules , and numeric outcomes .
Never operands#
The operand types, not the expected result type, select the operator row.
- Numeric arithmetic, ordering, and equality: the non-Never operands must fix one eligible type; Never fills the rest.
- Time arithmetic: known operands must select exactly one row.
- Two Never operands cannot select a numeric, ordering, or equality row; unary signs and
?need an independently known operand. not,and, andortake Bool, so Never is fine.
The result keeps the row’s type: 1 + panic(message: "stop") is Int; 1 == panic(message: "stop") is Bool. x Int := -panic(message: "stop") is rejected.
See compatibility
and error propagation
for Never in calls, returns, and ?.
Source location#
__LINE__ is the Int line number of the token and __FILE__ is the String name of the file being compiled; both are constants filled in at the use site, so inside a function they name where it is written, not where it is called. A local binding or declaration with either name shadows the constant. To report a caller’s position, use a parameter default of caller_site() from @std/test/test.ms (file:line:col) or caller_frame() from @std/concurrency/promise.ms (file:line in function, the form a fault report shows) instead.
fn main() Void {
print(f"{__FILE__}:{__LINE__}")
}Evaluation#
- Subexpressions evaluate left to right, each once. The right side of
false and ...andtrue or ...is skipped but must still type-check. - A call evaluates its callable or receiver first, then arguments in written order (not parameter order).
- Indexing evaluates the receiver, then the index.
- List elements and map entries evaluate in written order, key before value (collections ).
- A function expression only creates a value; its body runs on invocation (closures ).
- Interpolation evaluates embedded expressions once, in order (text and bytes ).
- If a subexpression exits by Result propagation or fault, later subexpressions and the operation do not run.
Examples#
fn calculated(value Int, active Bool) Int {
product := 1 + 2 * 3 // 7
same := not value == product // not (value == product)
if active and same {
return product
}
return value
}fn invalid(value Int, ratio Float) Bool {
mixed := value + ratio // Type error: exact numeric types differ.
return 0 < value < 10 // Syntax error: comparison chain.
}Not expressions: assignment (a statement
), bitwise operators, exponentiation, tuples, and general expression-valued blocks. Conditional expressions use if condition { a } else { b }; see conditionals
.