Code Style
Trailing Newline (EOF)
Every non-empty .no source file must end with exactly one trailing newline (that is, the file ends with a single line break).
- File has no trailing newline → add one.
- File ends with multiple blank lines → collapse them into a single trailing newline.
- Empty file (0 bytes) → left unchanged.
Excluded directories: dist/, vscode-nolang/, node_modules/.
Rationale: a single, consistent EOF newline keeps git diff clean, avoids "no newline at end of file" warnings, and makes concatenation/tooling predictable.
Automated enforcement (built into the toolchain)
This rule is enforced automatically by the toolchain — there is no separate script:
no fmt: thefmtsubcommand (src/cmd/no/main.go) formats files in place and callsfmt.FormatFile, which guarantees exactly one trailing newline.- LSP format-on-save /
textDocument/formatting:formatNolangCode→fmt.FormatFileinsrc/lsp/server.goappends/collapses the EOF newline automatically when you save or format a.nofile in the editor.
Implementation lives in src/fmt/formatter.go:
FormatFile(code)formats a complete file and callsensureTrailingNewline, which strips all trailing\r/\n(CRLF-safe, multi-blank-line-safe) and appends a single\n. Empty or unparseable input is returned unchanged so the formatter never mangles a file it cannot understand.Format(code)is the pure fragment formatter (no trailing newline), used mainly by unit tests; preferFormatFilewhenever you write a real source file.
Import Statement Cleanup (Dedup / Remove Unaliased std Imports / Sort)
no fmt (and LSP format-on-save) automatically normalizes the contiguous import block at the top of a file (# path[.fn] [alias]); the implementation lives in src/fmt/imports.go:
- Dedup: imports that are byte-identical (same path, function name, and alias) are collapsed to the first occurrence.
- Automatic removal of every unaliased pure std module import: standard library modules are implicitly loadable (see Cross-Module Call Prefixes), so a bare
# std/<module>with no alias and no.function(e.g.# std/noml,# std/math,# std/database/sql) binds nothing and is redundant — the formatter removes it. Three exceptions keep it:- an alias (
# std/noml n) or a function import (# std/fmt.sprintf fm) was written — a deliberate name binding; - the import line carries a comment or an attached
#{...}annotation — user-written content is never silently dropped.
- an alias (
- Automatic sorting: imports are sorted lexicographically by path → function → alias (stable sort).
A _ alias (# path _) marks an import as deliberately unused / side-effect-only:
no fmt keeps it verbatim (it is not treated as an unaliased import) and no vet
does not emit the unimpuse hint. It is the same convention as _-prefixed unused
variables. See Export · Deliberately unused imports.
Conservative boundary: if any import in the block carries a comment (own line above or trailing on the same line) or an attached #{...} annotation (e.g. the #{bind=ffi} native-binding policy), the whole block keeps its source order and nothing is removed — sorting would break the comment/statement pairing and removal would take the comment with it. Exact duplicates with no attached content are still deduplicated in that case.
Import blocks that appear anywhere other than the top of the file (after code) are left untouched.
#{fmt-skip}
; before ; after
# std/vec # aaa/lib
# std/noml # std/io
# std/io # std/vec
# std/noml n
# aaa/lib → unaliased std imports (# std/noml, # std/vec, # std/io) removed;
; aliased # std/noml n kept; the rest sorted lexicographically
Comment Markers
Nolang supports two single-line comment markers and one multi-line (block) comment marker, with the following semantics:
//— traditional single-line marker (comments to end of line);— alternative single-line marker (implemented 2026-07-17, comments to end of line);; ... ;;— multi-line (block) comment (implemented 2026-07-18, symmetric delimiters; if left unclosed, the comment runs to end of file)
#{fmt-skip}
// this is a comment
; this is also a comment, same meaning
x = 1 ; inline comment, to end of line
;;
this is a multi-line (block) comment
it can span several lines
ending with ;; ;;
y = 2 ;; inline block comment ;;
Block delimiting: ;; opens and ;; closes; everything between them (including newlines) is comment content. A single ; inside does not close the block — only ;; does. If no closing ;; is found, the comment runs from the opening ;; all the way to the end of file. The opening ;; only enters multi-line mode when nothing but whitespace follows it on that line — with text after the ;; on the same line it is an ordinary single-line comment (;; note comments that line only, the next line is still code). The closing delimiter works the same way: only whitespace may follow the ;;.
The formatter preserves the original marker: no fmt never changes any comment marker — ; stays ;, // stays //, ;; ... ;; stays ;; ... ;;. The formatter records the original marker via Comment.Marker and emits it verbatim; block-comment content (including internal newlines) is also preserved as-is, so formatting is idempotent.
Safe scope: when ; / ;; appear inside string literals (e.g. 'text/plain; charset=utf-8', index-from(';', pos)) or inside // comments, the lexer's string and comment scanners consume them first, so they are never treated as comment markers.
Note on cond -> X; Y: since ; is now a comment, cond -> X; Y parses as "run cond -> X (evaluate X then discard)" plus an inline comment ; Y — X is never assigned. The correct form is cond -> X = Y (an established stdlib pattern; see arr.no, uuid.no, path.no, err.no, assert.no). If you find cond -> X; Y in source, change it to cond -> X = Y.
Single-line multi-statement writing is forbidden: ; is only a comment marker and cannot join multiple statements on one line; , cannot join statements either. Every statement inside a block { ... } must occupy its own line. Compacting a block onto one line is the most dangerous mistake:
#{fmt-skip}
; ❌ Wrong: `; return }` all becomes a comment, so the block's `}` disappears
cond -> { print('X'); return }
; ✅ Correct: one statement per line
cond -> {
print('X')
return
}
cond -> { print('X'); return } effectively leaves only cond -> { print('X'): the block never closes, and every statement after the stranded } (usually the whole remainder of the function body, sometimes the following module-level functions) is swallowed. The compiler may not even report an error, and any diagnostic may point far away from the real mistake.
Boolean Literals & == true / == false Simplification (implemented 2026-09-24)
Beyond the true / false keywords, Nolang accepts two shorthand boolean literals:
!!— a standalone literal equal totrue.!— a standalone literal equal tofalse(only when the token after!cannot start an operand; if!is followed bynewline/;/ EOF /)/}/]/->, it parses asfalse).
Note: this refers to
!!/!in expression position, which is different from the loop-position forms!! { }(always execute) and! { }(never execute).
Both shorthands become an ordinary BooleanLiteral at parse time, so the four forms f == true, f == !!, f == false, f == ! are syntactically equivalent and flow through the same logic.
no fmt's handling of booleans (implemented in src/fmt/expr.go):
-
Standalone literals normalize to the keyword spelling:
c = !!→c = true,c = !→c = false. -
Known simplifies, unknown does not: when exactly one side of
==/!=is a boolean literal AND the other operand can be proven to be a bool value, the formatter emits the simplified form. All four pipelines share the same signature-collection rules (collectModuleSignatures: baked-in std tables + local modules reached viause/#+ EnumVariants) and the sameSemRebuildConfig.Applyinjection contract; only the supplier differs:no fmt/ LSP usebuild.FmtSigLoader, whileno build/no vetstill go throughpreloadModuleSignatures+astParseConfig(the two loaders are not merged yet).no fmtinjects before the freshSkipLoweringparse; LSP injects inParseDocumentand publishes aparseSnapshot, so format-on-save reuses a deep copy of that sugar AST (fmt.CloneProgramForFormat) and, with default settings, no longer parses again. Three sources count as proof:- An explicit type annotation:
b bool = true, parameter(b bool). - A boolean literal assignment:
flag = true/flag = false. - A call to a function whose declared result is
bool: defined in this file (e.g.bytes-eq = ... (eq bool)), or visible through the signature table (e.g. stdargs.has-flag, a localhelper.is-ok). A call on a variable receiver (s.starts-with('a')) is resolved through the receiver's already-inferred type inSem(s: str) againststr.starts-with; an uninferred receiver, or the same variable name inferred as different types in different scopes, stays unknown (no "globally unique method name" guessing, which could mistake?boolfor plainbool). A call whose result type the table cannot resolve stays unknown.
Source ( bbelow is a "known" variable)Formatted b == true/b == !!bb == false/b == !! bb != true/b != !!! bb != false/b != !btrue == b(literal on the left)b!=simply flips the polarity;true == false(both sides are literals) is left untouched. A bare name with no bool evidence, such asf == true, is left untouched too. - An explicit type annotation:
-
?Tand every unknown operand keep the comparison: options (?T), cross-module calls whose result type the signature table cannot resolve, bare names without an assignment, dot access with an uninferred receiver type, call expressions and arithmetic results all keep== true/== false. Collapsing one into a barex/! xcontrol-flow guard triggers an MIR "option-as-i1" codegen crash — v0.3.3 reverted the whole rule for exactly this reason (8a8ecb59). 2026-11-15 restored it under a positive proof rule instead of the old "no?Tvisible, so it must be a value" inference. On the same dayno fmtand LSP gained cross-module signatures too, so option results such asfs.write-str(...)(?bool) are visible and are stopped by the option hard gate — not by being invisible. An option is an independent hard gate (boolOperandIsOptionTyped) checked before the bool value proof, so it is never simplified whether or not the annotation survives in the source: bothok ?bool = fs.write-str(...)andok = fs.write-str(...)keep the comparison. Removing redundant type annotations is an intended, correct part ofno fmt(fixRedundantTypeSource); do not disable that removal to preserve option detection. Regression tests:src/fmt/bool_comparison_test.go,src/fmt/signatures_test.go,src/lsp/fmt_gate_test.go. -
Applies inside
->arms / standalone if-then conditions too (for known variables):b == ! -> return→! b -> return. -
Precedence-safe: negation is written as
!(with one space) to match the existing prefix-operator convention, which keepsno fmtidempotent. Today every provable operand is an identifier, so!cannot re-bind; the implementation still keeps the parenthesis guard for non-atomic operands (! (a + b), never! a + b) in case the proof rule is widened later.
Deferred Zero-Init for Return Values
Nolang functions use a deferred zero-init strategy for their named result parameters (out parameters): the function prologue does not zero-initialize the out parameters. Instead, the compiler tracks, via a bitmap __ret_init_bitmap, whether each out parameter was explicitly assigned anywhere in the body. When the function returns, any out parameter that was not explicitly assigned automatically gets a zero-value store for its type (integer → 0, str-long → zeroinitializer, struct → zeroinitializer, option → nil). This mechanism is symmetric with the existing __move_bitmap deferred-free mechanism.
Why this design
- Performance: avoids emitting a
store zeroinitializerfor every out parameter in the prologue only to have it overwritten by a later assignment — a purely redundant store. The deferred strategy writes zero only when "it really wasn't assigned". - Readability: you don't need boilerplate early zero-assignments like
found = false/result = nilat the top of a function; readers see directly that "only the success path assigns". - Consistency: uses the same bitmap-tracking pattern as the
__move_bitmapdeferred-free mechanism, keeping the compiler internals symmetric.
Recommended style
Do not pre-zero the out parameters at the top of a function — the compiler fills zero on return. Write only the "success path" assignments:
; Good: no early zero-init, the compiler handles it
hashmap-str-tmpl.contains = (key str) (found bool) {
val ?v = .get(key)
val: {
ok -> found = true
err -> {
}
nil -> {
}
}
}
Anti-pattern (avoid)
Do not write redundant early zero-assignments — they are dead stores overwritten by a later assignment:
#{fmt-skip}
; Bad: redundant early zero-init
hashmap-str-tmpl.contains = (key str) (found bool) {
found = false ; redundant — the compiler zero-fills on return
val ?v = .get(key)
val: {
ok -> found = true
err -> {}
nil -> {}
}
}
Option defaults to nil
For ?T option-typed out parameters, the zero-fill writes nil directly (tag=1, data=0), equivalent to result = nil. So paths like "not found / empty set / EOF" need only a bare return, with no result = nil in the source:
#{fmt-skip}
; Good: the miss path uses a bare return, the compiler fills result = nil
hashmap-str-tmpl.get = (key str) (result ?v) {
.size == 0 -> return ; compiler fills result = nil
...
; fall-through: compiler fills result = nil
}
Debugging hint
If a function returns an unexpected zero value (e.g. found should be true but is false, or result should have a value but is nil), check that every path that should return a non-zero value explicitly assigns the out parameter inside the body. The compiler does not infer intent — it only zero-fills unassigned out parameters. See the debugging hint in .agents/skills/nolang-debug/SKILL.md.
Markdown code blocks (no fmt -md)
no fmt -md formats only the inside of ```no / ```nolang fences; the fence lines and all other Markdown are preserved byte for byte. A block's body is parsed as Nolang source; if it cannot be parsed the block is left untouched and its line number is reported, so formatting never mangles a file it cannot understand. (-md and -fix are mutually exclusive — -md only formats.)
Keep correct and wrong examples in separate blocks
Putting "the correct form" and "the wrong form" in one block makes the parser treat both as one program: the correct half loses its no fmt check, while the wrong half may be silently "fixed" by the formatter until the mistake is invisible. Therefore:
- a correct example gets its own block with no annotation, so
no fmtformats and validates it; - a wrong example gets its own block whose first line is
#{fmt-skip}, so it is neither validated nor modified.
; ✅ Correct: one statement per line
cond -> {
print('X')
return
}
#{fmt-skip}
; ❌ Wrong: everything after `;` is a comment, so the block's `}` disappears
cond -> { print('X'); return }
Three legitimate uses of #{fmt-skip}
- Wrong examples / counter-examples — not valid programs to begin with; formatting only gets in the way.
- Pseudo-code and signature summaries — shape-only fragments with no implementation.
- Cheat sheets with aligned comment columns —
no fmtrewritescode ; noteascode; note; the column alignment is the whole point of such a table.
Never annotate just to prevent expansion
no fmt expands an empty block { } and a single-line arm -> { x() } onto several lines:
ok = (b bool) (yes bool) {
}
dispatch = (cmd str) {
cmd == 'a' -> {
fa()
}
}
This is the canonical form and should be accepted — only once expanded does the block have a line of its own to insert further statements into; otherwise every added statement starts with manually splitting the block. Likewise, true -> {} turning into true -> {\n} is no reason to roll back. Only the three cases above (counter-examples, pseudo-code, aligned tables) genuinely need #{fmt-skip}.
Comment-only blocks need no annotation
A block that contains only comments (the usual way of "commenting out" the correct form) parses to zero statements. no fmt treats that as "nothing to format", leaves it verbatim and reports nothing — it is not a syntax error, and adding #{fmt-skip} would only hide that fact.
Order: annotate first, format second
no fmt -md -w rewrites every block that is not filtered out. Once the formatter has "corrected" a wrong example, the counter-example no longer demonstrates anything and the original spelling is gone for good. Add #{fmt-skip} first, run -w second.