Contents Open

DocsLanguage Reference

Summary of the Grammar

The language's formal grammar, in EBNF.

This chapter is Sable's formal grammar, spec/grammar.ebnf from the language repository, reproduced in full. The reference chapters quote the productions they describe; here they are all together, in the grammar file's own order. The file's section rules have become the headings of this page, and everything else is copied exactly.

The grammar describes what the parser accepts, not everything the compiler then checks: a program the grammar admits may still be refused by the type checker, and a few productions are accepted by the parser for constructs the compiler does not give a meaning yet (see Declarations). Where the grammar and the parser differ, the reference chapters follow the parser and say so: notably, casts (as, as?, as!, unchecked as, is) bind as postfix operators, tighter than any prefix operator, as the precedence table in Expressions shows, and try covers the whole expression to its right short of an assignment.

Newlines are significant only as statement terminators, by the rule in Lexical Structure; NL in the grammar stands for one.

Notation#

EBNF
(* ========================================================================== *)(*  The Sable Programming Language — Formal Grammar                           *)(*  Version 0.1 (design draft)                                                *)(*                                                                            *)(*  Notation:                                                                 *)(*    =            definition                                                 *)(*    |            alternation                                                *)(*    [ x ]        optional                                                   *)(*    { x }        zero or more                                               *)(*    ( x )        grouping                                                   *)(*    "x"          terminal                                                   *)(*    (* ... *)    comment                                                    *)(*                                                                            *)(*  The grammar is LL(k) with a small number of parser-directed decisions,     *)(*  noted inline. Newlines are significant only as statement terminators       *)(*  (see lexical.md §4); NL below denotes a statement break.                   *)(* ========================================================================== *)

Compilation unit#

EBNF
CompilationUnit   = [ ShebangLine ] ModuleDecl { ImportDecl } { TopLevelDecl } EOF ;ModuleDecl        = { Attribute } "module" QualifiedName NL ;ImportDecl        = [ "public" ] "import" ImportTarget NL ;ImportTarget      = QualifiedName [ "as" Identifier ]                  | QualifiedName "." "{" ImportItem { "," ImportItem } "}"                  | QualifiedName "." "{" "*" "}" ;                    (* the wildcard is braced so that the statement cannot end                       on '*', which is not a statement-ending token *)ImportItem        = Identifier [ "as" Identifier ] ;QualifiedName     = Identifier { "." Identifier } ;TopLevelDecl      = Declaration                  | ComptimeBlock                  | ConditionalCompilation ;

Declarations#

EBNF
Declaration       = { Attribute } { Modifier } DeclarationKind ;DeclarationKind   = FunctionDecl                  | StructDecl                  | ClassDecl                  | ActorDecl                  | ProtocolDecl                  | UnionDecl                  | EnumDecl                  | ExtensionDecl                  | AliasDecl                  | VariableDecl                  | ConstDecl                  | InitDecl                  | DeinitDecl                  | PropertyDecl                  | SubscriptDecl                  | OperatorDecl ;Modifier          = Visibility                  | "static" | "open" | "sealed" | "abstract" | "final"                  | "override" | "required" | "convenience" | "mutating"                  | "nonmutating" | "lazy" | "async" | "const" | "nonisolated"                  | "unsafe"                  | "weak" | "unowned" [ "(" ( "safe" | "unsafe" ) ")" ] ;(* "unsafe" is a modifier only before "fn" or another modifier, on a   function: "unsafe fn", "unsafe static fn". Before a block it starts an   UnsafeBlock. *)Visibility        = "public" | "package" | "internal" | "private"                  | "private" "(" "set" ")" ;Attribute         = "@" QualifiedName [ "(" [ AttributeArgs ] ")" ] ;AttributeArgs     = AttributeArg { "," AttributeArg } ;AttributeArg      = [ Identifier ":" ] Expression ;

Functions#

EBNF
FunctionDecl      = "fn" FunctionName [ GenericParams ] "(" [ ParamList ] ")"                    [ EffectSpec ] [ "->" ReturnType ]                    [ WhereClause ]                    FunctionBody ;FunctionName      = Identifier | QualifiedName ;   (* QualifiedName: explicit                                                      protocol implementation,                                                      e.g. fn Drawable.render *)FunctionBody      = Block                  | "=>" Expression NL                  | NL ;                            (* no body: protocol / abstract *)EffectSpec        = { "async" | ThrowsSpec } ;ThrowsSpec        = "throws" [ "(" Type ")" ] | "rethrows" ;ReturnType        = Type ;                         (* "-> Node&" returns a reference *)ParamList         = Param { "," Param } [ "," ] ;Param             = { Attribute } [ ParamModifier ] [ ParamLabel ] Identifier                    ":" [ ParamModifier ] Type [ "..." ] [ "=" Expression ] ;                    (* the modifier may precede the name or follow the colon;                       the second form composes with an external label.                       'in name:' is the label 'in', not the modifier:                       'fn build(in r: region)' is called 'build(in: a)' *)ParamModifier     = "inout" | "out" | "consuming" | "in" ;                    (* a parameter that refers to its argument says so in                       its type, "a: Node&"; "ref" and "borrowing" are                       reserved, and an error (S1013) *)ParamLabel        = Identifier | Keyword | "_" ;    (* external label *)

Type declarations#

EBNF
StructDecl        = "struct" Identifier [ GenericParams ] [ ":" TypeList ]                    [ WhereClause ] TypeBody ;ClassDecl         = "class" Identifier [ GenericParams ] [ ":" TypeList ]                    [ WhereClause ] TypeBody ;ActorDecl         = "actor" Identifier [ GenericParams ] [ ":" TypeList ]                    [ WhereClause ] TypeBody ;ProtocolDecl      = "protocol" Identifier [ GenericParams ] [ ":" TypeList ]                    [ WhereClause ] ProtocolBody ;UnionDecl         = "union" Identifier [ ".." ] [ GenericParams ]                    [ ":" TypeList ] [ WhereClause ] UnionBody ;                    (* ".." marks a variant-sized union *)EnumDecl          = "enum" Identifier [ ":" Type ] EnumBody ;ExtensionDecl     = "extension" Type [ ":" TypeList ] [ WhereClause ] TypeBody ;AliasDecl         = "alias" Identifier [ GenericParams ] "=" Type NL ;TypeBody          = "{" { MemberDecl } "}" ;ProtocolBody      = "{" { ProtocolMember } "}" ;MemberDecl        = Declaration                  | TerseFieldDecl                  | AssociatedTypeDecl                  | ConditionalCompilation ;ProtocolMember    = { Attribute } { Modifier }                    ( AssociatedTypeDecl                    | FunctionDecl            (* body optional = default impl *)                    | PropertyDecl                    | SubscriptDecl                    | InitDecl                    | OperatorDecl ) ;AssociatedTypeDecl = "associatedtype" Identifier [ ":" TypeList ]                     [ "=" Type ] [ WhereClause ] NL ;                     (* the where clause is the protocol's: "where Iter.Element == Element" *)UnionBody         = "{" { UnionCase } { MemberDecl } "}" ;UnionCase         = { Attribute } Identifier [ "(" [ CasePayload ] ")" ]                    [ "," ] NL ;CasePayload       = CaseField { "," CaseField } ;CaseField         = [ Identifier ":" ] Type ;EnumBody          = "{" EnumCase { [ "," ] EnumCase } "}" ;EnumCase          = { Attribute } Identifier [ "=" Expression ] ;

Members#

EBNF
VariableDecl      = [ "async" ] [ "using" ] ( "let" | "var" ) BindingPattern                    [ ":" Type ] [ "=" Expression ] [ Accessors ] [ "," | ";" ] NL ;TerseFieldDecl    = Identifier ":" Type [ "=" Expression ] [ Accessors ]                    [ "," | ";" ] NL ;                    (* inside a type body only; declares an immutable field *)ConstDecl         = "const" Identifier [ ":" Type ] "=" Expression NL ;PropertyDecl      = ( "let" | "var" ) Identifier ":" Type Accessors ;Accessors         = "{" ( GetSetBlock | ObserverBlock | "get" [ "set" ] ) "}" ;GetSetBlock       = GetAccessor [ SetAccessor ] | SetAccessor GetAccessor ;GetAccessor       = { Attribute } [ Visibility ] "get" ( Block | "=>" Expression | NL ) ;SetAccessor       = { Attribute } [ Visibility ] "set" [ "(" Identifier ")" ]                    ( Block | NL ) ;ObserverBlock     = { ( "willSet" | "didSet" ) [ "(" Identifier ")" ] Block } ;InitDecl          = "init" [ "?" ] [ GenericParams ] "(" [ ParamList ] ")"                    [ ThrowsSpec ] [ WhereClause ] ( Block | NL ) ;DeinitDecl        = "deinit" Block ;SubscriptDecl     = "subscript" [ GenericParams ] "(" [ ParamList ] ")"                    "->" Type [ WhereClause ] ( Accessors | "=>" Expression NL ) ;OperatorDecl      = [ "prefix" | "postfix" ] "operator" OperatorSymbol                    "(" [ ParamList ] ")" "->" Type ( Block | "=>" Expression NL ) ;OperatorSymbol    = "+" | "-" | "*" | "/" | "%" | "&" | "|" | "^"                  | "<<" | ">>" | "==" | "!=" | "<" | "<=" | ">" | ">="                  | "[" "]" | "(" ")" | "!" | "~" ;

Generics#

EBNF
GenericParams     = "<" GenericParam { "," GenericParam } ">" ;GenericParam      = { Attribute } [ "out" | "in" ] Identifier                    [ ":" TypeList ] [ "=" Type ] ;                                                 (* "N: Int", an integer type: a value parameter *)WhereClause       = "where" WhereItem { "," WhereItem } ;WhereItem         = Type ":" TypeList            (* conformance / inheritance *)                  | Type "==" Type               (* same-type constraint      *)                  | Expression ;                 (* const generic predicate   *)TypeList          = ConstraintType { "&" ConstraintType } ;   (* composition in constraints *)ConstraintType    = [ "~" ] Type ;               (* "~Copyable" lifts the implicit constraint *)

Types#

EBNF
Type              = UnionType ;UnionType         = IntersectionType { "|" IntersectionType } ;    (* structural union *)IntersectionType  = PostfixType { "&" PostfixType } ;              (* composition *)PostfixType       = PrimaryType { TypeSuffix } ;TypeSuffix        = "?"                                   (* optional *)                  | "!"                                   (* iuo *)                  | "&" [ "<" RelRefSpec ">" ] [ "?" ]    (* reference *)                  | ArraySuffix                  | "." Identifier [ GenericArgs ] ;      (* nested / associated *)RelRefSpec        = ( "u8" | "u16" | "u32" | "i8" | "i16" | "i32" )                    [ "in" Identifier ] ;ArraySuffix       = "[" "]"                               (* T[]      *)                  | "[" Expression "]"                    (* T[k]     *)                  | "[" ".." [ Expression ] "]"           (* T[..] T[..k] *)                  | "[" ">" ".." "]"                      (* T[>..]   *)                  | "[" ">" ".." "<" "]"                  (* T[>..<]  *)                  | "[" ":" "]"                           (* T[:]     *)                  | "[" Type ":" Type "]" ;               (* [K: V]   *)PrimaryType       = QualifiedName [ GenericArgs ]                  | "some" Type                  | "any" Type                  | "~" Type                (* "~Copyable", as a constraint only *)                  | TupleType                  | FunctionType                  | "(" Type ")"                  | "Self" ;TupleType         = "(" [ TupleTypeElem { "," TupleTypeElem } ] ")" ;TupleTypeElem     = [ Identifier ":" ] [ "inout" ] Type ;   (* "inout": a function type's parameter only *)FunctionType      = [ "async" ] TupleType [ ThrowsSpec ] "->" Type ;GenericArgs       = "<" GenericArg { "," GenericArg } ">" ;GenericArg        = Type                  | IntegerLiteral ;             (* for a value parameter: Buf<Int, 4> *)                    (* parser-directed: on '<' after a type name, scan for a                       balanced '>' not interrupted by a statement terminator *)

Statements#

EBNF
Block             = "{" { Statement } "}" ;Statement         = Declaration                  | ExpressionStatement                  | IfStatement                  | GuardStatement                  | WhileStatement                  | RepeatStatement                  | ForStatement                  | MatchStatement                  | SwitchStatement                  | DoStatement                  | RegionStatement                  | UsingStatement                  | DeferStatement                  | ReturnStatement                  | ThrowStatement                  | YieldStatement                  | BreakStatement                  | ContinueStatement                  | FallthroughStatement                  | UnsafeBlock                  | ComptimeBlock                  | ConditionalCompilation                  | LabeledStatement                  | Block                  | NL ;LabeledStatement  = Identifier ":" ( WhileStatement | ForStatement                                   | RepeatStatement | Block ) ;ExpressionStatement = Expression NL ;IfStatement       = "if" ConditionList Block                    { "else" "if" ConditionList Block }                    [ "else" Block ] ;GuardStatement    = "guard" ConditionList "else" Block ;ConditionList     = Condition { "," Condition } ;Condition         = "let" BindingPattern [ ":" Type ] [ "=" Expression ]                  | "var" BindingPattern [ ":" Type ] [ "=" Expression ]                  | "case" Pattern "=" Expression                  | Expression ;WhileStatement    = "while" ConditionList Block ;RepeatStatement   = "repeat" Block "while" Expression NL ;ForStatement      = "for" [ "try" ] [ "await" ] BindingPattern "in" Expression                    [ "where" Expression ] Block ;MatchStatement    = "match" Expression "{" { MatchCase } "}" ;MatchCase         = "case" PatternList [ "where" Expression ]                    ( "=>" ArmBody | ":" { Statement } )                  | "default" ( "=>" ArmBody | ":" { Statement } ) ;ArmBody           = Expression | Block | ReturnStatement | BreakStatement | ContinueStatement ;PatternList       = Pattern { "," Pattern } ;SwitchStatement   = "switch" Expression "{" { SwitchCase } "}" ;SwitchCase        = "case" ExpressionList ":" { Statement }                  | "default" ":" { Statement } ;ExpressionList    = Expression { "," Expression } ;DoStatement       = "do" Block { CatchClause } ;CatchClause       = "catch" [ Pattern [ "where" Expression ] ] Block ;RegionStatement   = "region" [ Identifier [ "=" Expression ] ] Block ;UsingStatement    = "using" ( "let" | "var" ) BindingPattern [ ":" Type ]                    "=" Expression NL ;                    (* no braced form: '{' after the initialiser would be a                       trailing closure on it *)DeferStatement    = "defer" Block ;ReturnStatement   = "return" [ Expression ] NL ;ThrowStatement    = "throw" Expression NL ;YieldStatement    = "yield" Expression NL ;         (* only in a generator's body:                                                 SYNTAX.md §5, "Generators" *)BreakStatement    = "break" [ Identifier ] NL ;ContinueStatement = "continue" [ Identifier ] NL ;FallthroughStatement = "fallthrough" NL ;UnsafeBlock       = "unsafe" Block ;ComptimeBlock     = "comptime" Block ;ConditionalCompilation =      "#if" CompileCondition { Statement | Declaration }    { "#elseif" CompileCondition { Statement | Declaration } }    [ "#else" { Statement | Declaration } ]      "#endif" ;CompileCondition  = Expression ;   (* restricted: identifiers, os(), arch(),                                      feature(), !, &&, ||, parentheses *)

Patterns#

EBNF
Pattern           = OrPattern ;OrPattern         = OptionalPattern { "|" OptionalPattern } ;(* 'let v?' is '.Some(let v)': the pattern, matched against what an   optional holds. *)OptionalPattern   = PrimaryPattern { "?" } ;PrimaryPattern    = WildcardPattern                  | BindingPattern                  | LiteralPattern                  | RangePattern                  | TuplePattern                  | UnionCasePattern                  | RecordPattern                  | ArrayPattern                  | TypeTestPattern                  | "(" Pattern ")" ;WildcardPattern   = "_" ;BindingPattern    = [ "let" | "var" ] Identifier                  | TuplePattern                  | RecordPattern ;LiteralPattern    = Literal | "-" NumericLiteral ;RangePattern      = Expression ( "..." | "..<" ) Expression                  | ( "..." | "..<" ) Expression                  | Expression ( "..." ) ;TuplePattern      = "(" [ Pattern { "," Pattern } ] ")" ;UnionCasePattern  = [ QualifiedName ] "." Identifier                    [ "(" [ SubPattern { "," SubPattern } ] ")" ] ;SubPattern        = [ Identifier ":" ] Pattern ;RecordPattern     = QualifiedName "{" [ FieldPattern { "," FieldPattern } ] "}" ;FieldPattern      = Identifier [ ":" Pattern ] ;ArrayPattern      = "[" [ ArrayPatternElem { "," ArrayPatternElem } ] "]" ;ArrayPatternElem  = Pattern | "..." [ "let" Identifier ] ;TypeTestPattern   = "is" Type                  | "let" Identifier "as" Type ;

Expressions#

EBNF
(*    Listed loosest-binding first; each level is left-associative unless      *)(*    noted. This mirrors SYNTAX.md §16.                                      *)Expression        = AssignExpr ;AssignExpr        = TernaryExpr [ AssignOp AssignExpr ]          (* right assoc *)                  | "_" "=" AssignExpr ;                         (* dropped *)AssignOp          = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|="                  | "^=" | "<<=" | ">>=" | "??=" | "&+=" | "&-=" | "&*=" ;TernaryExpr       = CoalesceExpr [ "?" Expression ":" TernaryExpr ] ;CoalesceExpr      = LogicalOrExpr { "??" LogicalOrExpr } ;       (* right assoc *)LogicalOrExpr     = LogicalAndExpr { "||" LogicalAndExpr } ;LogicalAndExpr    = BitOrExpr { "&&" BitOrExpr } ;BitOrExpr         = BitXorExpr { "|" BitXorExpr } ;BitXorExpr        = BitAndExpr { "^" BitAndExpr } ;BitAndExpr        = EqualityExpr { "&" EqualityExpr } ;EqualityExpr      = RelationalExpr { ( "==" | "!=" | "===" | "!==" ) RelationalExpr } ;RelationalExpr    = RangeExpr { ( "<" | "<=" | ">" | ">=" ) RangeExpr } ;RangeExpr         = ShiftExpr [ ( "..<" | "..." ) [ ShiftExpr ] ]                  | ( "..<" | "..." ) ShiftExpr ;ShiftExpr         = AdditiveExpr { ( "<<" | ">>" ) AdditiveExpr } ;AdditiveExpr      = MultiplicativeExpr { ( "+" | "-" | "&+" | "&-" ) MultiplicativeExpr } ;MultiplicativeExpr= CastExpr { ( "*" | "/" | "%" | "&*" ) CastExpr } ;CastExpr          = UnaryExpr { CastOp Type } ;CastOp            = "as" | "as" "?" | "as" "!" | "unchecked" "as" | "is" ;UnaryExpr         = PrefixOp UnaryExpr | PostfixExpr ;PrefixOp          = "-" | "+" | "!" | "~" | "&" | "^"                  | "await" | "move" ;                    (* prefix '^' counts from the end: '^1', a FromEnd *)TryExpr           = ( "try" | "try" "?" | "try" "!" ) UnaryExpr                    [ "catch" ( Block | Expression ) ] ;                    (* the catch supplies an inline fallback value; '!' is                       try's only with nothing between them: 'try !f()' is                       'try (!f())' *)PostfixExpr       = PrimaryExpr { PostfixOp } ;PostfixOp         = "." MemberName [ GenericArgs ]                  | "?" "." MemberName                  | "!"                  | "(" [ ArgumentList ] ")" [ TrailingClosure ]                  | "?" "(" [ ArgumentList ] ")"                  | "[" ArgumentList "]"                  | "?" "[" ArgumentList "]"                  | TrailingClosure ;MemberName        = Identifier | Keyword ;                    (* any keyword may name a member: 'super.init', 'T.self' *)ArgumentList      = Argument { "," Argument } [ "," ] ;Argument          = [ Identifier ":" ] [ "&" | "out" | "move" ] Expression ;                    (* "&" marks an argument the call may write: required                       for an "inout" or "out" parameter ("out" may be                       written for an "out" one), an error anywhere else                       (S3209). A "T&" parameter takes the argument plainly. *)TrailingClosure   = ClosureExpr { Identifier ":" ClosureExpr } ;PrimaryExpr       = Literal                  | Identifier [ GenericArgs ]                  | "self" | "super" | "Self"                  | "." Identifier [ "(" [ ArgumentList ] ")" ]   (* inferred member *)                  | KeyPathExpr                  | "(" Expression ")"                  | TupleExpr                  | ArrayLiteral                  | DictLiteral                  | RecordLiteral                  | ClosureExpr                  | MatchExpr                  | IfExpr                  | TryExpr                  | "unsafe" Block                  | Type "." "self"                  | CalledType "(" [ ArgumentList ] ")"   (* its initialiser *)                  | "#" Identifier ;                (* compiler builtins: #file, #line *)KeyPathExpr       = "\" [ Identifier [ GenericArgs ] ] "." MemberName { ( "." | "?." ) MemberName } ;   (* \.address.city *)MemberName        = Identifier | IntegerLiteral ;CalledType        = "[" Type ":" Type "]"                   (* [String: Int]()   *)                  | PostfixType "[" ">" ".." [ "<" ] "]" ;  (* Int[>..]()        *)TupleExpr         = "(" [ TupleElem { "," TupleElem } ] ")" ;TupleElem         = [ Identifier ":" ] Expression ;ArrayLiteral      = "[" [ Expression { "," Expression } [ "," ] ] "]" ;DictLiteral       = "[" ":" "]"                  | "[" KeyValue { "," KeyValue } [ "," ] "]" ;KeyValue          = Expression ":" Expression ;RecordLiteral     = QualifiedName "{" [ FieldInit { "," FieldInit } [ "," ] ] "}" ;FieldInit         = Identifier ":" Expression ;                    (* no shorthand: '{ x }' would be a closure returning x *)MatchExpr         = MatchStatement ;      (* usable in expression position *)IfExpr            = IfStatement ;         (* usable in expression position when                                             every branch yields a value *)(* 'async let' is a VariableDecl, not an expression *)ClosureExpr       = [ CaptureList ] ClosureSignature "=>" ( Expression | Block )                  | [ CaptureList ] "{" [ ClosureHeader ] { Statement } "}" ;ClosureSignature  = "(" [ ClosureParams ] ")" [ ClosureThrows ] [ "->" Type ]                  | Identifier ;ClosureParams     = ClosureParam { "," ClosureParam } ;ClosureParam      = Identifier [ ":" [ "inout" ] Type ] ;ClosureHeader     = [ "(" ] ClosureParams [ ")" ] [ ClosureThrows ] [ "->" Type ] "in" ;ClosureThrows     = "throws" [ "(" Type ")" ] ;      (* 'rethrows' parses, and is S3664 *)CaptureList       = "[" CaptureItem { "," CaptureItem } "]" ;CaptureItem       = [ "weak" | "unowned" ] ( "self" | Identifier [ "=" Expression ] ) ;

Literals#

The token definitions these productions refer to are in Lexical Structure.

EBNF
Literal           = NumericLiteral                  | StringLiteral                  | CharLiteral                  | BoolLiteral                  | "none" ;NumericLiteral    = IntegerLiteral | FloatLiteral ;BoolLiteral       = "true" | "false" ;StringLiteral     = SimpleString | MultilineString | RawString ;                    (* interpolation segments \( Expression [ ":" FormatSpec ] )                       are parsed recursively by the lexer/parser pair *)(* A hole's format spec (SYNTAX.md §16) is raw text up to the hole's ')',   read by the binder, not tokens. *)FormatSpec        = [ [ Fill ] Align ] [ "+" | "-" | " " ] [ "#" ] [ "0" ]                    [ Digits ] [ "," | "_" ] [ "." Digits ]                    [ "d" | "x" | "X" | "o" | "b" | "e" | "E" | "f" | "g" | "G" | "%" | "?" ] ;Align             = "<" | "^" | ">" ;Fill              = ? any scalar but '"', "'", "\", "(" and ")" ? ;Digits            = Digit { Digit } ;
Sable

A systems language with value semantics, automatic reference counting, move-checked resources and compile-time checks on how memory is used, compiled ahead of time to native code through LLVM.

Sable is pre-1.0: the language, the standard library and the toolchain work end to end, but expect changes between versions.