Scope and ownership
СсылкаThis page owns expression grouping, operators, ranges, and member and index access.
It also specifies the retirement of pipeline, composition, and expression-placeholder syntax. Functions and generics owns call argument binding. Collections and comprehensions owns collection construction. Type and library entries own individual members. Pattern matching owns wildcard patterns. Failure and propagation owns postfix ? behavior.
Selected source forms
СсылкаGrouped = "(" Expression ")" ;Unary = ("-" | "!") Unary | Power ;Power = Postfix ["**" Unary] ;RangeShape = Additive (".." | "..<") Additive ["by" Additive] ;IndexSuffix = "[" Expression "]" ;MemberSuffix = "." MemberName ;OptionalMemberSuffix = "?." MemberName ;
This handwritten excerpt shows selected source forms. The precedence record supplies the grouping between operator families. It omits call argument lists, collection construction, and other page-owned syntax; parsing alone does not establish operand legality.
Grouping and postfix forms
Empty parentheses form the unit literal (). Parentheses around one expression explicitly group that expression. A parenthesized comma list is rejected during parsing with TPZ2001. Postfix extensions attach to the preceding expression in source order.
Parentheses select a grouping for an expression. The unit literal () is documented in Literals and templates. Function argument binding, collection construction, propagation, and nominal updates keep their own owners; their suffixes appear here only to locate their grouping.
Причина
Explicit grouping makes operand relationships visible. An ordered postfix chain gives each extension one receiver.
Explicit control operands
A control operand has a required outer pair of parentheses. The construct consumes that pair and parses its contents with the ordinary expression grammar. Record construction, record update, and lambdas keep the same forms they have in a binding or call argument. Their result types are checked separately.
| Position | Canonical form |
|---|---|
| if test | if (test) { body } |
| if-let value | if let Pattern = (value) { body } |
| while test | while (test) { body } |
| while-let value | while let Pattern = (value) { body } |
| for iterable | for Pattern in (iterable) { body } |
| using value | using name = (value) { body } |
| match scrutinee | match (value) { cases } |
| match guard | case Pattern if (test) => body |
| comprehension iterable | [for Pattern in (iterable) => value] |
| comprehension filter | [for Pattern in (iterable) if (test) => value] |
Omitting the required pair is rejected during parsing with TPZ2001. Extra parentheses inside the pair retain ordinary grouping. The existing concurrent(timeout: expression) argument list already delimits its timeout expression. A loop has no operand.
Причина
An undelimited input and the same input inside the required parentheses supply the same condition, matched value, iteration source, or resource. The boundary preserves that intent and lets each position use ordinary expression grammar. Record construction and updates retain their existing forms, and lambdas retain one parenthesized parameter list. Parentheses inside an operand group that expression. The explicit boundary prevents a record body or a lambda arrow from taking the place of the following control body or case arrow.
Precedence and associativity
СсылкаPrecedence and associativity
Higher rows bind more tightly. These rows specify parser grouping. Operand-type acceptance is checked separately.
| Rank | Forms | Association | Binary parser level |
|---|---|---|---|
| 1 | call suffix, index suffix, member suffix, optional-, propagation suffix, record- | Successive postfix extensions | Separate parser production |
| 2 | ** | Right | Separate parser production |
| 3 | prefix -, ! | Recursive prefix | Separate parser production |
| 4 | *, /, % | Left | 9 |
| 5 | +, - | Left | 8 |
| 6 | ., . | Left | 7 |
| 7 | ==, !=, <, <=, >, >=, in | Left | 6 |
| 8 | && | Left | 5 |
| 9 | \|\| | Left | 4 |
| 10 | ?? | Left | 3 |
A prefix on the left applies outside power. The right operand of ** admits unary syntax. The range row accepts the by step clause.
| Expression | Grouping |
|---|---|
- | - |
2 ** 3 ** 2 | 2 ** (3 ** 2) |
a ?? b ?? c | (a ?? b) ?? c |
The structured table describes grouping. A parsed combination can still fail type checking. Equality, ordering, and in share one level, and ?? groups to the left.
Power accepts a unary expression on its right. Thus - groups as -, while 2 ** - parses with a negative exponent. The integer exponent restriction is a separate runtime condition.
Причина
A fixed precedence table makes expression grouping independent of whitespace. The same grouping applies before operand types are checked.
Unary, binary, and logical operators
СсылкаUnary operators
| Operators | Operand types | Result | Operation |
|---|---|---|---|
! | bool | bool | Logical negation |
- | int, float, Big, Decimal | Operand type | - negates the value |
Prefix + is rejected during parsing with TPZ2001. Use the operand directly. Binary + remains addition.
Literal sign rules are defined by Literals and templates. Other operand families remain Pending.
Literal bounds are covered by Literals and templates. This rule covers operators applied to values. Unary minus negates a value and does not introduce another numeric type.
Причина
An ordinary expression already denotes its value, so an identity prefix would add another spelling. Numeric negation preserves the operand type.
Arithmetic operands and results
The following operand pairs produce the listed result types.
| Operators | Left operand | Right operand | Result | Operation |
|---|---|---|---|---|
+, -, *, /, ** | int | int | int | Arithmetic |
+, -, *, /, ** | float | float | float | Arithmetic |
% | int | int | int | Arithmetic |
+ | string | string | string | Concatenation |
+, -, * | Big | Big | Big | Arithmetic |
+, -, * | Decimal | Decimal | Decimal | Arithmetic |
Mixed int/float operands are rejected during checking. Integer and Length value boundaries are specified below.
Arithmetic examples use small integers so grouping is visible independently of overflow boundaries. BigInt and Decimal division APIs belong to their library entries. The Types and Literals pages own type forms, literal bounds, and units.
The Decimal value contract defines exact decimal arithmetic and canonical scale. Explicit BigInt division and remainder follow the BigInt contract. Duration arithmetic and range failures follow the Duration value rule.
Evaluation follows the operand and assignment order.
Причина
Requiring matching numeric types avoids implicit changes in precision. Explicit result types let arithmetic participate in the same type checks as other expressions.
Integer and Length value boundaries
Integer arithmetic stays within - through 9223372036854775807. Division truncates toward zero. A nonzero remainder has the dividend's sign. Integer 0 ** 0 is 1.
| Boundary | Runtime diagnostic |
|---|---|
| Integer or Length division by zero, or integer remainder by zero | TPZ4002 |
| Integer overflow, including minimum int divided or reduced modulo -1 | TPZ4004 |
| Integer power with a negative exponent | TPZ4005 |
| Integer exponent greater than 4294967295, even with base 0 or 1 | TPZ4004 |
| Unrepresentable Length result or a non-finite scaling operand | TPZ4004 |
Length operations use the following operand pairs. U denotes the same unit on both Length operands. Mixed units are rejected during checking.
| Operators | Left | Right | Result |
|---|---|---|---|
+, - | Length<U> | Length<U> | Length<U> |
/ | Length<U> | Length<U> | float |
* | Length<U> | int- | Length<U> |
* | int- | Length<U> | Length<U> |
/ | Length<U> | int | Length<U> |
Length multiplication and integer division round to the nearest representable fixed-precision value, with ties choosing the even value. Dividing two Length values gives their floating-point ratio.
When a constant initializer reaches a numeric fault, checking rejects it with TPZ5001 and a message beginning constant expression error:.
The physical length contract defines stored scaled points and explicit unit conversions.
Причина
Checked arithmetic prevents silent wraparound in computed sizes. Matching length units prevents accidental mixing of document measurements. Ties-to-even rounding avoids a consistent bias at exact halfway values.
Comparison and membership
==, != compare equality, and <, <=, >, >= compare order. The operands must have compatible, comparable types. These operations produce bool. Comparison capabilities are defined by Protocols and implementations. A declared nominal Eq or Order conformance supplies both its protocol-qualified method and the corresponding operators. Nested derived comparisons use that same conformance.
Write element membership as element in container. in produces bool for Array<T>, Set<T>, Range<int>. The value must be compatible with the container's element type. Range membership requires both bounds and step alignment. Map, string are rejected as membership containers during checking.
Substring search and Map key lookup follow their distinct library contracts.
The comparison operators produce Boolean results after the relevant type and capability checks. General compatibility and protocol resolution are documented by Types and Protocols and implementations. For a range, membership also considers its step.
The Decimal comparison contract defines exact equality and ordering independently of input padding.
Причина
Set. and in ask the same question about whether an equal element belongs to a set. The in operator expresses that membership intent for arrays, sets, and integer ranges. Range membership includes step alignment so it agrees with iteration. Substring search and Map key lookup retain their distinct input and result contracts.
Logical operators and coalescing
The left operand is evaluated first. The following cases skip the right operand and produce the indicated value. Otherwise, the right operand is evaluated and supplies the result.
| Operator | Left type | Right type | Skip right when left is | Result when skipped | Evaluate right when left is |
|---|---|---|---|---|---|
&& | bool | bool | false | false | true |
\|\| | bool | bool | true | true | false |
?? | Option<T> | T | Some(value) | value | None() |
?? | T \| null | T | non- | left | null |
The short-circuit decision follows evaluation of the left operand. In the example, any call to mark would print an extra line; that line is absent from the independent expected output.
Причина
Skipping an unused operand avoids its effects and failures. This lets a guard or fallback depend on the value already computed.
Derived equality and operators use the inner manual equality
Ссылкаimport std.io { writeLine }record Token { key: int, noise: int }impl Eq<Token> {function equals(a: Token, b: Token) -> bool { a.key == b.key }}record Box derives Eq { item: Token }let a = Box { item: Token { key: 1, noise: 10 } }let b = Box { item: Token { key: 1, noise: 20 } }let c = Box { item: Token { key: 2, noise: 10 } }writeLine("{Eq.equals(a, b)}")writeLine("{a == b}")writeLine("{Eq.equals(a, c)}")writeLine("{a != c}")
true
true
false
true
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
truetruefalsetrue
A manual equality hides an opaque field from outer operators
Ссылкаimport std.io { writeLine }record Callback { key: int, run: () -> int }impl Eq<Callback> {function equals(a: Callback, b: Callback) -> bool { a.key == b.key }}record Box derives Eq { item: Callback }let a = Box { item: Callback { key: 1, run: () => 7 } }let b = Box { item: Callback { key: 1, run: () => 9 } }writeLine("{a == b}")writeLine("{Eq.equals(a, b)}")
true
true
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
truetrue
Derived ordering and operators use the inner manual ordering
Ссылкаimport std.io { writeLine }record Rank { score: int }impl Order<Rank> {function compare(a: Rank, b: Rank) -> int {if (a.score > b.score) { -1 } else if (a.score < b.score) { 1 } else { 0 }}}record Box derives Order { item: Rank }let a = Box { item: Rank { score: 9 } }let b = Box { item: Rank { score: 3 } }writeLine("{Order.compare(a, b)}")writeLine("{a < b}")writeLine("{Order.compare(b, a)}")writeLine("{b > a}")
-1
true
1
true
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
-1true1true
Operand and assignment evaluation order
Binary expressions evaluate their operands from left to right. The same order applies within nested operands. The first runtime fault terminates evaluation, so later operands do not run. The short-circuit rule still determines whether a right operand runs.
| Assignment form | Evaluation order |
|---|---|
x = value() | Evaluate the right value, then write x. |
a[index()] = value() | Evaluate the receiver, evaluate the index, validate the slot, evaluate the right value, then write the slot. |
record. | Evaluate the right value, then read the named record root, update the field, and write the root. |
a[index()]. | Evaluate the receiver and index, validate the slot, evaluate the right value, then read the record, update the field, and write the slot. |
x += value() and other compound arithmetic assignments | Evaluate the target and read its old value, evaluate the right value, apply the operation, then write the result. |
A fault in an earlier assignment step prevents later steps. Assignment does not give a named record field a read before its right-hand value.
The short-circuit rule determines which operands run. Function calls keep their argument evaluation order.
Причина
One operand order makes effects and the first fault reproducible. Existing assignment forms retain their evaluation order.
Ranges and access
СсылкаRanges and steps
Both endpoints are required and have type int. The result has type Range<int>.
| Operator | Upper bound |
|---|---|
. | inclusive |
. | exclusive |
The by clause supplies an int step. Its default is 1. The sequence begins at the first endpoint and advances by adding the step. A positive step advances toward an increasing end value. A negative step advances toward a decreasing end value. Bounds in the wrong direction produce an empty range.
Membership requires bounds and step alignment. A zero step is invalid. A statically detected zero step is rejected during checking. A zero step that reaches evaluation causes a runtime fault. Iteration is defined by Blocks and control flow.
The by clause is part of the range expression. An inclusive upper bound is included only if the sequence reaches it. Blocks and control flow describes how for consumes a range; collection construction is documented separately.
Причина
Explicit bounds and steps define the visited integers without materializing an array. Membership and iteration use the same sequence.
Member, index, and optional access
object. follows the selected type or library entry's member contract. array[index] accepts an int index into Array<T> and produces T. Indices start at 0. Other index types are rejected during checking. Negative or out-of-bounds indices cause a runtime fault.
object?. accepts Option<T>, T | null.
| Receiver | Member access and result |
|---|---|
None() | Skip access and produce None() |
null | Skip access and produce null |
Some(value) | Access the wrapped value and produce one Option layer, flattening an existing Option result |
non- | Access the value and produce the member result |
| Receiver type | Result type |
|---|---|
Option<T> | Option<member- with one-layer flattening |
T \| null | member- |
A member name selects a field or member whose individual contract belongs to its type or library entry. The access example uses an existing array's length property only to show optional access. Array construction, mutation, and the property's API contract are outside this page.
Evaluation follows the operand and assignment order.
Причина
Optional access skips a member lookup when its receiver is absent. Bounds checks prevent an invalid array position from producing an ordinary element value.
Choose Unicode scalars or grapheme clusters explicitly
text. returns Array<string> in source order. Each element contains one Unicode scalar value. Empty text returns an empty array. The operation preserves the stored scalars without normalization. Joining its elements with an empty separator reproduces the original string.
text. follows the Unicode grapheme contract. Use the returned array's length and indexing operations for the chosen text unit.
Loop inputs follow the iteration rule. Choose scalar values or grapheme clusters explicitly before iterating over text.
Причина
A scalar and a grapheme cluster are different text units. Explicit names preserve scalar algorithms while allowing document editing to keep combining marks, Hangul syllables, and emoji sequences together. Unicode 16 matches the language character data and gives every host the same boundaries. Returning an Array reuses its count and index operations without additional string spellings.
Calls and function composition
СсылкаOrdinary calls and saved values
Write calls as callee(arguments) and members as value.. Bind an intermediate value with let when it must be evaluated once or reused.
Method chains and successive let bindings read from the input through its transformations in order.
|> is rejected during parsing with TPZ2001. This includes bare-callable, inserted-argument, placeholder, and member-shortcut stages. A standalone expression _ is also rejected during parsing.
When migrating a pipeline with effects, bind the input first, then evaluate the callee and written arguments in their required order. The resulting ordinary call follows Functions and generics.
Use a named binding when one computed value is needed more than once. A wildcard _ belongs to a pattern and has no expression meaning. Ordinary calls use the argument binding rules in Functions and generics.
Причина
A pipeline and a method chain both present a value followed by the transformations that consume it. When the transformations are ordinary functions, successive let bindings present the same input-to-result reading order. These forms preserve the intended data flow and make evaluation and reuse explicit. Written call arguments keep each consumed value visible. Bind effectful input, callee, and argument expressions in their required order when replacing a pipeline.
Compose calls in a function body
Compose calls in a function body, for example (value: T) => second(first(value)). Input, intermediate, and result types follow ordinary function and call rules.
The body can name successive results with let in data-flow order.
The >> composition operator is rejected during parsing with TPZ2001. Bind function values before constructing the lambda when their evaluation or capture must happen once.
To preserve composition-time evaluation, first bind each function value once and in the desired order. Capture those immutable bindings in the function body. Later calls then reuse the same function values.
Причина
A composition operator and a function body both describe a transformation whose result becomes the next transformation input. Successive let bindings inside the body read in that same data-flow order, and ordinary call typing preserves the intermediate types. Binding function values before constructing the body preserves evaluation and capture that must happen once.
Examples and expected results
СсылкаEach example is a complete source file with an independent expected result and an assertion plan. No execution receipt is attached. Missing boundary coverage remains explicit; a future observation that differs from an intended result requires triage and an implementation limitation when appropriate, rather than replacement of the expectation.
Grouping arithmetic and power
Ссылкаimport std.ioio.writeLine("{2 + 3 * 4}")io.writeLine("{(2 + 3) * 4}")io.writeLine("{20 - 5 - 3}")io.writeLine("{2 ** 3 ** 2}")io.writeLine("{-2 ** 2}")io.writeLine("{(-2) ** 2}")
14
20
12
512
-4
4
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
142012512-44
Наблюдаемые утверждения · Пройдено · 5.21.3
Код завершения 0.
142012512-44
Нет вывода ошибок.
- Пройдено · expected 0; observed 0
- Пройдено · stdout matches the authored expectation
- Пройдено · stderr matches the authored expectation
- Пройдено · stdout matches the authored expectation
- Пройдено · stdout matches the authored expectation
The expected result is specified from the source contract. This exact fixture has not been run on a public Topaz 5.21.x CLI.
Skipping a right operand
Ссылкаimport std.iofunction mark() -> bool {io.writeLine("evaluated")true}io.writeLine("{false && mark()}")io.writeLine("{true || mark()}")let present: Option<int> = Some(7)let absent: Option<int> = None()io.writeLine("{present ?? 9}")io.writeLine("{absent ?? 9}")
false
true
7
9
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
falsetrue79
Наблюдаемые утверждения · Пройдено · 5.21.3
Код завершения 0.
falsetrue79
Нет вывода ошибок.
- Пройдено · expected 0; observed 0
- Пройдено · stdout matches the authored expectation
- Пройдено · stderr matches the authored expectation
The expected result is specified from the source contract. This exact fixture has not been run on a public Topaz 5.21.x CLI.
Apply ordinary calls and a function body
Ссылкаimport std.iofunction increment(n: int) -> int { n + 1 }function double(n: int) -> int { n * 2 }function subtract(a: int, b: int) -> int { a - b }let composed = (n: int) => double(increment(n))io.writeLine("{double(increment(3))}")io.writeLine("{composed(3)}")io.writeLine("{subtract(10, 3)}")io.writeLine("{subtract(3, 10)}")
8
8
7
-7
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
887-7
This fixture uses ordinary calls and a lambda. Its expected values are unchanged. Product execution of this revised fixture remains pending.
Membership respects a range's step
Ссылкаimport std.iolet odd = 1..<6 by 2io.writeLine("{1 in odd}")io.writeLine("{2 in odd}")io.writeLine("{5 in odd}")io.writeLine("{6 in odd}")
true
false
true
false
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
truefalsetruefalse
Наблюдаемые утверждения · Пройдено · 5.21.3
Код завершения 0.
truefalsetruefalse
Нет вывода ошибок.
- Пройдено · expected 0; observed 0
- Пройдено · stdout matches the authored expectation
- Пройдено · stderr matches the authored expectation
- Пройдено · stdout matches the authored expectation
The expected result is specified from the source contract. This exact fixture has not been run on a public Topaz 5.21.x CLI.
Indexing and optional member access
Ссылкаimport std.iolet values = [4, 5]let present: Option<Array<int>> = Some(values)let absent: Option<Array<int>> = None()io.writeLine("{values[0]}")io.writeLine("{present?.length ?? 0}")io.writeLine("{absent?.length ?? 0}")
4
2
0
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
420
Наблюдаемые утверждения · Пройдено · 5.21.3
Код завершения 0.
420
Нет вывода ошибок.
- Пройдено · expected 0; observed 0
- Пройдено · stdout matches the authored expectation
- Пройдено · stderr matches the authored expectation
The expected result is specified from the source contract. This exact fixture has not been run on a public Topaz 5.21.x CLI.
Rejecting a parenthesized comma list
Ссылкаlet value = (1, 2)
Нет стандартного вывода.error[TPZ2001]: parentheses group a single expression; `(a, b)` comma lists are not Topaz syntax
--> example.tpz:1:15
|
1 | let value = (1, 2)
| ^
example.tpz: 1 diagnostic
Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
parenthesized-comma-list at
example.tpz:1:15
Наблюдаемые утверждения · Пройдено · 5.21.3
Код завершения 1.
Нет стандартного вывода.
error[TPZ2001]: parentheses group a single expression; `(a, b)` comma lists are not Topaz syntax--> example.tpz:1:15|1 | let value = (1, 2)| ^example.tpz: 1 diagnostic
- Пройдено · expected nonzero; observed 1
- Пройдено · checking TPZ2001; cause parenthesized-comma-list; primary location asserted; additional diagnostics allow
This fixture expects rejection at the comma because parentheses group a single expression. It is run through check so parsing is reached, and requires the parsing diagnostic and its location. The exact public CLI observation is pending.
Signed division, zero power, and Length arithmetic
Ссылкаimport std.iolet quotient = -7 / 3let remainder = -7 % 3let zeroPower = 0 ** 0io.writeLine("{quotient} {remainder} {zeroPower}")io.writeLine("{(1pt + 2pt) == 3pt}")io.writeLine("{(1pt * 2) == 2pt}")io.writeLine("{(2 * 1pt) == 2pt}")io.writeLine("{(1pt / 2) == 0.5pt}")io.writeLine("{3pt / 2pt}")
-2 -1 1
true
true
true
true
1.5
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
-2 -1 1truetruetruetrue1.5
The expected result follows from current SELF source. Execution against public Topaz 5.21.3 is pending CI.
Integer division by zero is rejected in a constant
Ссылкаconst bad = 1 / 0
Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
constant-integer-division-zero at
example.tpz:1:13
The expected result follows from current SELF source. Execution against public Topaz 5.21.3 is pending CI.
An overflowing integer constant is rejected
Ссылкаconst bad = 9223372036854775807 + 1
Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
constant-integer-addition-overflow at
example.tpz:1:13
The expected result follows from current SELF source. Execution against public Topaz 5.21.3 is pending CI.
An integer exponent must be non-negative
Ссылкаconst bad = 2 ** -1
Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
constant-integer-negative-exponent at
example.tpz:1:13
The expected result follows from current SELF source. Execution against public Topaz 5.21.3 is pending CI.
Length division by zero is rejected in a constant
Ссылкаconst bad = 1pt / 0
Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
constant-length-division-zero at
example.tpz:1:13
The expected result follows from current SELF source. Execution against public Topaz 5.21.3 is pending CI.
An unrepresentable Length constant is rejected
Ссылкаconst bad = 1pt * 9223372036854775807
Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
constant-length-unrepresentable at
example.tpz:1:13
The expected result follows from current SELF source. Execution against public Topaz 5.21.3 is pending CI.
Rejecting unary plus before an integer
Ссылкаlet value = +1
Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
removed-unary-plus at
example.tpz:1:13
Write 1 to use the integer value.
Rejecting unary plus before a bound value
Ссылкаlet value = 1let copy = +value
Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
removed-unary-plus at
example.tpz:2:12
Use the bound value directly.
Rejecting unary plus before a float
Ссылкаlet value = +1.5
Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
removed-unary-plus at
example.tpz:1:13
Write 1. to use the floating value.
Using ordinary values, negation, and binary addition
Ссылкаimport std.iolet value = 3io.writeLine("{1}")io.writeLine("{1.5}")io.writeLine("{value}")io.writeLine("{-value}")io.writeLine("{value + 2}")
1
1.5
3
-3
5
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
11.53-35
Ordinary values need no identity prefix. Unary minus and binary addition retain their arithmetic meanings.
Use in for arrays, sets, and ranges
Ссылкаimport std.iolet values = [1, 3]let members = set { 1, 3 }let odds = 1..<5 by 2io.writeLine("{1 in values}:{2 in values}")io.writeLine("{1 in members}:{2 in members}")io.writeLine("{1 in odds}:{2 in odds}")
true:false
true:false
true:false
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
true:falsetrue:falsetrue:false
A Map is not an element-membership container
Ссылкаlet found = "key" in map { "key": 1 }
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
map-not-element-membership
Контракт обязательного основного местоположения не определён.
Substring search is not element membership
Ссылкаlet found = "a" in "abc"
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
string-not-element-membership
Контракт обязательного основного местоположения не определён.
Keep combining marks, Hangul, and emoji in their grapheme clusters
Ссылкаimport std.iolet text = "é가👩💻🇰🇷"let clusters = text.graphemes()io.writeLine("{text.scalars().length}:{clusters.length}")io.writeLine("{clusters[0] == "é"}")io.writeLine("{clusters[1] == "가"}")io.writeLine("{clusters[2] == "👩💻"}")io.writeLine("{clusters[3] == "🇰🇷"}")io.writeLine("{clusters.join("") == text}")
9:4
true
true
true
true
true
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
9:4truetruetruetruetrue
Segment empty text, CRLF, leading marks, and regional indicators
Ссылкаimport std.iolet empty = "".graphemes()let lineBreak = "\r\n".graphemes()let marks = "́̂".graphemes()let flags = "🇰🇷🇯".graphemes()io.writeLine("{empty.length}:{lineBreak.length}:{marks.length}:{flags.length}")io.writeLine("{lineBreak[0] == "\r\n"}")io.writeLine("{marks[0].scalars().length}")io.writeLine("{flags[0] == "🇰🇷"}:{flags[1] == "🇯"}")
0:1:1:2
true
2
true:true
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
0:1:1:2true2true:true
Reject a pipeline into a bare callable
Ссылкаfunction increment(n: int) -> int { n + 1 }let value = 3 |> increment
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
removed-call-sugar
Контракт обязательного основного местоположения не определён.
Reject implicit pipeline argument insertion
Ссылкаfunction add(a: int, b: int) -> int { a + b }let value = 3 |> add(4)
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
removed-call-sugar
Контракт обязательного основного местоположения не определён.
Reject a pipeline placeholder
Ссылкаfunction subtract(a: int, b: int) -> int { a - b }let value = 3 |> subtract(10, _)
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
removed-call-sugar
Контракт обязательного основного местоположения не определён.
Reject a pipeline member shortcut
Ссылкаlet item = { answer: 7 }let value = item |> .answer
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
removed-call-sugar
Контракт обязательного основного местоположения не определён.
Reject the composition operator
Ссылкаfunction increment(n: int) -> int { n + 1 }function double(n: int) -> int { n * 2 }let composed = increment >> double
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
removed-call-sugar
Контракт обязательного основного местоположения не определён.
Reject a standalone expression placeholder
Ссылкаlet value = _
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
removed-expression-placeholder
Контракт обязательного основного местоположения не определён.
Save values to preserve call and composition effects
Ссылкаimport std.iofunction input() -> int {io.writeLine("input")3}function subtract(a: int, b: int) -> int { a - b }function stage() -> (int, int) -> int {io.writeLine("callee")subtract}function argument() -> int {io.writeLine("argument")10}let saved = input()let callee = stage()let written = argument()io.writeLine("{callee(written, saved)}")function increment(n: int) -> int { n + 1 }function double(n: int) -> int { n * 2 }function first() -> (int) -> int {io.writeLine("first")increment}function second() -> (int) -> int {io.writeLine("second")double}let left = first()let right = second()let composed = (n: int) => right(left(n))io.writeLine("{composed(3)}:{composed(5)}")
input
callee
argument
7
first
second
8:12
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
inputcalleeargument7firstsecond8:12
Reject an undelimited if operand
Ссылкаlet value = if true { 1 } else { 0 }
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
control-operand-parentheses at
example.tpz:1:16
Reject an undelimited if let operand
Ссылкаlet value = if let Some(item) = Some(1) { item } else { 0 }
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
control-operand-parentheses at
example.tpz:1:33
Reject an undelimited while operand
Ссылкаwhile false { () }
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
control-operand-parentheses at
example.tpz:1:7
Reject an undelimited while let operand
Ссылкаlet mut value: Option<int> = None()while let Some(item) = value { value = None() }
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
control-operand-parentheses at
example.tpz:2:24
Reject an undelimited for operand
Ссылкаfor item in [1] { let _ = item }
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
control-operand-parentheses at
example.tpz:1:13
Reject an undelimited using operand
Ссылкаfunction manage(file: File) -> () {using resource = file {}}
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
control-operand-parentheses at
example.tpz:2:20
Reject an undelimited match operand
Ссылкаlet value = match 1 { case _ => 2 }
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
control-operand-parentheses at
example.tpz:1:19
Reject an undelimited match guard operand
Ссылкаlet value = match (1) {case 1 if true => 1case _ => 0}
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
control-operand-parentheses at
example.tpz:2:13
Reject an undelimited comprehension iterable operand
Ссылкаlet values = [for item in [1] => item]
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
control-operand-parentheses at
example.tpz:1:27
Reject an undelimited comprehension filter operand
Ссылкаlet values = [for item in ([1]) if true => item]
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения parse. Ненулевой код завершения.
control-operand-parentheses at
example.tpz:1:36
Delimited tests, iterators, scrutinees, and guards
Ссылкаimport std.iolet mut count = 0if (true) { count += 1 }if let Some(value) = (Some(1)) { count += value }while (count < 3) { count += 1 }let mut pending: Option<int> = Some(1)while let Some(value) = (pending) { pending = None() }for value in ([1, 2]) { count += value }let chosen = match (count) {case 6 if (((flag: bool) => flag)(true)) => 6case _ => 0}let collected = [for value in ([1, 2]) if (((flag: bool) => flag)(value > 0)) => value]io.writeLine("{chosen}")io.writeLine("{collected.length}")
6
2
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
62
Record construction and update use ordinary operand grammar
Ссылкаimport std.iorecord Flag { enabled: bool }let state = { enabled: true }let first = if (Flag { enabled: true }.enabled) { 1 } else { 0 }let second = if (state { enabled: false }.enabled) { 1 } else { 2 }let third = match (Flag { enabled: true }) {case Flag { enabled: true } => truecase _ => false}io.writeLine("{first},{second},{third}")
1,2,true
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
1,2,true
The using expression has the same required boundary
Ссылкаfunction manage(file: File) -> () {using resource = (file) {let handle: File = resource}}
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Проверка принимает программу. Код завершения 0.
Read transformations in data-flow order
Ссылкаimport std.iofunction increment(value: int) -> int { value + 1 }function double(value: int) -> int { value * 2 }function transform(value: int) -> int {let increased = increment(value)double(increased)}let values = [1, 2]let chained = values.map(increment).map(double)let increased = values.map(increment)let staged = increased.map(double)let composed = values.map(transform)io.writeLine("{chained[0]},{chained[1]}")io.writeLine("{staged[0]},{staged[1]}")io.writeLine("{composed[0]},{composed[1]}")
4,6
4,6
4,6
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
4,64,64,6
Binary and nested operands print from left to right
Ссылкаimport std.iofunction value(label: string, number: int) -> int {io.writeLine(label)number}let result = value("left", 1) + value("middle", 2) * value("right", 3)io.writeLine("{result}")
left
middle
right
7
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
leftmiddleright7
The left operand faults before the right operand runs
Ссылкаimport std.iofunction left(divisor: int) -> int {io.writeLine("left")1 / divisor}function right(number: int) -> int {io.writeLine("right")9223372036854775807 + number}left(0) + right(1)
left
Ожидаемый результат
Ожидаемый результат
Этап отклонения run. Ненулевой код завершения.
diagnostic-tpz4002 at
example.tpz:4:5
left
Both calls would fault if evaluated. The left call produces TPZ4002, and the right call produces no output.
Index assignment evaluates the index before its value
Ссылкаimport std.iofunction index() -> int {io.writeLine("index")0}function value() -> int {io.writeLine("value")7}let mut values = [1]values[index()] = value()io.writeLine("{values[0]}")let mut number = 1number += value()io.writeLine("{number}")
index
value
7
value
8
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
indexvalue7value8