Documentation
¶
Overview ¶
Package syntax contains bork's lexer, syntax tree, and parser.
Index ¶
- func Keywords() []string
- func Lex(file string, src []byte, diags *diag.List) ([]Token, []Comment)
- func LexCompiler(file string, src []byte, diags *diag.List) ([]Token, []Comment)
- type AmbientDecl
- type Argument
- type Arm
- type Binary
- type Binding
- type Block
- type BoolLit
- type Bundle
- type Call
- type ClassDecl
- type Comment
- type Comptime
- type ContextName
- type Copy
- type CopyUpdate
- type Effect
- type Expr
- type ExprStmt
- type FieldDecl
- type FieldInit
- type FieldPat
- type File
- type FloatLit
- type For
- type FuncDecl
- type FuncTypeExpr
- type Generate
- type GoBind
- type GoCode
- type GoTag
- type Ident
- type If
- type Import
- type InstanceDecl
- type IntLit
- type Interp
- type Kind
- type Lambda
- type ListLit
- type ListPat
- type LitPat
- type LoopControl
- type MapLit
- type Match
- type MockStmt
- type Need
- type Needs
- type Param
- type Pattern
- type PredRef
- type Propagated
- type ProviderBundle
- type ProviderEntry
- type RecordLit
- type Return
- type RuleDecl
- type RuneLit
- type ScopeExpr
- type Selector
- type StaticPartsLit
- type Stmt
- type StringLit
- type TestDecl
- type Token
- type TrustStmt
- type Try
- type TypeDecl
- type TypeExpr
- type TypeHead
- type TypeKind
- type TypeParam
- type TypePat
- type Unary
- type Use
- type Uses
- type VariantDecl
- type VariantPat
- type WildcardPat
- type WithBinding
- type WithExpr
- type Yield
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Keywords ¶ added in v0.0.4
func Keywords() []string
Keywords returns the reserved words recognized by the lexer.
Types ¶
type AmbientDecl ¶
type AmbientDecl struct {
Pos diag.Pos
Name string
Type *TypeExpr
// Logged is the position of the logged marker, if present.
Logged *diag.Pos
// Propagated is the propagated marker, if present.
Propagated *Propagated
}
AmbientDecl declares an ambient value: `ambient traceId: String`, optionally marked `logged` (its value is added to every log line written while a with binds it) or `propagated("header")` (sent across process boundaries under that name).
type Argument ¶
type Argument struct {
Name string
Pos, NameEnd, End diag.Pos
ValueStart diag.Pos
// RemovalStart includes the preceding comma, when no comment would
// be removed with it. Zero for the first argument or commented spans.
RemovalStart diag.Pos
}
Argument describes a call argument as written; Name is empty for a positional argument. End is after its expression, NameEnd after its label.
type Binding ¶
type Binding struct {
// Package values use process-lifetime memo cells, including without lazy.
Package bool
AsyncScope Expr
AsyncPos diag.Pos
Lazy bool
LazyPos diag.Pos
Pos diag.Pos
Name string
Type *TypeExpr // nil if not written
Value Expr
}
Binding is `name = value`, or `name: Type = value`. Bindings are immutable.
type Block ¶
type Block struct {
Pos diag.Pos
Stmts []Stmt
Tail Expr
End diag.Pos // position of the closing '}'
}
Block is `{ stmts; tail }`. Tail is the block's value; nil means the block's value is Ok (or Never, if it ends by returning).
type Bundle ¶
type Bundle struct {
Pos diag.Pos
Name string
Items []*Use // instances, bundles, and pkg.* of imported packages
}
Bundle names a set of instances, which `use` brings into scope at once: `instances Json { ItemDecode, ItemEncode, money.* }`. A package suggests instances to its importers with one.
type Call ¶
type Call struct {
Start diag.Pos // start of the callee, including grouping parentheses
Pos diag.Pos // position of '('
End diag.Pos // position after the closing ')'
Fun Expr
FunEnd diag.Pos // position after the callee, before type arguments
Args []Expr
// Arguments retains labels and source ranges, parallel to Args. A
// synthesized pipeline input has no label.
Arguments []Argument
// TypeArgs are explicit type arguments: `empty[Int]()`.
TypeArgs []*TypeExpr
// Pipe retains the source of a desugared pipeline for diagnostics.
Pipe diag.Pos
PipeStart, PipeEnd diag.Pos // range of the receiver expression
PipeTargetEnd diag.Pos // end of the original pipeline target
PipeWrap bool // receiver needs parentheses before a selector
PipeBare bool // target was written without call parentheses
}
type ClassDecl ¶
ClassDecl is a type class: `class Show[T] { fn show(x: T): String }`. Its methods are signatures, without bodies.
type Comment ¶
type Comment struct {
Text string
Pos diag.Pos
End diag.Pos // position immediately after the token
}
Comment is a source comment, kept for future tooling (formatter, editor support). The parser does not use comments.
type ContextName ¶
ContextName omits a constructor's owner: .{ ... } or .Variant. Name is empty for a record, and End is after the dot or variant name.
func (*ContextName) Position ¶
func (e *ContextName) Position() diag.Pos
type Copy ¶
type Copy struct {
Pos diag.Pos // position of 'copy'
X Expr
Updates []*CopyUpdate
}
Copy is `x.copy(age: 37, address.city: "Oslo")`: a new record equal to x except for the given (possibly nested) fields.
type CopyUpdate ¶
type Expr ¶
Expr is an expression. Everything that produces a value is an expression, including if, blocks, and return.
type FieldPat ¶
type FieldPat struct {
Pos diag.Pos
Field string
Pattern Pattern // nil for the `{ radius }` shorthand
}
FieldPat is one field of a destructuring pattern: `{ radius }` binds the field to its own name, and `{ radius: p }` matches it against the pattern p (a name to bind, a literal, a nested pattern, ...).
type File ¶
type File struct {
// Script marks a single executable file with an implicit main.
Script bool
Path string
// Source retains the original text for compile-time debug probes.
Source string
// Package is the import path of the file's package (set by the
// driver), and Imports what the file imports.
Package string
Imports []*Import
Uses []*Use
Bundles []*Bundle
Providers []*ProviderBundle
Rules []*RuleDecl
// Classes and Instances; the instances' methods are also in Funcs.
Classes []*ClassDecl
Instances []*InstanceDecl
// Prelude is set for the compiler's built-in prelude.
Prelude bool
Types []*TypeDecl
Ambients []*AmbientDecl
Funcs []*FuncDecl
// Bindings contains immutable package values.
Bindings []*Binding
Tests []*TestDecl
Comments []Comment
}
File is one parsed .bork source file.
func Parse ¶
Parse parses one source file. Syntax errors are added to diags; the returned file holds whatever could be parsed.
func ParseEmbedded ¶
ParseEmbedded reuses the immutable tokens of embedded prelude/standard sources. Every call builds a fresh syntax tree: the checker expands calls in that tree. User files use Parse, so edits do not grow this bounded compiler-source cache.
func ParseFiles ¶
ParseFiles parses independent sources concurrently when there is enough work to amortize worker setup. Files and diagnostics retain the input order.
type FuncDecl ¶
type FuncDecl struct {
// ScriptMain is the synthetic entrypoint of a script.
ScriptMain bool
// Constructor names the owning record in `fn New = Config.new`.
Constructor *TypeExpr
Pos diag.Pos
Name string
// IsPred is set for `pred name(x: T, ...) { ... }`: a function
// returning Bool that can be used in `where` clauses.
IsPred bool
// TypeParams lists the type parameters of a generic function:
// `fn map[A, B](...)`.
TypeParams []*TypeParam
Params []*Param
// ParamsEnd is the position of the ')' that ends the parameters.
ParamsEnd diag.Pos
// Requires relates function inputs; result constraints remain on Result.
Requires Expr
// Uses lists the effects the function may have, `uses io + net`,
// or is nil when it declares none.
Uses *Uses
// Needs lists the ambient values it reads, `needs traceId +
// locale?`, or is nil when it reads none.
Needs *Needs
Result *TypeExpr
Body *Block
GoBody *GoCode
// GoBind is set instead of a body for a binding to a Go function:
// `fn Getenv(key: String): String unsafe go "os.Getenv"`.
GoBind *GoBind
// Instance is set for a method of an instance declaration.
Instance *InstanceDecl
// IsMethod is set for a method, `fn (xs: List[T]) first[T](): T`:
// its receiver is its first parameter.
IsMethod bool
}
FuncDecl is `fn name(params): Result { body }`. Result is nil when the function returns Ok. A function implemented in Go has GoBody instead of Body.
type FuncTypeExpr ¶
FuncTypeExpr is a function type: `(A, B) => C`, or with effects, `(A) uses io => C`.
type GoBind ¶
GoBind names the Go function a binding calls, with its import path: "os.Getenv", "crypto/sha256.Sum256".
type GoCode ¶
type GoCode struct {
Pos diag.Pos // position of '{'
Imports []string
// ImportAliases contains explicit aliases by path.
ImportAliases map[string]string
// Body is the text between the braces, with the import lines
// blanked out, so its lines still match the source.
Body string
}
GoCode is the body of `unsafe go { ... }`: Go statements, preceded by optional `import [alias] "path"` lines.
type Import ¶
Import is `import "example.com/shop/money"` or, with a name to use instead of the path's last element, `import cash "example.com/shop/money"`.
The parser reads a use of an imported name, `money.add` or `money.Amount`, as one qualified name: an Ident (or type, predicate, or pattern name) "money.add".
type InstanceDecl ¶
type InstanceDecl struct {
Pos diag.Pos
Name string
TypeParams []*TypeParam
Class string // possibly qualified: fmt.Show
ClassPos diag.Pos
Type *TypeExpr
Methods []*FuncDecl
}
InstanceDecl is a named instance of a class for a type: `instance showInt: Show[Int] { fn show(x: Int): String { ... } }`, or generic: `instance showList[T: Show]: Show[List[T]] { ... }`.
type Interp ¶
type Interp struct {
Prefix Expr // nil for the built-in s prefix
PrefixEnd diag.Pos // opening quote position for a named prefix
Pos diag.Pos
Parts []string
Exprs []Expr
}
Interp is an interpolated string: s"Hello $name, ${age + 1}". Parts holds the (unquoted) text around the expressions, so it has one more element than Exprs.
type Kind ¶
type Kind int
Kind is the kind of a token.
const ( EOF Kind = iota Illegal Semi // explicit ';' or a newline that ends a statement TIdent TInt TFloat TRune TString TInterp // s"...": the text from the opening quote to the closing one TGoCode // the raw Go inside `unsafe go { ... }` // Keywords KwFn KwIf KwElse KwReturn KwTrue KwFalse KwType KwSealed KwMatch KwUnsafe KwPred KwWhere KwAnd KwTrust KwRule KwOr KwGenerate KwYield KwFor KwBreak KwContinue // Delimiters LParen RParen LBrace RBrace LBrack RBrack Comma Colon Dot Ellipsis // ... in a list pattern Underscore // the wildcard pattern _ // Operators Assign // = Plus // + Minus // - Star // * Slash // / Pct // % Not // ! AndAnd // && OrOr // || Eq // == NotEq // != Lt // < LtEq // <= Gt // > GtEq // >= Pipe // | PipeGt // |> Arrow // => Quest // ? )
type Lambda ¶
Lambda is a function value: `x => x + 1`, `(a, b) => a + b`, or `(x: Int) => { ... }`.
type ListPat ¶
type ListPat struct {
Pos diag.Pos
Elems []Pattern
HasRest bool
Rest string // "" when ignored
RestPos diag.Pos
}
VariantPat is a name pattern: a variant (`Shape.Circle { radius }`, `Option.None`), a type (`NotFound`), a record destructure (`User { name }`), or, for a single name that is not a type, a binding of the whole value (`n`). ListPat matches a list: `[]`, `[a, b]`, or `[first, ...rest]` (Rest binds the remaining elements; `[first, ...]` ignores them).
type LoopControl ¶
func (*LoopControl) Position ¶
func (e *LoopControl) Position() diag.Pos
type Match ¶
type Match struct {
Pos diag.Pos
Close diag.Pos // the closing brace, before which new arms can be inserted
TrailingSeparator bool // the final arm already has a comma or newline
X Expr
Arms []*Arm
}
Match is `match (x) { pattern => value, ... }`.
type MockStmt ¶
type MockStmt struct {
Pos diag.Pos // the binding's name, or 'mock'
Name string // the handle's name, or ""
MockPos diag.Pos // 'mock'
Target Expr
Params []*Param
// ParamsStart and ParamsEnd are the positions of the '(' and ')'
// around the parameters.
ParamsStart, ParamsEnd diag.Pos
// Requires relates function inputs; result constraints remain on Result.
Requires Expr
Body *Block
}
MockStmt is `mock target(a, b) { ... }`, or `m = mock target(...) { ... }` with a handle m that records the calls: in a test, it replaces the function target until the end of the enclosing block. Target is an *Ident (`fetch`, `payments.Charge`) or a *Selector naming a method (`Store.save`, `model.Point.Value`). Params holds the parameters' names only (no types); `_` ignores one.
type Need ¶
Need is one ambient value named in a `needs` declaration; Optional is set for `locale?`, which is read as an Option.
type Needs ¶
Needs is a declaration of the ambient values a function reads: `needs traceId + locale?`.
type Param ¶
type Param struct {
Pos diag.Pos
Name string
Type *TypeExpr
// Default is the value of a function parameter that a call may
// leave out (`attrs: Map[String, Int] = {:}`), or nil.
Default Expr
// In names the parameter (a Scope or an OwnedScope) whose scope this
// one belongs to, in `conn: Conn in prev`; "" if none.
In string
InPos diag.Pos
}
Param is a function's or a lambda's parameter. A lambda's parameter may leave out its type (Type is nil).
type PredRef ¶
PredRef is one predicate in a where clause: `positive`, or `between(1, 65535)`, whose arguments are constants or parameter names. The constrained value itself is the predicate's first argument and is not written. A clause with alternatives, `p or q`, has the first in Name and Args and the rest in Or.
type Propagated ¶
Propagated is the `propagated("traceparent")` marker of an ambient declaration: the name of the header (or message metadata) that carries the value.
type ProviderBundle ¶
ProviderBundle is a compile-time named provider list.
type RecordLit ¶
type RecordLit struct {
Type Expr // *Ident, *TypeHead, *Selector or *ContextName
Fields []*FieldInit
End diag.Pos
}
RecordLit is `User { name: "Ada", age: 36 }` or `Shape.Circle { radius: 3 }`.
type RuleDecl ¶
type RuleDecl struct {
Pos diag.Pos
Name string
Params []*Param
Premises []Expr
Conclusions []Expr
}
RuleDecl is an inference rule:
rule weaken(x: Int, a: Int, b: Int) {
atLeast(x, a) and a >= b => atLeast(x, b)
}
Premises are predicate calls (facts to find) or other Bool expressions (conditions, computed when their variables are constants). Conclusions are predicate calls.
type ScopeExpr ¶
type ScopeExpr struct {
Pos diag.Pos
Name string
// Policies are those of `scope s with taskTimeout(100),
// cleanupTimeout(500) { ... }`; none for the defaults.
Policies []Expr
Body *Block
}
ScopeExpr is `scope s { ... }`: a block with a scope named s, which closes (running its finalizers) when the block ends.
type StaticPartsLit ¶
StaticPartsLit is created only by the checker for a named interpolation. It has no source syntax: runtime Strings cannot acquire literal provenance.
func (*StaticPartsLit) Position ¶
func (e *StaticPartsLit) Position() diag.Pos
type Stmt ¶
type Stmt interface {
// contains filtered or unexported methods
}
Stmt is a statement inside a block.
type TestDecl ¶
TestDecl is a test: `test "adds numbers" { assert(add(1, 2) == 3) }`. Tests run with `bork test`, and are left out of programs. A test with parameters is a property test, run on generated values of them: `test "doubles" (n: Int where small) { assert(double(n) > n) }`.
type Token ¶
type Token struct {
Kind Kind
Text string
Pos diag.Pos
End diag.Pos // position immediately after the token
}
Token is a lexed token. Text holds the source text for identifiers and literals.
type TrustStmt ¶
TrustStmt is `trust p(x, ...)`: from here on, p(x, ...) is taken as a fact without proof.
type Try ¶
Try is `x?`: keep the leftmost member of x's type, and return every other member from the enclosing function.
type TypeDecl ¶
type TypeDecl struct {
Pos diag.Pos
Name string
// TypeParams lists a generic type's parameters: `type Pair[A, B]`.
TypeParams []*TypeParam
GoName *GoBind
Kind TypeKind
Private bool // record construction belongs to its package
Fields []*FieldDecl // RecordType
Variants []*VariantDecl // SealedType
Alias *TypeExpr // AliasType
Where []*PredRef // whole-value invariants on records and sealed types
// Derive lists the classes to derive instances of:
// `type User = { ... } derive (Decode, Encode)`.
Derive []string
DerivePos diag.Pos
}
TypeDecl is `type Name = ...`.
type TypeExpr ¶
type TypeExpr struct {
Uses *Uses // latent effects on Seq[T]
Pos diag.Pos
Name string
Args []*TypeExpr
Union []*TypeExpr // non-nil for a union; Name and Args are then unused
// Func is set for a function type `(A, B) => C`; Name and Args are
// then unused.
Func *FuncTypeExpr
// Where lists the clauses of `T where p and (q(1) or r)`, all of
// which must hold.
Where []*PredRef
}
TypeExpr is a written type: a name with optional type arguments (`Option[Int]`), or a union of types (`User | NotFound`).
type TypeParam ¶
type TypeParam struct {
Pos diag.Pos
Name string
// Bounds lists the classes the type must have instances of:
// `T: Show + Eq`.
Bounds []string
}
TypeParam is a declared type parameter.
type Use ¶
Use brings instances of another package into scope: `use money.showAmount`, or every exported one: `use money.*`.
type Uses ¶
type Uses struct {
Pos diag.Pos
End diag.Pos // just after the last effect (or nothing)
Effects []Effect
}
Uses is a declaration of effects: `uses io + net`, or `uses nothing` (Effects is then empty).
type VariantDecl ¶
type VariantPat ¶
type VariantPat struct {
Pos diag.Pos
Path []string
Fields []*FieldPat
Braces bool // written with { ... }, possibly empty
}
func (*VariantPat) Position ¶
func (p *VariantPat) Position() diag.Pos
type WildcardPat ¶
WildcardPat is `_`.
func (*WildcardPat) Position ¶
func (p *WildcardPat) Position() diag.Pos
type WithBinding ¶
WithBinding is one `name: value` of a with.