Design decisions
The rules of Topaz 6.0 come from individual decisions. For each decision this chapter records the problem it addressed, the behavior chosen and the alternatives that were considered and rejected. Each example of a decision states its expected result.
Lexical structure and literals
- Line endings preserve statement boundaries
LF, CRLF and lone CR each count as one line break in source.
- A former block-comment opener follows the operator rules
The parser reads
/as* /followed by*. - Comments use one line at a time
Start a comment with
/./ - Newlines separate statements and discarding a value is explicit
Use a line break to separate statements.
- Identifiers must already be in NFC
Write identifiers in Unicode 16 NFC.
- Radix prefixes and hexadecimal digits use lowercase
Write
0bfor binary and0xfor hexadecimal, both in lowercase. - Durations display as milliseconds and report overflow
Durationsupports addition, subtraction, integer multiplication in either order, comparison, display andto.Millis() - Every template tag uses the same escapes
Use the same escape grammar for all template tags.
- Source line endings leave string values unchanged
Read each physical LF, CRLF or lone CR in a string literal as one newline.
- Path.from constructs paths from strings
Remove the
ptag. - Whitespace-only source lines become blank lines in strings
On source lines made entirely of spaces and tabs, remove that whitespace and keep the newline.
- String interpolation and derived
Showwrite finite floats without an exponentFor nonzero finite values in interpolation or derived display, choose a decimal with the fewest significant digits that rounds back to the same binary64 value.
- Path.from is the single path constructor
Use
Path.to construct a path from text.from
Bindings and types
- A binding has at most one type annotation
Reject a declaration that uses both a binding annotation and a pattern annotation for the same binding.
- A binding cannot reuse a visible constructor name
Write
Choice.for a nullary variant.Empty() - Mutation diagnostics identify the cause
Checking reports TPZ5003 for an immutable root and points to its reference.
- Optional mutation still needs a mutable root binding
Follow fields, indices, parentheses and
?.back to the root binding. - A local function name refers to one declaration throughout its block
A local
functiondeclaration shadows an outer value with the same name throughout its block. - Early reads are diagnosed at their evaluation boundary
A read before initialization in an immediately evaluated expression, such as a condition or
matchsubject, produces TPZ3018 during name resolution. - Matching evaluates pattern expressions as it reaches them
The expression providing the value follows its surrounding evaluation path.
- A name refers to the same declaration in checking and execution
Each place that uses a name has one target for its role, and checking and execution use that same target.
- Parentheses around a callee preserve its constant eligibility
A call's eligibility in a
constinitializer stays the same with or without parentheses around its callee. - Assigning and passing collections gives independent values
Arrays, maps and sets are values.
- A lambda defers a mutating method call
Reject a detached mutator such as
let add = xs.during checking.push - Mutating a temporary requires using the result
Reject a mutating call that has no root binding and discards its result during checking.
- If without else always returns unit
An
ifwithout anelsereturns()even in a value context. - A map fallback uses get with the defaulting operator
Write
m..get(k) ?? fallback
Expressions, patterns and control flow
- Positive values use no unary plus
Remove unary
+. - In tests membership in arrays, sets and ranges
Use
into test membership in arrays, sets and ranges. - An absent optional receiver skips method arguments
Evaluate the receiver once.
- Ordinary calls and bindings express data flow
Remove
|>,>>and expression-position_. - Parentheses delimit control operands
Wrap control operands and guards in parentheses, as in
if (test),match (value)andwhile (test). - Operands evaluate from left to right
Evaluate binary operands and nested operands from left to right.
- A write targets the binding after the right-hand value is evaluated
Indexed assignment and mutating methods write to the binding’s current value after evaluating the right-hand side or arguments.
- Numeric patterns accept negative literals
A numeric literal pattern can have one leading
-. - Record patterns name both the field and its pattern
Write every record pattern field as
field: pattern. - A missing colon in a record pattern is a parse error
Keep TPZ5611 reserved for defensive checks.
- A match arm uses a block to return from its function
Put
returninside a block when using it in a match arm. - Match picks the first successful arm and rejects covered arms
Try
matcharms in source order and select the first arm whose pattern and guard both succeed. - A range pattern with two literal endpoints that matches no value fails checking
Apply the usual integer literal checks first when both endpoints are literals.
- Computed endpoints run each time matching reaches a range
On reaching a range, evaluate the computed lower endpoint before the upper one.
- A list rest has an explicit pattern
Always follow
.with a pattern.. - Constructors use parentheses even without arguments
Use parentheses for constructors in values and patterns, as in
None(),Empty()andSome(x). - Every match covers all possible values
The checker requires every match to cover every possible value.
- For performs effects and a comprehension collects values
A
forloop performs effects and returns()in every context. - The defer diagnostic asks for a block
During parsing, TPZ2004 says that
defertakes a block and points to the start of the body expression. - Defer puts deferred work in a block
Follow
deferwith a block. - Control flow cannot jump across a defer boundary
A
return,break,continue, or?crossing adeferbody produces TPZ5001 at the expression during checking, even in unreachable code. - Returning an error value still runs registered cleanup
When
?returnsErr, rundeferblocks in reverse registration order in scopes being exited. - An unrecoverable runtime fault skips remaining cleanup
An ordinary runtime fault terminates execution and cannot be caught to resume it.
Functions and generics
- Lambda parameters use parentheses even when there is one
Put parentheses around every lambda parameter list.
- Variadic parameters have no defaults
Reject a default on a variadic parameter.
- A type parameter's capabilities are explicit protocol bounds
A type parameter or opaque projection with no static member contract cannot read a field or call a method through a dot.
- Calls use positional arguments and records carry named options
Use positional arguments for calls.
- Explicit type arguments follow a name or member access
Write explicit type arguments after a name or member access.
- Whitespace between type arguments and the call does not change the parse
After a name or member, parse type arguments when
<and>enclose a type-list shape and the next token is(. - An argument in a union call has one type across branches
Use independent arguments to instantiate the branch signatures first.
- Each parameter name appears once in its list
Reject a repeated name within one parameter list in named functions and lambdas.
Structures
- Decimal rounding modes form an ordinary enum
Roundingis an ordinary enum with six variants.Mode - An enum payload can use a union containing an enum
Permit a union containing an enum as a variant payload.
- Enum variants can use prelude constructor names
Allow
None,Some,OkandErras enum variant names. - A structural record update writes each field once
Reject duplicate field names in the same structural record update.
- A constructor requires arguments even in a value position
Use
Name(arguments)in a value position. - Self names the type that conforms to a protocol
Protocol declarations take no type parameters of their own.
- Protocol signatures use ordinary function declaration rules
Use ordinary generic, variadic and default parameter rules.
- Protocol implementations inherit defaults and visibility from their contracts
Implementation methods may be generic or variadic and omit return annotations.
- Imported conformance visibility does not depend on how it is defined
Manual and derived conformances follow the same import visibility.
- Manual JSON conformance uses encode and decode
Manual conformance supplies ordinary
encodeanddecodemethods. - Using cleans up on normal and structured early exit
usingcleanup runs on normal and structured early exit. - Derived conformance calls the nested type's conformance
Invoke the inner type's manual or derived conformance.
- Newtypes derive conformances explicitly
Use an explicit
derivesclause on anewtype, just as for records and enums. - Equality, ordering, and JSON each have their own requirements
Map and Set equality compare membership.
- Protocols follow ordinary module name rules
Apply the regular export, import, and name resolution rules to protocols.
- Generic conformance bounds go in the leading parameter list
Put bounds in the leading parameter list, as in
impl<T: Eq> Eq<Box<T>>. - Generic protocol implementations use the same bounds syntax as functions
A protocol implementation can declare explicit generic parameters and bounds, and it can be conditional or conditionally derived.
- Collections receive expected types from context
Propagate expected types consistently to arrays, sets, maps and comprehensions.
- Callbacks chain transformations and comprehensions build collections
Keep callback methods such as
arr.for chained transformations.map(f) - Arrays, sets and ranges share callback methods
Provide eager
map,filterandreducefor arrays, sets and ranges. - Maps and sets preserve insertion order
Map keys, values, entries, iteration and display follow insertion order.
Failure, concurrency and modules
- A Result error type needs an annotation when inference cannot determine it
If inference cannot determine the error type, checking reports TPZ5022 and asks for a type annotation.
- A callback returns its own propagated error
When
?propagates from a lambda or callback, returnResultorOptionfrom that call. - An empty concurrent group returns an empty record
A
concurrentgroup with no arms produces an empty record. - A timeout evaluates a Duration expression once
Accept an ordinary
Durationexpression. - A deadline wins when completion coincides with it
A timeout wins when completion coincides with the deadline.
- A concurrent arm cannot transfer control out of its boundary
Reject return, loop control and error propagation statically when their target lies outside the arm.
- A timed group falls back even when a branch never finishes
A timed
concurrentgroup takes its fallback when the deadline expires. - A branch abandoned at the deadline skips user cleanup
An abandoned
concurrentbranch skips its remainingdeferandusingcleanup. - Entry files and imported modules use the same statement rules
Use the same top-level statement rules for entry files and imports.
- User code cannot name compiler-generated declarations
User code cannot name a declaration the compiler generates.
- Export let binds names with an ordinary pattern
Use an ordinary immutable
letpattern inexport let. - Public declarations are checked after type resolution
Check the resolved types of public declarations.
- Record defaults follow export visibility
Apply ordinary module visibility to name access in record defaults.
- As changes the imported name
Use
asonly when the name changes. - Imported values have immutable bindings
An imported binding is immutable.
Standard library
- Host reads, closes and writes have separate runtime faults
Use TPZ4008 for input, TPZ4009 for close and TPZ4010 for output at runtime.
- WriteLine returns unit and reports host write failure as a runtime fault
Keep the unit signature of
std..io. write Line - A host output fault points to the failed write call
Use a dedicated runtime fault for a host write failure in
writeand point its diagnostic at that call.Line - Collection length, keys and values are properties
Use properties for
length,keysandvalueson collections. - An empty collection has length zero
Test emptiness with
length == 0. - An out-of-bounds byte slice fails at runtime
A byte slice excludes its end and requires
0 <= start <= end <= length. - Hex byte input uses lowercase pairs
Read each byte as two lowercase hexadecimal digits.
- Decompression consumes one complete stream
Consume a single complete stream, frame, or member as defined by the format.
- Decompression accepts an output byte limit
Decompression functions accept an optional
maxargument and returnBytes Errif the decoded size exceeds it. - Path operations use normalized lexical components
Operate on normalized lexical components.
- Regex escape names reserve ASCII letters and digits
Reserve ASCII letters and digits after a backslash for escape names.
- Named regex captures have one spelling
Use Unicode 16.0 regex syntax with simple case folding.
- Oversized regex patterns fail at compilation
Compilation caps instructions at 65536, program size times capture slots at
2^22and group nesting at 128. - A regex repetition does not add another empty iteration
Do not add an empty iteration that makes no progress.
- Search, split and replace share one match sequence
Choose leftmost-first, nonoverlapping matches and apply the empty-match progress rule.
- Regex matches report UTF-8 byte offsets
Match.andstart Match.are UTF-8 byte offsets.end - Regex replacements use braces for capture references
Capture zero is the entire match.
- URL operations follow WHATWG
Parse and serialize absolute URLs under WHATWG without a base URL.
- Internationalized domains use Unicode 16.0.0
UTS 46 processing uses the Unicode 16.0.0 tables.
- Civil dates range from year 1 through year 9999
Use the proleptic Gregorian range
0001-through01- 01 9999-.12- 31 - Big integer text uses an explicit radix and lowercase digits
Use radix 2 through 36 and lowercase ASCII digits.
- Decimal multiplication checks the normalized result scale
Use an arbitrary-precision integer coefficient and normalized scale from 0 through 4294967295.
- Decimal parsing checks the entire ASCII input
Parse a complete ASCII decimal.
- Decimal rounding names its direction and tie rule
Provide six rounding modes.
- Decimal division rounds the exact quotient once
Round the exact quotient once at the requested scale.
- Decimal to integer conversion succeeds only for an exact result
int.is exact.to Decimal - Decimal comparisons use exact numerical values
Compare exact numerical values.
- Filesystem functions preserve bytes and sort directory entries
Byte operations preserve the bytes exactly.
- An explicit main consumes standard input once
For
main(args, stdin), read standard input to the end and pass it asstdin. - File streams preserve existing files and share cursor state
Open an existing regular file for reading and writing without creating or truncating it.
- JSON null uses the kind check
Use
value..kind() == "null" - JSON numbers preserve their original spelling
Preserve the exact source spelling of each JSON number.
- JSON parsing consumes the whole document and rejects duplicate keys
Parse one complete document and reject duplicate decoded keys.
- JSON writing sorts object keys
Dispatch through the JSON protocol once.
- Named CSV reading rejects duplicate headers
Name-based CSV reading returns an error when a header name is repeated.
- CSV writing with a supplied header rejects duplicate columns
stringifyreturnsWith Header Result<string, string>and rejects repeated requested column names. - TOML accepts leap seconds and limits nesting to 128
Accept a seconds value of 60 under RFC 3339.
- TOML follows 1.0 and reports JSON conversion errors
Read TOML 1.0 forms and write the root table deterministically.
- Test loops use ordinary for
Use
forin place offorandAll Int for, which are removed.All Bool - Parser scans use Unicode scalar positions
Integer ASCII predicates return a result for every integer input.
- Scaled-point conversion uses toScaledPoints
Use
toin place ofScaled Points scaled.Points - Public typesetting distances use Length of points
Use
Length<Pt>for public distances instd..typeset - The CJK cluster classification is named CjkCluster
Rename
KoreantoCluster Cjkto reflect its classification scope.Cluster - An empty final line follows the 52 percent threshold
Apply the below-52-percent rule even when the character count is zero.
- The line cost function is named lineBadness
Rename
linetoBadness Mpt line.Badness - The letter-spacing cap is a font-relative length
maxtakesLetter Spacing Em Length<Em>. - Typesetting picks the same breaks under the same conditions
With the same input order, policy, calculation grid and release, line breaks, selected kinds, widths, costs and error variants match.
- Break classification and paragraph planning have distinct boundaries
classifycompares stored point ticks.Breaks - Empty typesetting input succeeds with an empty result
For otherwise valid input, an empty cluster array or paragraph succeeds with an empty result.
- A nonempty paragraph needs a permitted final shaping boundary
Every ruleset requires the final shaping boundary of nonempty input to permit a break.
- Paragraph planning states its search and returns two results
FixedPoint starts with 80 preceding candidates and expands the search.
- Typesetting rejects negative extents while permitting negative tracking
Reject negative physical extents, penalty widths and drop-cap insets.
- Selected penalty width contributes to line width
Include a selected penalty's width for every kind in both cost methods and in the natural width used for justification.
- The final-line minimum applies only to the last FixedPoint line
Apply
minonly when calculating the final FixedPoint line.Final Line Width Ratio M - Consumer artifacts use inspectConsumerArtifact
Keep
inspectand remove the equivalentConsumer Artifact verify.Consumer Artifact - Lispex evaluation is distinct from admission and evidence work
The 6.0 API distinguishes canonical evaluation, admission, host interruption and additional evidence work.
- A Lispex request is an immutable snapshot once identified
Canonical byte exchange and host Datum construction preserve exact values within explicit conversion budgets.
- A Lispex package becomes usable after admission
Verify every supplied component and resource contract before returning a usable package handle.
- Transported Lispex code goes through admission again
Preparation produces an immutable verified rule under its own finite budget.
- Lispex distinguishes completed evaluation from a failed attempt
A completed evaluation returns the canonical settlement.
- Lispex uses distinct identities for requests, sources and execution
Give semantic requests, source provenance, engine bytes and profile host work distinct typed identities.
- Lispex replay checks a new result against the recorded result
freshverifies the stored request before execution and succeeds when the new settlement matches the recorded one.Replay - Lispex evaluation results survive follow-up verification
Keep the canonical evaluation result and report profile qualification, artifact verification and issuer authentication separately.
- Lispex phases use separate finite resource limits
Use complete finite limit records for preparation, evaluation and host work.
- Lispex factories produce ordinary immutable rules
Use verified lock entries and explicit preparation limits to produce the standard immutable rule form.
- Strings can be split into grapheme clusters
string.splits a string into an array using Unicode 16 grapheme boundaries.graphemes() - Existing string and array members carry their signatures forward
Keep the 5.21 signatures unless a separate decision removes or renames the member.
- String-to-integer conversion accepts ASCII digits and an optional minus
string.accepts ASCII decimal digits with an optional leadingto Int() -.
Tools
- A deferred error fails the whole command
A deferred runtime or host error fails the execution and prevents a
test-report.ok - Test assertions evaluate once and compare golden files exactly
Evaluate arguments once, from left to right.
- Storage cleanup preserves workspaces that may still be in use
Preserve workspaces with a live or uncertain owner regardless of age.
- Command options with no effect are removed
Remove options that have no effect, including
-.- types - Topaz version prints the product version
Run
topaz versionto print the version. - An option value is a separate argument
Pass the value as the next argument.
- A command option occurs at most once
Reject a repeated option even when its values are identical.
- Commands select JSON output with the same option
Use
-on commands with JSON output.- format json - JSON diagnostics keep stable codes and primary locations
The
-contract covers structured identity, required fields and their types, coordinate units, severity and the cause pointed to by the primary location.- format json - Topaz help opens command help
Request help with
topaz help. - Vendor brings dependency sources into the project
Use
vendorand removefetch, which performed the same operation. - Dependency declarations use tables
Write dependency declarations as tables.
Diagnostics
- TPZ0002 is retired and reserved
Retire TPZ0002 in 6.0.0 and retain its identity, meaning and documentation address.
- Call depth counts active user calls
For TPZ5009, count named functions, lambdas, user callbacks, protocol methods and receiver methods.
Decisions without a rule yet
- Type checking defers only judgments that depend on unknown facts
During checking, report each distinct failed obligation once.
- Generic functions keep their polymorphism in bindings
An eligible unannotated binding preserves the generic signature.
- Standard library constructor and cost faults point to the public call
Use the public call site as the primary location of faults from standard library constructors and cost calculations.