37. Grammatica
Questo capitolo è un riassunto in stile BNF della sintassi MALDA accettata dal parser di riferimento (MaldaLang/Parser/Parser.cs, MaldaLang/Lexer.cs). La semantica Tier 0 è definita in Specificazione del linguaggio MALDA 1.0.
api chiuse, async/await, le pipe, le comprehension, i letterali dict/graph/oggetto, i pattern variant e send/spawn/receive. Gli esempi narrativi restano nei capitoli tematici (per esempio Workflow durevoli e Actor). Se grammatica e parser non coincidono, vince il parser fino a un emendamento della spec.
37.1 Programma
Program ::= TopLevelItem*
TopLevelItem::= IncludeStmt | UsingStmt | ImportStmt
| WorkflowDecl | ActorDecl | ClassDecl | PromptDecl | TypeDecl | ComponentDecl
| SchemaDecl | ApiDecl | SuiteDecl | ContextDecl | PolicyDecl
| DecoratedFunctionDecl | DecoratedPropertyDecl | PropertyDecl
| ExportableDecl | Statement
IncludeStmt ::= "include" StringLiteral ";"
UsingStmt ::= "using" (Identifier "=")? QualifiedName ";"
ImportStmt ::= "import" (
"{" Identifier ("," Identifier)* "}" "from" ( StringLiteral | QualifiedName )
| (Identifier "=")? StringLiteral
| (Identifier "=")? QualifiedName
| JsImport
) ";"
JsImport ::= "js" ( Identifier "=" StringLiteral
| "{" Identifier ("," Identifier)* "}" "from" StringLiteral
| "global" Identifier ("," Identifier)*
) /* contextual "js" / "global"; JavaScript backend only */
ExportableDecl ::= "export"? ( FunctionDecl | ClassDecl | TypeDecl | SchemaDecl
| "var" Identifier TypeHint? "=" Expression ";" )
QualifiedName ::= Identifier ("." Identifier)*
function e le dichiarazioni decorate vengono parsate al top level (e dentro i blocchi tramite Declaration()). Non sono forme Statement nidificate valide dentro i blocchi ordinari. fn e def non sono produzioni.
37.2 Dichiarazioni top-level
FunctionDecl ::= "function" Identifier "(" ParamList? ")" ReturnType?
( Block | Expression ";" )
DecoratedFunctionDecl ::= Decorator+ FunctionDecl
ReturnType ::= ("->" | "=>") (Identifier | "program" "(" Identifier ")")
ClassDecl ::= "class" Identifier (
"(" ParamList? ")" ( "{" ClassMember* "}" | ";" | AccessModifier? FunctionDecl )
| ("extends" Identifier)? "{" ClassMember* "}"
| AccessModifier? FunctionDecl
)
/* later ClassDecl with the same Identifier is an augmentation
(same program, include splice, or a later REPL entry);
AccessModifier? FunctionDecl is a single-method / compact form */
ClassMember ::= AccessModifier? (FieldDecl | MethodDecl | ConstructorDecl)
FieldDecl ::= "var" Identifier TypeHint? ("=" Expression)? ";"
MethodDecl ::= AccessModifier? FunctionDecl
ConstructorDecl ::= AccessModifier? FunctionDecl /* name equals class name; forbidden when a primary constructor is present */
TypeDecl ::= "type" Identifier "=" Constructor ("|" Constructor)* ";"
Constructor ::= Identifier ("(" CtorParamList? ")")?
CtorParamList ::= CtorParam ("," CtorParam)* ","?
CtorParam ::= Identifier (":" SchemaType)?
SchemaDecl ::= "schema" Identifier "{" SchemaField* "}"
SchemaField ::= Identifier ":" SchemaType ";"
SchemaType ::= Identifier "[]"? "?"? /* e.g. string, int[], string? */
ApiDecl ::= "api" Identifier "{" ApiMethodSig* "}"
ApiMethodSig ::= "function" Identifier "(" CtorParamList? ")" ";"
/* optional SchemaType per param, same as CtorParam; impl = top-level function of the same name */
ActorDecl ::= Decorator? "actor" Identifier "{" ActorBodyItem* "}"
/* the only actor decorator is @worker(): run the actor off the main thread */
ActorBodyItem ::= MessageDecl | ActorMember
MessageDecl ::= "message" Identifier "(" ParamList? ")" ReturnType? ";"
ActorMember ::= AccessModifier? ( FieldDecl | "on" Identifier "(" ParamList? ")" ReturnType? Block
| MethodDecl | ConstructorDecl )
PromptDecl ::= "prompt" Identifier "(" ParamList? ")" ReturnType? PromptBody
PromptBody ::= Block | ObjectLiteral /* statement body or object-literal config; object fields may end with optional ';' */
PromptBodyField ::= "system" | "user" | "model" | "temperature" | "tools" | "gather" | "maxTokens" | "examples" | "attachments"
/* gather + -> Type = Mode C (tool round, then typed extract). tools: stays Mode B.
attachments: image/pdf parts on await; user/system stay strings. */
ComponentDecl ::= "component" Identifier ComponentParams? Block
ComponentParams ::= "(" ParamList? ")"
PropertyDecl ::= "property" Identifier PropertyParams? Block
DecoratedPropertyDecl ::= Decorator+ PropertyDecl
Decorator ::= "@" Identifier "(" DecoratorArgList? ")"
DecoratorArgList ::= DecoratorArg ("," DecoratorArg)*
DecoratorArg ::= (Identifier ":")? Expression
/* named keys are decorator-only; @budget(tokens: 4000, tools: 8). Call-site ArgList stays positional. */
SuiteDecl ::= "suite" StringLiteral "{" EvalCase* "}"
EvalCase ::= Decorator* "case" StringLiteral Block
ContextDecl ::= "context" Identifier "{" ContextField* "}"
PolicyDecl ::= "policy" "{" PolicyRule* "}"
WorkflowDecl ::= "workflow" Identifier "(" ParamList? ")" "{" WorkflowStmt* "}"
WorkflowStmt ::= StepStmt | ApprovalStmt | WaitStmt | Statement
StepStmt ::= "step" Identifier "=" CallExpr StepOptions? ";"
StepOptions ::= ("retry" Integer | "backoff" String | "delay" Integer
| "maxDelay" Integer | "timeout" Integer | "compensate" CallExpr)*
ApprovalStmt ::= "approval" Identifier "=" "approval"
"(" Expression ("," Expression)? ")" ApprovalOptions? ";"
ApprovalOptions ::= ("timeout" Integer | "onReject" CallExpr)*
WaitStmt ::= "wait" Identifier "=" "awaitSignal"
"(" Expression ("," Expression)? ")" ("timeout" Integer)* ";"
AccessModifier ::= ("public" | "private")? "static"?
TypeHint ::= ":" "out"? Identifier
ParamList ::= Param ("," Param)* ","? /* one trailing "," allowed; a lone "," is an error */
Param ::= Decorator* Identifier TypeHint?
CallExpr ::= Expression PostfixSuffix* /* see §34.4 */
Le dichiarazioni property possono includere decoratori come @requires(...) e @targets(...) per gli hint di capability dei backend.
37.3 Istruzioni
Statement ::= VarDecl | DestructuringVarDecl
| Assignment | DestructuringAssignment
| IfStmt | WhileStmt | ForStmt | ForAwaitStmt | ForeachStmt
| WithinStmt
| ReturnStmt | PrintStmt | BreakStmt | ContinueStmt
| TryStmt | ThrowStmt | SendStmt
| DeferStmt | UsingResourceStmt
| MatchStmt | ExpressionStmt | Block
VarDecl ::= ("var" | "const") Identifier TypeHint? "=" Expression ";"
DestructuringVarDecl ::= "var" DestructuringPattern TypeHint? "=" Expression ";"
Assignment ::= LValue AssignOp Expression ";"
AssignOp ::= "=" | "+=" | "-=" | "*=" | "/="
LValue ::= Identifier | MemberAccess | ArrayAccess
DestructuringAssignment ::= DestructuringPattern "=" Expression ";"
IfStmt ::= "if" "(" Expression ")" Statement ("else" Statement)?
WhileStmt ::= "while" "(" Expression ")" Statement
ForStmt ::= "for" "(" (VarDecl | Assignment)? ";" Expression? ";" Assignment? ")" Statement
ForAwaitStmt::= "for" "await" "(" "var" Identifier "in" Expression ")" Statement
ForeachStmt ::= "foreach" "(" "var" Identifier "in" Expression ")" Statement
| "for" "(" "var" Identifier "in" Expression ")" Statement
WithinStmt ::= "within" "(" Integer ("ms" | "s" | "m") ")"
("budget" "(" NamedArg ("," NamedArg)* ")")? Block
ReturnStmt ::= "return" Expression? ";"
PrintStmt ::= "print" "(" Expression ")" ";"
BreakStmt ::= "break" ";"
ContinueStmt::= "continue" ";"
TryStmt ::= "try" Block CatchClause+ FinallyClause?
| "try" Block FinallyClause
CatchClause ::= "catch" ("(" Identifier ("if" Expression)? ")")? Block
FinallyClause ::= "finally" Block
ThrowStmt ::= "throw" Expression ";"
SendStmt ::= "send" SendTarget SendOptions? ";"
SendTarget ::= Expression /* send target.handler(args) or send target(args) */
SendOptions ::= "then" "(" Identifier ")" Block
| "timeout" Expression ("catch" "(" Identifier ")" Block)?
DeferStmt ::= "defer" Block
UsingResourceStmt ::= "using" Identifier "=" Expression Block
MatchStmt ::= "match" Expression "{" MatchCase* DefaultCase? "}" (";")?
MatchCase ::= "case" Pattern ("if" Expression)? ":" Statement (";")?
DefaultCase ::= "default" ":" Statement (";")?
ExpressionStmt ::= Expression ";"
Block ::= "{" (TopLevelItem | Statement)* "}"
Un'espressione match { ... } nuda può comparire come istruzione senza punto e virgola dopo }.
37.4 Espressioni (precedenza)
Dalla più bassa alla più alta: assegnamento, pipe |>, ternario ? :, coalescenza null ??, espressione match, or/||, and/&&, uguaglianza, confronto, additivo, moltiplicativo, unario (await, async, not/!, -, ++/--), postfisso ((), [], ., ?., ?[], ++/--). La tabella completa è in Appendice B.
Expression ::= AssignExpr
AssignExpr ::= Pipe (AssignOp Expression)?
Pipe ::= Ternary ("|>" Ternary)*
Ternary ::= MatchExpr ("?" Expression ":" Expression)?
MatchExpr ::= "match" Expression "{" MatchCase* DefaultCase? "}"
| LogicalOr
LogicalOr ::= LogicalAnd (("or" | "||") LogicalAnd)*
LogicalAnd ::= Equality (("and" | "&&") Equality)*
Equality ::= Comparison (("==" | "!=") Comparison)*
Comparison ::= Additive (("<" | "<=" | ">" | ">=") Additive)*
Additive ::= Multiplicative (("+" | "-") Multiplicative)*
Multiplicative ::= Unary (("*" | "/" | "%") Unary)*
Unary ::= "await" Unary | "async" Unary
| ("not" | "!" | "-" | "++" | "--") Unary
| Postfix
Postfix ::= Primary PostfixSuffix*
PostfixSuffix ::= "(" ArgList? ")" | "[" Expression "]" | "." Identifier
| "?." Identifier | "?[" Expression "]" /* null-conditional */
| "++" | "--"
Primary ::= Literal | Identifier | "(" Expression ")"
| "this" | "super" | "self" | "null"
| "new" QualifiedName "(" ArgList? ")"
| "spawn" Identifier "(" ArgList? ")"
| "receive" "(" ")"
| ArrayLiteral | DictLiteral | GraphLiteral | ObjectLiteral
| InterpolatedString | LambdaExpr | FunctionExpr
LambdaExpr ::= LambdaParams Arrow (Expression | Block)
LambdaParams::= "(" ParamList? ")" | Identifier
Arrow ::= "=>" | "->" /* same Arrow token in lexer */
FunctionExpr ::= "function" "(" ParamList? ")" Block
/* anonymous function: same value as "(" ParamList? ")" "=>" Block */
/* Array, dict, graph and object literals, ArgList and ParamList allow one trailing ","
before the closing bracket; a lone "," is an error. */
ArrayLiteral ::= "[" (Expression ("," Expression)* ","?)? "]"
| ListComprehension
ListComprehension ::= "[" Expression "for" Identifier "in" Expression
("if" Expression)? "]"
DictLiteral ::= "dict" "{" (Expression ":" Expression ("," Expression ":" Expression)* ","?)? "}"
| DictComprehension
DictComprehension ::= "dict" "{" Expression ":" Expression "for" Identifier "in" Expression
("if" Expression)? "}"
GraphLiteral ::= "graph" ("directed" | "undirected") "{"
("nodes" ":" Expression ("," "edges" ":" Expression)?)
("edges" ":" Expression ("," "nodes" ":" Expression)?)? ","?
"}"
ObjectLiteral ::= "{" (ObjectEntry ("," ObjectEntry)* ","?)? "}"
ObjectEntry ::= (StringLiteral | Identifier) ":" Expression
InterpolatedString ::= '$"' … '"' | '$"""' … '"""'
37.5 Pattern
Pattern ::= LiteralPattern | IdentifierPattern | WildcardPattern
| VariantPattern | ArrayPattern | ObjectPattern
LiteralPattern ::= Integer | Float | StringLiteral | Boolean | "null"
IdentifierPattern ::= Identifier
WildcardPattern ::= "_"
VariantPattern ::= Identifier "(" (Pattern ("," Pattern)*)? ")"
/* Bare Identifier that names a declared constructor is also a
VariantPattern with implicit '_' payloads of that arity. */
ArrayPattern ::= "[" (Pattern ("," Pattern)*)? RestPattern? "]"
RestPattern ::= "..." Identifier?
ObjectPattern ::= "{" ObjectPatternEntry ("," ObjectPatternEntry)* "}"
ObjectPatternEntry ::= (Identifier | StringLiteral) (":" Pattern)?
DestructuringPattern ::= ArrayPattern | ObjectPattern
37.6 Lessico e token
Keyword, operatori, commenti, stringhe e letterali numerici sono definiti in Struttura lessicale. fn e def non sono keyword. Sia => sia -> producono lo stesso token Arrow (corpi delle lambda e tipi di ritorno).
Identifier ::= [A-Za-z_][A-Za-z0-9_]*
ArgList ::= Expression ("," Expression)* ","?
Vedi anche
- Struttura lessicale — token e keyword
- Appendice — tabella di precedenza degli operatori
- Language spec 1.0 — semantica Tier 0
- Workflow durevoli — esempi di workflow
- Actor — esempi di messaging tra actor