# Grammar (v0) The syntax accepted by `louise_syntax`, the parser in `crates/louise_syntax/src/grammar/`. Every ```` ```louise ```` sample in `docs/` is parsed by the test suite. **Notation:** - `x?` means optional, `x*` repeated, `x+` one or more. - `x,*` means comma-separated, with a trailing comma allowed. ## Lexical structure | Token | Form | |---|---| | Identifier | Unicode letter or `_`, then letters, digits or `_`. A lone `_` is the wildcard. | | Integer | `42`, `1_000`, `0xff`, `0b1010` | | Float | `1.5`, `2e-3`, `1.5e3` (a digit is required on both sides of `.`) | | String | `"..."` with `\` escapes (`\n \t \r \0 \\ \" \` \{ \} \u{hex}`); may span lines. `{expr}` and `{expr:?}` are holes ([ADR 0034](../adr/0034-string-interpolation.md)); a literal brace is `\{` or `\}` | | Template | `` `...` `` after a tag, with the same escapes and holes as a string ([ADR 0048](../adr/0048-tagged-templates.md)) | | Comment | `// ...` to end of line. `/// ...` is a doc comment for the next item. | **Keywords:** `as` `ctl` `defer` `effect` `else` `final` `fn` `handle` `if` `impl` `import` `let` `match` `multi` `opaque` `pub` `region` `return` `trait` `type` `use` `where` `with`. `return` also heads a handler's return clause. **Contextual names, not keywords:** - `resume`, - `True` and `False`, which are constructors. **Naming convention:** - Types and constructors start with an uppercase letter. - Values, functions, effects, modules and type variables start lowercase. The parser relies on this convention in exactly two places: in patterns, an uppercase name is a constructor and a lowercase name binds a variable; and a callee whose last segment is uppercase heads a construction, not an application ([ADR 0062](../adr/0062-parens-free-functions.md)). ## Items ``` file = item* item = attr* "pub"? "opaque"? (fn | type | effect | trait | impl | import) // "opaque" only before type attr = "@" name (ident | string | int | ident "(" ident+ ")")* // `@derive Eq Show`, `@extern c "sym" (blocking io)` import = "import" name ("/" name)* ("." "{" import_item,* "}")? ("as" name)? import_item = "type"? name ("as" name)? fn = "fn" name "::" param* ret? where? block? // `fn add :: a b { a + b }` (ADR 0062) param = ("~" name)? (pattern (":" type)? | ":" type) // `~n`, `~n: T` (pun), `~n:(p: T)` (rename) ret = "->" type ("/" effect_row)? where = "where" type,+ type_def = "type" name type_params? ("{" (variant ","?)* "}" | "=" type)? // no body: abstract variant = Name ("(" ((name ":")? type),* ")")? ("->" type ("where" type,+)?)? // refined: ADR 0041 type_params = "<" name,* ">" effect = "effect" name type_params? "{" op* "}" effect_alias = "effect" "alias" name "=" type,+ // ADR 0044; "alias" is a keyword only after "effect" op = ("fn" | "ctl" | "multi" "ctl" | "final" "ctl") name "::" param* ret where? trait = "trait" name type_params? "{" (fn | assoc)* "}" impl = "impl" type where? "{" (fn | assoc)* "}" assoc = "type" name type_params? ("=" type)? // ADR 0047: `= type` in impls only ``` **Refined constructors:** a constructor may end with its result type, `-> T<..>`, and constraints, `where Show` ([ADR 0041](../adr/0041-gadts-and-existentials.md)). A constructor's `where` ends at the end of its line, so a comma there, or one starting the next line, separates constructors. **Abstract types:** a `type` without a body is abstract. Its values come from outside Louise: built-ins such as `Int` in the prelude, or FFI resources. **Opaque types:** `pub opaque type T { ... }` exports the type but not its constructors and fields: other modules can name `T`, and only `T`'s module can build, match or read its values ([ADR 0033](../adr/0033-opaque-types.md)). `opaque` needs `pub` and a body with constructors (`E0118`). **Bodyless functions:** a `fn` without a body is valid syntax. It is used for `@extern` declarations and trait method signatures. Later phases check that bodies are present where they are required (`E0115`). **Attributes** are parsed as any name with space-separated identifier or literal arguments, or an identifier applied to identifiers (`(blocking io)`). Which attributes exist, their arguments and the items they apply to are checked after parsing (`E0114`; see [the language reference](language.md#programs-and-modules)). ```louise import std/actor.{type Subject, send} /// A labelled-field constructor is a record. @derive Eq Show pub type User { User(name: String, email: String) } effect fail { final ctl fail :: reason: String -> Never } pub fn check :: u: User -> User / { if u.name == "" { fail "empty name" } else { u } } ``` ## Types ``` type = path_type | fn_type | tuple_type path_type = name ("." name)* ("<" (type | binding),* ">")? binding = name ("<" name,* ">")? "=" type // in a `where` constraint only (ADR 0047) fn_type = "send"? "fn" "(" (("~" name ":")? type),* ")" ret // `send`: only here (ADR 0004, Revision 6); `fn() -> T` is `fn(()) -> T` (ADR 0062) tuple_type = "(" type,* ")" // () is the unit type effect_row = "<" type,* ("|" type)? ">" // labels (an effect alias expands in place, ADR 0044), then an optional row variable ``` Generic `<...>` appears **only** in type positions; expressions have no turbofish. That is what makes `<` at the start of an expression unambiguous as HTML. ## Expressions Operators, from loosest to tightest binding. All are left-associative, except comparisons, which cannot be chained. | Operators | Meaning | |---|---| | `\|>` | pipe | | `\|\|` | or | | `&&` | and | | `==` `!=` `<` `>` `<=` `>=` | comparison (not chainable) | | `<>` | append (`Semigroup`: strings, lists, `Bytes`, `Order`) | | `+` `-` | additive | | `*` `/` `%` | multiplicative | | `-` `!` (prefix) | negation | | `f a b` `C(..)` `e.field` `t.0` `` e`...` `` | application, construction, field access, tuple index, tagged template | ``` atom = literal | name | "(" ")" | "(" expr ")" | "(" expr ("," expr)+ ","? ")" | "[" (expr | ".." expr),* "]" | block | if | match | lambda | handle | region | return | html region = "region" block // scope of mutable references (ADR 0002) return = "return" expr? // early return (ADR 0037); see below call = expr arg+ // application by juxtaposition (ADR 0062) arg = atom | "~" name (":" atom)? | "_" // `~name: x` labelled, `~name` a pun, `_` placeholder ctor = (name ".")* Name "(" ((name ":")? expr | ".." expr),* ")" // `(` touches the constructor (adjacency) template = expr "`" text_or_hole* "`" // tagged template (ADR 0048); "`" directly after the tag block = "{" stmt* "}" // value of the last expression stmt = "let" pattern (":" type)? "=" expr | "use" (pattern,+)? "<-" expr | "defer" expr // cleanup for the rest of the block (ADR 0016) | expr if = "if" expr block ("else" (if | block))? match = "match" expr "{" arm* "}" arm = pattern ("|" pattern)* ("if" expr)? "->" expr "," // "," optional after a block body or before "}" lambda = "fn" param* ret? block // no name, no `::` (ADR 0062) handle = "handle" block "with" "{" ((name | "return") param* "->" expr ",")* "}" ``` **`return` takes the rest of the line's expression**, the loosest there is: `return a + b |> f` returns the pipe. `return` followed by a line break, `}`, `,` or `)` returns `()`, so a bare `return` doesn't swallow the next line's statement. **`_` as an argument is a placeholder** ([ADR 0023](../adr/0023-pipe-placeholders-and-capture.md)). `x |> f a _` is `f a x`. Outside a pipe, `f a _` is the function `fn v { f a v }`. A call takes at most one `_`, never with a `..` spread, and `_` is accepted nowhere else in an expression. **`use` is Gleam's callback sugar.** `use a, b <- f x` turns the rest of the enclosing block into the callback, applied last and unlabelled: `f x (fn a b { rest })` ([ADR 0062](../adr/0062-parens-free-functions.md)). **`defer` also takes the rest of the block.** `defer c` runs `c` after the statements that follow it, however they are left (normally or by unwinding); their value is the block's. ### Line-break rules Statements have no separators, so line breaks resolve four ambiguities: 1. **Application continues by indentation** ([ADR 0062](../adr/0062-parens-free-functions.md)): an application's arguments (and a definition's parameters, and an attribute's arguments) may continue on following lines that start with an atom *more indented* than the statement they belong to; a line at the statement's indent starts a new statement. A construction's `(` keeps its own rule: it touches the constructor, with no space or line break between them (issue #319). `Some(1)` is a construction; `go Pin (x)` passes `Pin` and `(x)` as two arguments. 2. **HTML at line start:** a line that begins with `<` immediately followed by a tag name, or with `<>` immediately followed by a line break or `<`, starts an HTML literal. It does not continue the previous expression. 3. **Templates join their tag:** a template literal's `` ` `` directly follows the tag — `` pug`...` ``, never `` pug `...` ``. A template without one is an error. 4. **Leading operators continue:** any other operator at the start of a line continues the previous expression. This keeps pipelines and concatenations readable: ```louise fn report :: xs: List -> String { let total = xs |> list.filter fn x { x > 0 } |> list.sum "total: " <> int.to_string total } ``` ## Patterns ``` pattern = "_" | name | literal | "-" number | Ctor ("." Ctor)* ("(" ((name ":")? pattern | ".."),* ")")? | "(" pattern,* ")" | "[" (pattern | ".." name?),* "]" | pattern "as" name ``` ## HTML literals ``` html = "<" tag attr* ("/>" | ">" child* "") | "<>" child* "" attr = attr_name ("=" ("\"...\"" | "'...'" | "{" expr "}"))? child = text | "{" expr? "}" | html tag = letters, digits, "-", "_", ":", "." (e.g. div, my-widget, ui.Card) ``` **Rules:** - Elements must be closed explicitly. Write void elements as `
`. - Text is kept verbatim in the tree. What a literal means (its type, children, attributes, components, whitespace and rendering) is defined in [ADR 0009](../adr/0009-html-literals.md). ```louise fn card :: title: String body: List -> Html {

{text title}

{body}
} ``` ## Tagged templates ``` template = expr "`" text_or_hole* "`" // "`" directly after the tag ``` `tag\`text {expr}\`` calls `tag` with the literal's `std/template.Template`: its text parts and the values of its holes. A templater is any function from a `Template` ([ADR 0048](../adr/0048-tagged-templates.md)); `std/template`'s own `pug`, `html` and `xml` are instead compiled to the HTML tree the template denotes ([ADR 0057](../adr/0057-compiled-std-templaters.md)). Holes are converted by their type, as in HTML literals: `String`s and shown values are text the templater escapes, elements are embedded. ```louise import std/template.{pug} fn card :: title: String body: Html -> Html { pug` .card h2 {title} {body} ` } ```