MoxyMoxy
Docs contents

Grammar

(* Moxy grammar

   Moxy is a C superset that compiles to C11. This file describes the
   syntax accepted by the parser in src/parse/ (state, types, expr,
   stmt, top, generic, reflect). Where the parser decides between two readings by
   looking ahead, the rule carries a comment saying how.

   Notation (ISO EBNF): "x" is a terminal, [ x ] is optional, { x } is
   zero or more, ( x | y ) groups alternatives, rules end with ';'.

   Not accepted in .mxy code (fine inside macros and C headers): K&R
   function definitions, __attribute__, _Generic, _Alignas, _Atomic,
   statement expressions ({ ... }), designator ranges [a ... b], and asm
   statements with operands. string, bool, true, false and null cannot
   be used as names. *)


(* ---- 1. Lexical structure ----------------------------------------- *)

(* Reserved words. __inline and __inline__ spell inline, __restrict
   spells restrict. true and false are reserved; NULL is an ordinary
   identifier. string and null lex as keywords but may also be used as a
   declarator, field, designator or member name, and an expression `string`
   or `null` refers to a variable of that name when one is in scope. *)
keyword = "auto" | "break" | "case" | "char" | "const" | "continue"
        | "default" | "do" | "double" | "else" | "enum" | "extern"
        | "float" | "for" | "goto" | "if" | "inline" | "int" | "long"
        | "register" | "restrict" | "return" | "short" | "signed"
        | "sizeof" | "static" | "struct" | "switch" | "typedef"
        | "union" | "unsigned" | "void" | "volatile" | "while" | "bool"
        | "_Bool" | "_Noreturn" | "_Alignof" | "_Static_assert"
        | "_Thread_local" | "string" | "true" | "false" | "null" ;

(* Contextual words. These lex as IDENT and only act as keywords in the
   positions named by the rules below, so they remain usable as variable
   and function names:
     match in await async defer namespace using ref shared weak unowned strong atomic fn
     map Result Future chan select lock gate Ok Err Some None impl interface dyn
     self Self,
     "test" at file scope before a STRING and "{" (2),
     "actor" at file scope before IDENT "{" (3c), "parallel" before "for" (6),
     "spawn" before "{" where a primary can start (8),
     "type" after '@', "timeout" in a select arm, and "_" / "default" /
     "else" in patterns.
   "static" before "for" or "if" starts compile-time reflection (6a). *)

IDENT     = ( letter | "_" | "$" ) { letter | digit | "_" | "$" } ;
INT       = ( digits | "0x" hexdigits | "0b" bindigits ) { "u" | "U" | "l" | "L" } ;
FLOAT     = (* C decimal and hex floating literals, suffix f F l L *) ;
CHAR      = "'" { char | escape } "'" ;
STRING    = '"' { char | escape | "\(" expr ")" } '"' ;
            (* one line only; "\(expr)" interpolates; adjacent STRING
               tokens are concatenated *)
DIRECTIVE = "#" { any } newline ;
            (* only as the first token on a line; backslash-newline
               continues it; comments inside are skipped *)

(* Comments are // to end of line and /* ... */. A /// line or a /** */ block
   directly above a declaration is a documentation comment for `moxy doc`, and
   its ```moxy fences are examples run by `moxy test`; to the parser it is an
   ordinary comment. On top of the C
   punctuation, Moxy adds  ..  ..=  =>  ::  |>  ??  ?.  and  @ . *)


(* ---- 2. Program and top level -------------------------------------- *)

program   = { top_item | test_block } ;

test_block = "test" STRING block ;
            (* file scope only, not inside a namespace; the STRING has no
               interpolation. `moxy test` keeps the blocks of the file it was
               given; every other command parses them and leaves them out *)

top_item  = DIRECTIVE
          | ";"
          | type_hint
          | namespace
          | using
          | static_assert
          | moxy_enum
          | impl
          | interface
          | actor
          | [ [ "shared" ] "ref" ] decl_group ;
            (* "ref" only directly before "struct", "shared" only before "ref struct" *)

(* Directives:
   - #include "x.mxy" and #include <x.mxy> are replaced by the tokens of
     that file before parsing; each file is spliced once. Other includes
     and directives (#define, #include <stdio.h>, ...) are copied to C.
   - At top level, #if #ifdef #ifndef #elif #else #endif are not copied
     as text: each declaration between them is tagged with the condition
     and emitted under it. They must balance by end of file.
   - #pragma once is dropped.
   - Inside function and struct bodies every directive is copied through
     unchanged. *)

type_hint = "@" "type" IDENT { "," IDENT } [ ";" ] ;
            (* declares C typedef names that come from headers *)

namespace = "namespace" IDENT { "::" IDENT } "{" { top_item } "}" ;
            (* nests: namespace a { namespace b { } } equals namespace a::b { } *)

using     = "using" IDENT { "::" IDENT } ";" ;

static_assert = "_Static_assert" "(" assign_expr [ "," assign_expr ] ")" ";" ;


(* ---- 3. Moxy enums ------------------------------------------------- *)

(* "enum Name {" is a Moxy (tagged) enum when its body has a '(' at the
   top nesting level. Otherwise it is a Moxy enum when the body has no
   '=' and the closing '}' is not followed by ';', an IDENT or '*' (an
   "impl" or "interface" that starts a block counts as no IDENT).
   Everything else is a C enum (c_enum_body). Moxy enums are recognized
   only at top level and directly inside namespaces.

     enum Shape { Circle(double r), Rect(double w, double h), Empty }  Moxy
     enum Color { Red, Green, Blue }                                   Moxy
     enum Mode { A, B };                                               C
     enum Level { Low = 1, High = 2 }                                  C  *)

moxy_enum     = "enum" IDENT [ type_params ] "{" [ variant { "," variant } [ "," ] ] "}" [ ";" ] ;
                (* with type_params it is always a Moxy enum *)
variant       = IDENT [ "(" [ variant_field { "," variant_field } [ "," ] ] ")" ] ;
variant_field = type_name [ IDENT ] ;   (* unnamed fields are called _0, _1, ... *)


(* ---- 3a. Generics -------------------------------------------------- *)

(* Type parameters follow the declared name of a struct, ref struct,
   Moxy enum or function; generic declarations appear only at top level
   or directly inside a namespace, and not inside a typedef.

     struct Pair<A, B> { A first; B second; }
     enum Option<T> { Some(T value), None }
     T max<T: Ord>(T a, T b) { ... }

   A prescan of the whole program learns the generic names first:
   "struct", "union" or "enum" IDENT "<", and at top level an IDENT
   followed by a type_params-shaped list and "(". While a generic
   declaration is parsed, its parameter names are type names. *)

type_params = "<" type_param { "," type_param } ">" ;
type_param  = IDENT [ ":" bound { "+" bound } ] ;
bound       = IDENT { "::" IDENT } [ type_args ] ;   (* an interface: Ord, Into<string> *)

type_args   = "<" type_name { "," type_name } ">" ;
              (* a ">>" closing two lists is split. "<" after a name starts
                 type_args only when the name is a known generic; otherwise
                 it is less-than. In an expression the list must be followed
                 by "(", "{" or "::", or, after a generic function's name,
                 by ";" "," ")" "]" or "}", or, after a generic type's name,
                 by "." IDENT (reflection: Pair<int, string>.fields). After a known non-generic type
                 name a type-shaped "<...>" is an error. *)


(* ---- 3b. Methods and interfaces ----------------------------------- *)

(* Both blocks appear only at top level or directly inside a namespace.
   "impl" starts one when it is followed by an IDENT, "<", a type keyword
   or "struct", and no type is named impl. "interface" starts one when it
   is followed by IDENT and "{" or "<". Inside either block, Self is a
   type name: the implementing type.

     impl Point { double len() { ... } static Point at(double x) { ... } }
     impl Shape for Point { ... }
     impl<T: Eq> Pair<T, T> { ... }
     interface Into<U> { U into(); }                                     *)

impl       = "impl" [ type_params ] [ iface_ref "for" ] type_name "{" { method } "}" ;
iface_ref  = IDENT { "::" IDENT } [ type_args ] ;
             (* read as the interface when "for" follows it *)
interface  = "interface" IDENT [ type_params ] "{" { method } "}" ;
method     = ";"
           | [ "static" ] specifiers declarator ( block | ";" ) ;
             (* a function; "self" is implicit unless "static". In an impl
                every method has a block; in an interface a block is a
                default body and ";" a required method. A method's own
                type_params are an error. *)

(* ---- 3c. Actors ---------------------------------------------------- *)

(* "actor" starts one at top level or directly inside a namespace, when it
   is followed by IDENT and "{", and no type is named actor. A member whose
   declaration reaches a "{" before a ";" (and doesn't start with struct,
   union or enum) is a method, as in an impl block; every other member is a
   field, as in a struct body. Inside the block, Self is the actor's type.

     actor Counter {
         long n;
         void add(long k) { self.n += k; }   cast: c.add(1) returns at once
         long get() { return self.n; }       call: await c.get()
     }                                                                    *)

actor      = "actor" IDENT "{" { ";" | method | field_decl } "}" ;
field_decl = specifiers [ declarator [ ":" cond_expr ] { "," declarator [ ":" cond_expr ] } ] ";" ;

(* A dyn type: "dyn" followed by the name of an interface the program
   declares (or a standard one), wherever a type can start, unless a
   type is named dyn. *)
dyn_type   = "dyn" IDENT { "::" IDENT } [ type_args ] ;


(* ---- 4. Declarations ----------------------------------------------- *)

decl_group = specifiers ";"                         (* tag only: struct S; enum E {..}; *)
           | specifiers                             (* see note: definition ending its line *)
           | specifiers declarator [ in_gate ] block            (* function definition, top level only *)
           | specifiers declarator in_gate ";"                  (* its prototype *)
           | wrap_macro declarator ( block | ";" )  (* top level only *)
           | specifiers init_decl { "," init_decl } ";" ;

in_gate    = "in" "gate" ;
             (* after a function's parameter list (and on a method's): the
                function allocates into its caller's gate and returns without
                a copy; a return from inside a gate of its own is an error,
                and so is "in gate" on an async or Future function *)

(* Library headers wrap a function's return type in a macro, or put a
   calling-convention macro before its name. Both are kept and written back
   in the same place in the generated C:
     CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) { ... }
     static void * CJSON_CDECL internal_malloc(size_t size) { ... }
   wrap_macro is read at top level when an IDENT that is not a type is
   followed by "(", a type, ")", then IDENT "(". A macro type name inside it
   that only C headers declare is learned from that spelling. *)
wrap_macro = IDENT "(" specifiers declarator ")" ;

(* A struct, union or enum definition whose closing '}' is the last token
   on its line needs no ';'. If anything else follows on the same line
   (a declarator, or a '}' closing a namespace) the normal rules apply. *)

init_decl  = declarator [ "=" initializer ] ;

(* "auto" with no type after it declares a variable whose type comes from
   the initializer, which is then required:  auto n = xs.len;
   "auto" followed by a type is the C storage class. *)

specifiers = spec_item { spec_item } { "[" [ ".." ] "]" | "?" } ;
             (* each trailing "[]" makes a Moxy list: int[] xs, string[][] grid;
                "[..]" makes a slice, a view of a list, C array or slice:
                int[..] mid, string[..][] parts;
                each "?" an optional: int? x, Node?[] xs (a list of optionals),
                int[]? xs (an optional list). i8 ... f64 and string take "?"
                only when what follows reads as a declaration (IDENT then
                "=" ";" "," ")", or "[" "," ">" ")"), so `string ? a : b`
                on a variable named string is still C *)

spec_item  = storage | qualifier
           | "void" | "char" | "short" | "int" | "long" | "float" | "double"
           | "signed" | "unsigned" | "bool" | "_Bool" | "string"
           | tag_spec
           | type_ref
           | field_qual
           | "async" ;
             (* "async" only before a type, and only on a function: its
                call runs on the calling thread and returns a Future of the
                declared type: async int load(string path) { ... }.
                Elsewhere it is an error; a name "async" (int async = 1,
                async(x)) stays C *)

field_qual = "weak" | "unowned" | "strong" | "atomic" ;
             (* only on struct fields; weak, unowned and strong directly
                before a type name IDENT, atomic before any type. unowned,
                strong and atomic stay ordinary names when a typedef
                already took them *)

storage    = "static" | "extern" | "inline" | "_Noreturn" | "_Thread_local"
           | "register" | "typedef" | "auto" ;
qualifier  = "const" | "volatile" | "restrict" ;

(* A specifier list holds at most one tag_spec or type_ref and does not
   mix it with the builtin type words. With only storage classes and
   qualifiers the type is int. *)

type_ref   = type_path | moxy_type | dyn_type | reflect_type ;

reflect_type = IDENT "." ( "type" | "elem" | "key" | "value" ) ;
             (* "type" only when IDENT is the variable of an enclosing static for:
                f.type tmp = v.[f];  (f.type)0  sizeof(f.type)
                "elem", "key" and "value" only when IDENT is a type parameter in scope:
                T.elem x = ...;  json_decode<T.elem>(j)  *)

type_path  = IDENT { "::" IDENT } [ type_args ] ;   (* type_args: generic types only *)
             (* a known type name: a struct/union/enum tag or typedef seen
                anywhere in the program, an @type name, or a common C
                typedef (size_t, int64_t, FILE, pthread_t, ...). An unknown
                IDENT followed by IDENT, or by "*" IDENT, is also read as
                a C typedef name, and so is an IDENT after "const" or
                "volatile" that is followed by "*" or IDENT.
                i8 i16 i32 i64 u8 u16 u32 u64 isize usize f32 f64 are type
                names when followed by IDENT, "*", ")", ",", ">", ">>", "[",
                "]" or a qualifier, unless the program declares that name
                as a variable, field or function. *)

moxy_type  = "map" "[" type_name "," type_name "]"
           | "Result" "<" type_name [ "," type_name ] ">"   (* Result<T> is Result<T, string> *)
           | "Future" "<" type_name ">"          (* ">>" closing two types is split *)
           | "chan" "<" type_name ">"
           | "fn" [ "?" ] "(" [ type_name { "," type_name } ] ")" [ "->" type_name ] ;
             (* closure type; without "->" it returns void. fn?(A) -> R is
                an optional closure; fn(A) -> R? returns an optional.
                These words are types only in these shapes and only when
                no user type has the same name. "chan" is also not a type
                when the program declares a variable, field or function
                named chan. *)

tag_spec   = "struct" IDENT type_params struct_body       (* generic; also after "ref" *)
           | ( "struct" | "union" ) ( IDENT [ struct_body ] | struct_body )
           | "enum" ( IDENT [ c_enum_body ] | c_enum_body ) ;

struct_body = "{" { member } "}" ;
member      = DIRECTIVE
            | ";"
            | specifiers ";"                            (* anonymous struct/union *)
            | specifiers member_decl { "," member_decl } ";" ;
member_decl = declarator [ ":" cond_expr ] ;           (* bit-field width *)

c_enum_body = "{" [ enumerator { "," enumerator } [ "," ] ] "}" ;
enumerator  = IDENT [ "=" cond_expr ] ;


(* ---- 5. Declarators ------------------------------------------------ *)

declarator  = { "*" { qualifier } } direct_decl ;
direct_decl = ( "(" [ IDENT ] declarator ")" | [ [ IDENT ] IDENT [ type_params ] ] ) { decl_suffix } ;
              (* the optional first IDENT is a calling-convention macro: before
                 a function's name when IDENT IDENT "(" follows and the first
                 is not a type name (kept in the generated C), or before the
                 "*" of a nested declarator, void *(CONV *fn)(int) (dropped:
                 x86-64 and ARM64, the only targets, ignore conventions) *)
              (* type_params only on a top-level function declaration *)
              (* "(" opens a nested declarator when followed by "*", "(",
                 or IDENT ")" where IDENT is not a type name:
                   int (*cmp)(const void *, const void *);
                   int (*table[4])(int);
                   void (*handler(int sig, void (*cb)(int)))(int);  *)

decl_suffix = "[" { "static" | "const" | "restrict" } [ assign_expr ] "]"
            | "(" param_list ")" ;
              (* int xs[] is a C array; int[] xs is a Moxy list *)

param_list  = "void"
            | "..."
            | [ param { "," param } [ "," "..." ] ] ;
param       = specifiers declarator ;                  (* name optional *)

type_name   = specifiers declarator ;                  (* abstract: no name *)


(* ---- 6. Statements ------------------------------------------------- *)

block     = "{" { statement } "}" ;

statement = DIRECTIVE
          | block
          | ";"
          | "if" "(" expr ")" statement [ "else" statement ]
          | "while" "(" expr ")" statement
          | "do" statement "while" "(" expr ")" ";"
          | for_c
          | for_in
          | parallel_for
          | "switch" "(" expr ")" statement
          | "case" cond_expr [ "..." cond_expr ] ":"     (* GNU case range *)
          | "default" ":"
          | "break" end
          | "continue" end
          | "return" [ initializer | expr ] end
          | "goto" IDENT ";"
          | IDENT ":" [ statement ]          (* label; statement omitted only before "}" *)
          | static_assert
          | static_for
          | static_if
          | match
          | select
          | defer
          | lock
          | gate
          | local_decl
          | macro_loop
          | expr end ;

(* A call to a name that isn't a Moxy function, directly followed by a block,
   is a C macro that expands to a loop header, as in cJSON's
     cJSON_ArrayForEach(element, array) { ... }
   The block is the loop body: break and continue apply to it. When the name
   is a Moxy function, it is a call statement followed by a block. *)
macro_loop = IDENT "(" [ arg { "," arg } ] ")" block ;

(* case and default are labels: they do not own the statements after them. *)

(* Expression-statement rule: the ';' after an expression, break,
   continue or return may be left out when the next token starts a new
   line, is '}', or is end of file. Inside a match arm a ',' also ends the
   statement. Declarations, goto, do-while and _Static_assert always need
   their ';'. *)
end       = ";" | (* nothing, under the rule above *) ;

local_decl = decl_group ;   (* no function definitions inside functions *)

(* A statement is read as a declaration when it starts with a storage
   class, a type keyword, a Moxy type shape, or a known type name not
   followed by '{', '(', '.', '->' or '='. An unknown IDENT starts a
   declaration when followed by an IDENT other than "in", by "*"... IDENT
   and then ';' '=' ',' or '[', or by "[" "]" IDENT or "[" ".." "]" IDENT. *)

for_c     = "for" "(" ( local_decl | [ expr ] ";" ) [ expr ] ";" [ expr ] ")" statement ;

for_in    = "for" IDENT [ "," IDENT ] "in" iterable statement ;
parallel_for = "parallel" for_in ;
            (* "parallel" directly before "for", unless a type is named
               parallel. The iterable must be a range (a..b, a..=b) and the
               loop has one name *)
            (* no parentheses. With two names the first is the index
               (lists, arrays, strings) or the key (maps). A channel takes
               one name and receives until it is closed and empty. *)
iterable  = expr [ ( ".." | "..=" ) expr ] ;
            (* a..b excludes b, a..=b includes it. Outside for-in, ranges
               appear only inside slice brackets (postfix_expr).
               Type{...} literals are not parsed in the head. *)

defer     = "defer" ( block | statement ) ;
            (* recognized when "defer" is followed by "{", "*", "return",
               or an IDENT that is not followed by ";" or "=" *)

lock      = "lock" "(" expr ")" block ;
            (* recognized when the ")" closing the parenthesis after "lock"
               is followed by "{", so a call statement lock(x); is still C.
               expr names a variable holding a shared ref struct *)

gate      = "gate" [ "(" expr ")" ] block ;
            (* recognized when "gate" is directly followed by "{", or by a
               parenthesis whose closing ")" is followed by "{", and isn't a
               type name; anywhere else gate is an ordinary name, and gate(x);
               is still a call. With "(" expr ")" the block allocates from
               that Arena (std/arena.mxy), whose memory outlives the block.
               The block can't contain goto, a label, or a case or default
               label of a switch outside it *)


(* ---- 6a. Compile-time reflection ----------------------------------- *)

static_for  = "static" "for" IDENT "in" unary_expr statement ;
              (* the source is T.fields, T.variants or c.fields; Type{...}
                 literals are not parsed in it. The body is unrolled once
                 per item by sema, so the loop never reaches C. *)

static_if   = "static" "if" "(" static_cond ")" statement [ "else" statement ] ;
              (* else static if chains like else if *)

static_cond = expr ;
              (* inside the condition a primary may also be a type, and
                 "(" only groups (there are no casts):
                   static_operand = type_name [ ":" IDENT { "::" IDENT } [ type_args ] ]
                 A type is read when the operand is f.type, string, a type
                 keyword, or a type name not followed by "." or "(", so
                 T.fields.len still parses as an expression. "T: Iface"
                 asks whether T implements an interface, as a bound
                 would: T: Ord, T: Into<string>. *)

(* Reflection properties are ordinary member accesses on a type or a
   static for variable, resolved by sema: T.name T.fields T.variants,
   xs.len, f.name f.index f.type, c.name c.index c.fields, and the kind
   queries T.is_struct T.is_enum T.is_simple T.is_list T.is_map
   T.is_optional T.is_bool T.is_int T.is_unsigned T.is_float (0 or 1) and the
   types T.elem T.key T.value. A generic instance can be the base:
   Pair<int, string>.fields. *)


(* ---- 7. match ------------------------------------------------------ *)

match     = "match" expr "{" { arm } "}" ;
            (* a statement, not an expression. Recognized when "match" is
               followed by "(" ... ")" "{", or by an IDENT, number, string,
               char, true, false, "*", "!", "-" or "[" (but not IDENT "="
               or IDENT ";"). Type{...} literals are not parsed in the
               subject. *)

arm       = pattern [ "if" assign_expr ] "=>" arm_body ;
            (* the guard sees the pattern's bindings. A "(" ... ")" right
               before "=>" is part of the pattern or guard, not a lambda's
               parameter list. *)

pattern   = alt_pattern { "|" alt_pattern } ;
            (* alternatives; each binds the same names at the same types.
               A literal is parsed above "|", so 1 | 2 is two alternatives
               and (A | B) is one value, C's bitwise or. *)

alt_pattern = "_" | "default" | "else"                       (* wildcard; the last two only at top level *)
          | variant_path "(" [ pattern { "," pattern } ] ")"
          | variant_path "{" [ field_pattern { "," field_pattern } [ "," ] ] "}"
          | variant_path                                     (* before "=>" "|" "," ")" "}" or "if" *)
          | xor_expr ;                                       (* literal or constant, above "|" *)

field_pattern = "." IDENT "=" pattern ;                      (* fields not named match anything *)

variant_path = IDENT { "::" IDENT } ;
            (* "(" after it makes a constructor pattern when the path
               contains "::", is Ok or Err, or starts with an uppercase
               letter; "{" "." or "{" "}" after it makes a struct pattern
               when the path contains "::" or starts with an uppercase
               letter. Otherwise the tokens are reparsed as an operand.
               A bare name means, in order: a constructor of the matched
               type (a variant, Some, None, Ok, Err); a binding when it
               starts with a lowercase letter or "_"; a constant compared
               by value otherwise:
               Shape::Circle(r)  Circle(r)  Red  Ok(v)  Err(e)  Some(v)
               None  0  'a'  "text"  MAX_SIZE  n  Some(Ok(0))
               Point{ .x = 0, .y = y }  1 | 2 | 3 *)

arm_body  = block [ "," ]
          | arm_stmt [ "," ]
          | assign_expr [ ";" ] arm_end ;
arm_stmt  = (* a statement starting with return, break, continue, if,
               while, for, do, switch, goto or ";" *) ;
arm_end   = "," | (* nothing, when the next token is "}" or starts a new line *) ;


(* ---- 7a. select ---------------------------------------------------- *)

select    = "select" "{" sel_arm { sel_arm } "}" ;
            (* recognized when "select" is followed by "{", so a C call
               select(n, ...) is unaffected *)

sel_arm   = sel_case "=>" arm_body ;
sel_case  = [ IDENT "=" ] postfix_expr "." "recv" "(" ")"   (* binds Result<T> *)
          | postfix_expr "." "send" "(" assign_expr ")"
          | "timeout" "(" assign_expr ")"                  (* milliseconds *)
          | "default" | "_" ;
            (* at most one default and one timeout, not both. Type{...}
               literals are not parsed in a case. *)


(* ---- 8. Expressions ------------------------------------------------ *)

expr        = assign_expr { "," assign_expr } ;

assign_expr = cond_expr [ assign_op ( brace_init | assign_expr ) ] ;
assign_op   = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^="
            | "<<=" | ">>=" ;

cond_expr   = coalesce_expr [ "?" expr ":" cond_expr ] ;

coalesce_expr = pipe_expr [ "??" coalesce_expr ] ;       (* right associative *)

(* Binary operators from src/parse/expr.c, lowest to highest precedence.
   All are left associative.

     1   |>
     2   ||
     3   &&
     4   |
     5   ^
     6   &
     7   ==  !=
     8   <  >  <=  >=
     9   <<  >>
    10   +  -
    11   *  /  %                                                    *)

pipe_expr   = or_expr { "|>" postfix_expr } ;
              (* x |> f is f(x); x |> f(a, b) is f(x, a, b); the right
                 side must be a call, a name or a member. The left side is
                 the whole expression before "|>", but an operator after
                 the right side applies to the result: 1 + 2 |> f is f(3),
                 x |> f + 1 is f(x) + 1. *)
or_expr     = and_expr { "||" and_expr } ;
and_expr    = bitor_expr { "&&" bitor_expr } ;
bitor_expr  = xor_expr { "|" xor_expr } ;
xor_expr    = bitand_expr { "^" bitand_expr } ;
bitand_expr = eq_expr { "&" eq_expr } ;
eq_expr     = rel_expr { ( "==" | "!=" ) rel_expr } ;
rel_expr    = shift_expr { ( "<" | ">" | "<=" | ">=" ) shift_expr } ;
shift_expr  = add_expr { ( "<<" | ">>" ) add_expr } ;
add_expr    = mul_expr { ( "+" | "-" ) mul_expr } ;
mul_expr    = unary_expr { ( "*" | "/" | "%" ) unary_expr } ;

unary_expr  = ( "-" | "+" | "!" | "~" | "*" | "&" | "++" | "--" ) unary_expr
            | "sizeof" "(" type_name ")"
            | "sizeof" unary_expr
            | "_Alignof" "(" type_name ")"
            | "await" postfix_operand { postfix_tail }
                                         (* when followed by IDENT or "(" *)
              (* await's operand is a primary with its calls, indexing and
                 member accesses, stopping before a postfix "?" or "!",
                 which then apply to the awaited value:
                 await f()? is (await f())?, await x.load() awaits x.load().
                 postfix_operand is postfix_expr without a trailing "?" or
                 "!"; postfix_tail is any postfix_expr suffix. Before any
                 other token (await await f, await *p) the operand is a
                 unary_expr *)
            | "(" type_name ")" unary_expr                     (* cast *)
            | postfix_expr ;
              (* "(" starts a cast when a type follows it; also for an
                 unknown (IDENT "*"...) and for an unknown (name_t)
                 followed by a name, literal or "(". Note that (int[]) is
                 a cast to a Moxy list, not a C array. *)

postfix_expr = primary { "(" [ arg { "," arg } ] ")"
                       | "[" expr "]"
                       | "[" [ expr ] ".." [ expr ] "]"     (* slice: a[i..j], a[i..], a[..j], a[..] *)
                       | "[" [ expr ] "..=" expr "]"        (* inclusive slice: a[i..=j], a[..=j] *)
                       | ( "." | "->" | "?." ) ( IDENT | keyword )
                       | ( "." | "->" ) "[" IDENT "]"     (* v.[f], p->[f] *)
                       | "++" | "--"
                       | "!"                              (* unwrap *)
                       | "?" } ;                          (* return early on Err or null *)
               (* "?." is one token unless a digit follows ("c ?.5 : 1" is C).
                  A postfix "?" is one not followed by an expression and then
                  a ":" of its own at the same nesting depth, so C's
                  c ? a : b keeps its meaning; "c ? f()? : g" reads the inner
                  "?" as postfix. "!" after an operand is postfix unless it
                  starts a line ("!=" is its own token). *)
arg          = brace_init | type_name | assign_expr ;
               (* type_name when the argument starts with a type keyword,
                  or a known type name followed by "," ")" or "*": a type
                  passed to a C macro, as in va_arg(ap, int) *)

primary     = INT | FLOAT | CHAR | STRING { STRING }
            | "true" | "false" | "null"
            | "string" "(" [ arg { "," arg } ] ")"   (* conversion; "(" required *)
            | ( "Ok" | "Err" ) "(" [ assign_expr ] ")"
            | "chan" "<" type_name ">" "(" [ assign_expr ] ")"   (* capacity; none = unbuffered *)
            | list_lit
            | brace_init
            | lambda
            | "spawn" block                           (* a Future of the block's return value *)
            | "(" type_name ")" brace_init            (* compound literal *)
            | "(" expr ")"
            | type_path brace_init                    (* struct literal *)
            | IDENT { "::" IDENT } [ type_args [ "::" IDENT ] ] ;
              (* name, ns::name, Enum::Variant; with type_args:
                 first<long>(xs), id<int>, Option<int>::None,
                 Pair<int, string>{ ... } *)
              (* type_path brace_init needs the last segment to be a known
                 type name, or Self inside an impl: Point{ .x = 1 },
                 geo::Point{ 1, 2 }, Self{ .items = [] }.
                 Type::name(args) calls a static method: Point::at(1, 2).
                 Enum::Variant(args) is a call on the path. *)

list_lit    = "[" [ initializer { "," initializer } [ "," ] ] "]" ;

lambda      = [ "async" ] "(" param_list ")" "=>" ( block | assign_expr ) ;
              (* chosen when the ")" matching "(" is followed by "=>";
                 every parameter needs a name:  (int x) => x * 2
                 () => { print("hi") }. With "async" its calls run as async
                 calls and return a Future: async (int x) => x * 2 is a
                 fn(int) -> Future<int> *)

brace_init  = "{" [ init_item { "," init_item } [ "," ] ] "}" ;
init_item   = "." IDENT { "." IDENT } "=" initializer      (* .pos.x = 1 *)
            | "[" cond_expr "]" "=" initializer            (* [2] = 5 *)
            | initializer [ ":" initializer ] ;            (* "key": value *)
initializer = brace_init | assign_expr ;

Edit this page on GitHub