check

package
v0.0.55 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package check type-checks a parsed bork package.

Index

Constants

View Source
const (
	ComptimeValuePolicyVersion = 1
	ComptimeResultLimit        = 16 << 20
	ComptimeNodeLimit          = 1000000
	ComptimeDepthLimit         = 256
)

ComptimeValuePolicyVersion versions the transport limits independently of the value schema. Future cache keys must include both versions.

View Source
const ComptimeSchemaVersion = 2
View Source
const ExecutionAuditVersion = 1
View Source
const ExecutionIntrinsicVersion = 1

Variables

NumericTypes lists every numeric type, each once.

Functions

func AlwaysFits

func AlwaysFits(from, to Type) bool

AlwaysFits reports whether every value of the numeric type from fits the numeric type to.

func Assignable

func Assignable(src, dst Type) bool

Assignable reports whether a value of type src can be used as a dst.

func BakePackageComptime

func BakePackageComptime(binding *PackageBinding, node *Comptime)

BakePackageComptime retains the runtime memo cell, but its recipe now returns decoded data instead of recomputing an initializer that comptime already used.

func CheckEffects

func CheckEffects(files []*syntax.File, info *Info, diags *diag.List)

CheckEffects checks every function body against the effects its signature declares (see "Effects in signatures" in docs/requirements.md): a function that declares nothing does nothing outside its arguments and result. main and tests may use every runtime effect, unless main declares some. It reads the typed tree, so it runs once the program type-checks.

func ComptimePackageResult

func ComptimePackageResult(binding *PackageBinding, node *Comptime, info *Info, diags *diag.List, eval Evaluator)

Check an annotation before a dependent recipe can use the package promise.

func ComptimeProof

func ComptimeProof(functions []*Func, info *Info, diags *diag.List, eval Evaluator)

ComptimeProof checks predicate implementations and their helpers before a compile-time proof executes them. Their own declared parameter contracts are available, independently of the calling recipe's runtime context.

func ComptimeQuery

func ComptimeQuery(q Query, info *Info, diags *diag.List, eval Evaluator)

ComptimeQuery validates the actual arguments of a proof invocation before batching downstream predicates. A predicate's own contract is a prerequisite even when the query was produced by a function-level where clause.

func ComptimeQueryKey

func ComptimeQueryKey(q Query) string

ComptimeQueryKey identifies active proof invocations by semantic arguments, rather than request-local expression addresses, for recursive proof detection.

func ComptimeRecipe

func ComptimeRecipe(node *Comptime, info *Info, diags *diag.List, eval Evaluator, helpers []*Func)

ComptimeRecipe checks internal obligations without inheriting runtime guards, parameter facts or contextual constraints on the eventual computed result.

func ComptimeResult

func ComptimeResult(node *Comptime, info *Info, diags *diag.List, eval Evaluator)

ComptimeResult validates nominal and field constraints on decoded data before dependent recipes can assume them. Contextual result constraints are checked by the enclosing facts pass, without executing the recipe again.

func DebugWarnings

func DebugWarnings(info *Info) *diag.List

DebugWarnings reports development markers without making checking fail.

func DescribeFacts

func DescribeFacts(info *Info, fn *Func, x Expr, site diag.Pos, where string, eval Evaluator) ([]KnownFact, *Proof, error)

DescribeFacts uses the same backward proofs as compilation. It deliberately enumerates only declared/guarded facts: there is no finite list of all predicates and arguments that could be proven about a value.

func EditorActiveParameter added in v0.0.18

func EditorActiveParameter(callable *CallableDescription, previous []syntax.Argument, currentName string) *int

EditorActiveParameter uses the same positional/named assignment as checking. A new argument after named ones selects the first parameter not supplied.

func EditorContextVariantUnique added in v0.0.38

func EditorContextVariantUnique(t Type, name string) bool

EditorContextVariantUnique applies context selection to a checked scrutinee. Invisible variants still count toward ambiguity, as they do in the checker.

func EditorVisibleTypes added in v0.0.4

func EditorVisibleTypes(info *Info, from *Package) map[string]Type

EditorVisibleTypes includes only names available without a package qualifier.

func Exported

func Exported(name string) bool

Exported reports whether a name is visible to other packages: it starts with an upper-case letter, as in Go.

func Facts

func Facts(files []*syntax.File, info *Info, diags *diag.List, eval Evaluator)

Facts checks the where clauses of a type-checked package.

func GoTypeOf

func GoTypeOf(t Type) types.Type

GoTypeOf is the underlying Go type of an opaque value or Go resource.

func Identical

func Identical(a, b Type) bool

Identical is identical for other packages.

func IntRange

func IntRange(t Type) (lo, hi constant.Value)

IntRange is the smallest and the largest value of the integer type t.

func InterpolationDiagnostics

func InterpolationDiagnostics(batch *InterpolationBatch, diags *diag.List)

InterpolationDiagnostics maps metadata-only results back to original holes.

func IsEq

func IsEq(class *Class) bool

IsEq reports whether class is the prelude's Eq, which every type whose values can be compared has, built in.

func IsFloat

func IsFloat(t Type) bool

IsFloat reports whether t is Float32 or Float.

func IsGoStruct

func IsGoStruct(cl *Class) bool

func IsInteger

func IsInteger(t Type) bool

IsInteger reports whether t is a signed or unsigned integer type.

func IsNumeric

func IsNumeric(t Type) bool

IsNumeric reports whether t is one of the number types.

func IsOption

func IsOption(t Type) bool

IsOption reports whether t is an Option[T] (the prelude's).

func IsShow

func IsShow(class *Class) bool

IsShow identifies the coherent prelude renderer; user-defined classes named Show retain the ordinary instance rules.

func LazyWarnings

func LazyWarnings(info *Info) *diag.List

LazyWarnings only reports a narrow, unconditional next-statement read. Complex initializers are excluded because removing their function boundary could change return/? behavior.

func Lifetimes

func Lifetimes(files []*syntax.File, info *Info, diags *diag.List)

Lifetimes checks that values never outlive the scopes they belong to.

A resource belongs to the scope it was opened in: a function that takes a scope returns values that live as long as it. So do values that hold such a value, such as a record with a resource field, or a lambda that uses one. A value's lifetime is the set of scopes that must all be open for it to be usable. The scopes are `scope s { ... }` blocks, and parameters: whatever a function is given lives as long as the call, at least.

The checks:

  • a value whose scope has ended is "possibly released", and may not be used;
  • a function (or lambda) may not return a value of a scope it opened;
  • an `unsafe go` function that takes a scope may keep its other arguments until that scope closes, so they must live as long as it;
  • a value stored in a channel or an atom must live as long as it.

bork values are immutable. Package lazy initializers cannot retain scoped values; channels and atoms keep only values that live as long as they do (see call). These checks cover the ways a value can escape its scope.

func LintWarnings added in v0.0.3

func LintWarnings(files []*syntax.File, info *Info) *diag.List

LintWarnings reads compiler identities and effect/proof results. It never changes type checking, inferred contracts, or the generated program.

func MentionsTypeParams

func MentionsTypeParams(t Type, tps []*TypeParam) bool

MentionsTypeParams reports whether t mentions one of tps.

func MigrationWarnings

func MigrationWarnings(info *Info) *diag.List

MigrationWarnings reports deprecated type spellings with precise edits.

func Reaches

func Reaches(from, to *Func) bool

Reaches reports whether calling from may call to (or is it), by the functions each calls.

func Rebinding added in v0.0.49

func Rebinding(info *Info, definition diag.Pos) *diag.Pos

Rebinding reports the declaration replaced by the binding at definition.

func TypeText

func TypeText(t Type, from *Package) string

TypeText renders t as code in package from would write it: the types of other packages qualified (money.Cents). With from nil, no names are qualified.

func WalkComptime

func WalkComptime(x Expr, visit func(Expr) bool)

WalkComptime visits typed recipe children, without following declaration references or expanding closed captures. Returning false skips a subtree.

Types

type APIDeclaration added in v0.0.13

type APIDeclaration struct {
	Kind, Name, Receiver, Signature, Documentation string
	Position                                       diag.Pos
}

type Ambient

type Ambient struct {
	Decl *syntax.AmbientDecl
	Name string
	Pkg  *Package
	Type Type
	// Constraints are the facts of its type (`ambient id: String where
	// nonEmpty`): a with must prove them, and a function that needs the
	// value knows them.
	Constraints []*Constraint
	// Logged and Header are its markers: with also publishes a marked
	// value in the goroutine's labels, for log lines (logged) and for
	// the header Header of outgoing calls (propagated).
	Logged bool
	Header string
}

Ambient is a declared ambient value.

func (*Ambient) Marked

func (a *Ambient) Marked() bool

Marked reports whether with publishes the ambient's values in the goroutine's labels.

func (*Ambient) QualifiedName

func (a *Ambient) QualifiedName(from *Package) string

QualifiedName is the ambient's name as code in package from refers to it.

type ArgumentLabel

type ArgumentLabel struct {
	Name  string
	Pos   diag.Pos
	Param int
}

ArgumentLabel identifies the parameter selected by a source argument label.

type Assembly

type Assembly struct {
	Mode      string             `json:"mode"`
	Target    string             `json:"target"`
	Result    string             `json:"result"`
	Effects   string             `json:"effects"`
	Tree      string             `json:"tree"`
	Providers []AssemblyProvider `json:"providers"`
	Roots     []AssemblyRoot     `json:"roots"`
	Order     []int              `json:"order"`
}

Assembly describes the graph resolved at one call site.

type AssemblyDependency

type AssemblyDependency struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	Provider int    `json:"provider,omitempty"`
	Scope    bool   `json:"scope,omitempty"`
}

type AssemblyProvider

type AssemblyProvider struct {
	Bundle        string               `json:"bundle,omitempty"`
	Entry         string               `json:"entry,omitempty"`
	EntryPosition *diag.Pos            `json:"entry_position,omitempty"`
	ID            int                  `json:"id"`
	Label         string               `json:"label"`
	Position      diag.Pos             `json:"position"`
	Product       string               `json:"product"`
	Dependencies  []AssemblyDependency `json:"dependencies"`
}

type AssemblyRoot

type AssemblyRoot struct {
	Name     string `json:"name,omitempty"`
	Type     string `json:"type"`
	Provider int    `json:"provider"`
}

type AsyncDescription

type AsyncDescription struct {
	Scope    string   `json:"scope"`
	Effects  string   `json:"initializer_effects"`
	Captures []string `json:"captures,omitempty"`
}

LazyDescription reports initializer metadata without evaluating a cell.

type Basic

type Basic struct {
	// contains filtered or unexported fields
}

Basic is a built-in type.

func (*Basic) String

func (b *Basic) String() string

type Binary

type Binary struct {
	Op   syntax.Kind
	X, Y Expr
	// contains filtered or unexported fields
}

Binary is `x op y`.

func (*Binary) Pos

func (e *Binary) Pos() diag.Pos

func (*Binary) TokenPos

func (e *Binary) TokenPos() diag.Pos

func (*Binary) Type

func (e *Binary) Type() Type

type Block

type Block struct {
	Assembly   *Assembly
	Conversion *SourceSpan
	Stmts      []Stmt
	Tail       Expr
	End        diag.Pos // the closing '}'
	// Labels are the bindings of a with's logged or propagated values,
	// which the block publishes in the goroutine's labels once its
	// statements (the with's bindings) have run, until it ends.
	Labels []*Var
	// contains filtered or unexported fields
}

Block is `{ stmts; tail }`. Tail is nil when the block's value is Ok (or it never finishes).

func (*Block) Pos

func (e *Block) Pos() diag.Pos

func (*Block) TokenPos

func (e *Block) TokenPos() diag.Pos

func (*Block) Type

func (e *Block) Type() Type

type BuildRead

type BuildRead struct {
	Pos        diag.Pos
	Kind, Path string
	Data       []byte
	Captured   bool
}

BuildRead is a direct intrinsic request. The driver fills Data from a rooted, frozen inventory before any compile-time execution.

type Builtin

type Builtin int

Builtin identifies a function provided by the compiler.

const (
	BuiltinNone Builtin = iota
	BuiltinPrintln
	BuiltinToString
	BuiltinConvert // toInt8(x), toFloat(x), ...
	BuiltinPanic
	BuiltinDbg
	BuiltinTodo
	BuiltinCallerLocation
	BuiltinAssert         // assert(cond)
	BuiltinAssertEqual    // assertEqual(actual, expected)
	BuiltinAssertSnapshot // assertSnapshot(x)
	BuiltinAssemble
)

type CArg

type CArg struct {
	Const   constant.Value // nil for a parameter or sibling
	Param   string
	Type    Type // argument type, including inference from sibling fields
	Sibling bool // argument names a field of the enclosing record or variant
	// contains filtered or unexported fields
}

CArg is an argument of a constraint's predicate, after the value itself: a constant, a function parameter, or a sibling field name (`to: AccountId where notEqual(from)`).

func (CArg) String

func (a CArg) String() string

type Call

type Call struct {
	Func *Func
	Inst *Instance
	Args []Expr
	// Needs holds what the call passes for each of Func's needs (in
	// the order of Func.Needs): a VarRef, Option.Some of one, or
	// Option.None.
	Needs []Expr
	// ArgOrder lists parameter indices in source evaluation order; nil
	// means declaration order. Args remains in declaration order for facts.
	ArgOrder []int
	Labels   []ArgumentLabel
	// Embedded is set for a compile-time bork/embed call.
	Embedded  *Embedded
	BuildRead *BuildRead
	// ReceiverCall distinguishes x.method(a) from Type.method(x, a).
	ReceiverCall bool
	// TypeArgNames holds, per type parameter, an explicit type argument
	// that is a plain name, as written (Port, not Int); "" for others.
	TypeArgNames []string
	// contains filtered or unexported fields
}

Call is a call of a declared function (or method). Args are the arguments as the function takes them: a method's receiver first, then the arguments written, then the defaults of those left out.

func (*Call) EvaluationArgs

func (c *Call) EvaluationArgs() []Expr

EvaluationArgs gives arguments in source evaluation order. Args itself maps parameter identities for contracts and generic specialization.

func (*Call) Pos

func (e *Call) Pos() diag.Pos

func (*Call) TokenPos

func (e *Call) TokenPos() diag.Pos

func (*Call) Type

func (e *Call) Type() Type

type CallBuiltin

type CallBuiltin struct {
	Builtin Builtin
	// DebugText is the original argument text for dbg.
	DebugText string
	Name      string
	Args      []Expr
	// Conv describes a numeric conversion of a value that is not a
	// constant; nil for other builtins.
	Conv *Conversion
	// contains filtered or unexported fields
}

CallBuiltin is a call of a function the compiler provides.

func (*CallBuiltin) Pos

func (e *CallBuiltin) Pos() diag.Pos

func (*CallBuiltin) TokenPos

func (e *CallBuiltin) TokenPos() diag.Pos

func (*CallBuiltin) Type

func (e *CallBuiltin) Type() Type

type CallValue

type CallValue struct {
	Fun  Expr
	Args []Expr
	// contains filtered or unexported fields
}

CallValue is a call of a function value: `f(x)`, `r.handler(x)`.

func (*CallValue) Pos

func (e *CallValue) Pos() diag.Pos

func (*CallValue) TokenPos

func (e *CallValue) TokenPos() diag.Pos

func (*CallValue) Type

func (e *CallValue) Type() Type

type CallableDescription

type CallableDescription struct {
	Requires             []string               `json:"requires,omitempty"`
	NamedArguments       bool                   `json:"named_arguments"`
	ParameterNamesAreAPI bool                   `json:"parameter_names_are_api"`
	Parameters           []ParameterDescription `json:"parameters"`
	// Needs lists the ambient values the function reads, as its
	// signature declares them (locale? for an optional one).
	Needs []string `json:"needs,omitempty"`
}

CallableDescription exposes declaration names, which are intentionally absent from function types. Renaming a named parameter breaks named callers.

func DescribeCallable

func DescribeCallable(fn *Func, params []Type, from *Package, bound bool) *CallableDescription

func EditorCallable added in v0.0.4

func EditorCallable(info *Info, from *Package, name string) *CallableDescription

EditorCallable resolves a declaration with ordinary package lookup rules.

type Class

type Class struct {
	Name    string
	Decl    *syntax.ClassDecl
	Pkg     *Package
	Prelude bool
	Param   *TypeParam
	Methods []*Func // each has Class set, and Param as its type parameter
}

Class is a type class: methods that a type has through an instance (`class Show[T] { fn show(x: T): String }`). Its methods are called like functions; which instance a call uses is decided by the types.

func (*Class) Method

func (c *Class) Method(name string) *Func

Method finds a method of the class by name.

func (*Class) String

func (c *Class) String() string

type ClassInstance

type ClassInstance struct {
	GoFieldDecoders []*Dict
	Name            string
	Decl            *syntax.InstanceDecl
	Pkg             *Package
	Prelude         bool
	Class           *Class
	TypeParams      []*TypeParam
	Type            Type
	// Methods holds the implementations, in the class's method order.
	Methods []*Func
	// Constraints are those of a constrained instance's type
	// (`Decode[Int where positive]`). Such an instance is used only for
	// values known to satisfy them.
	Constraints []*Constraint
}

ClassInstance is a named instance of a class for a type (`instance showInt: Show[Int] { ... }`). A generic instance (`instance showList[T: Show]: Show[List[T]]`) has type parameters, which may need instances themselves.

type Comptime

type Comptime struct {
	Body     *Block
	Owner    *Func
	Captures []*Var
	Value    Expr
	// contains filtered or unexported fields
}

Comptime retains a checked recipe until the driver evaluates it.

func PackageComptime

func PackageComptime(binding *PackageBinding) *Comptime

PackageComptime gives an initializer an independent checked return boundary.

func (*Comptime) Pos

func (e *Comptime) Pos() diag.Pos

func (*Comptime) TokenPos

func (e *Comptime) TokenPos() diag.Pos

func (*Comptime) Type

func (e *Comptime) Type() Type

type Const

type Const struct {
	Value constant.Value
	// SourceSpan covers folded arithmetic whose operand nodes are no longer
	// in the typed tree. Source queries select the complete folded value.
	SourceSpan *SourceSpan
	// contains filtered or unexported fields
}

Const is a constant: a number (or arithmetic on numbers), a String, or a Bool. A number has the value of its type: an Int64 for an integer type, or a float for a float type.

func (*Const) Pos

func (e *Const) Pos() diag.Pos

func (*Const) TokenPos

func (e *Const) TokenPos() diag.Pos

func (*Const) Type

func (e *Const) Type() Type

type Constraint

type Constraint struct {
	Pred      *Func
	PredParam string
	Args      []CArg
	Pos       diag.Pos
	Or        []*Constraint
	Path      string
	Pkg       *Package // scope in which predicate dictionaries are resolved
}

A Constraint is one predicate of a `where` clause, applied to the constrained value: `between(1, 65535)` on a port. Constraints are not part of a value's Type: ordinary type checking ignores them, and the facts pass (facts.go) checks them afterwards.

A constraint with alternatives, `positive or zero`, has a nil Pred and the alternatives in Or; at least one of them must hold.

A constraint inside a type argument applies at a path into the value: ".[]" for every element of a List, ".value" for the value in an Option.Some (`List[Int where positive]` has Path ".[]").

The predicate can also be a parameter of the function, a function value (`List[T where keep]`); PredParam names it, and Pred is nil.

func TypeConstraints

func TypeConstraints(typ Type) []*Constraint

TypeConstraints are the guarantees carried by every valid value of typ.

func (*Constraint) HasSiblingArgs

func (c *Constraint) HasSiblingArgs() bool

HasSiblingArgs reports whether a field constraint depends on sibling values.

func (*Constraint) InstanceFor

func (c *Constraint) InstanceFor(subject Type) *Instance

InstanceFor instantiates a constraint predicate using all its arguments. Some type parameters occur only in a sibling or function parameter.

func (*Constraint) String

func (c *Constraint) String() string

String renders the constraint as written: `positive`, `between(1, 5)`, `positive or zero`.

func (*Constraint) Text

func (c *Constraint) Text(from *Package) string

Text renders the constraint as code in package from would write it.

type ConstructorHead

type ConstructorHead struct {
	Start, End diag.Pos
	Uses       []TypeReference
}

ConstructorHead retains written type uses for source queries.

type Conversion

type Conversion struct {
	From, To Type
	Checked  bool
}

Conversion describes a numeric conversion of a non-constant value. Checked conversions may go out of range, and produce `To | OutOfRange`.

type Copy

type Copy struct {
	Candidate *Var
	X         Expr
	Updates   []*FieldUpdate
	// contains filtered or unexported fields
}

Copy is `x.copy(a: 1, b.c: 2)`.

func (*Copy) Pos

func (e *Copy) Pos() diag.Pos

func (*Copy) TokenPos

func (e *Copy) TokenPos() diag.Pos

func (*Copy) Type

func (e *Copy) Type() Type

type DeferredKind

type DeferredKind uint8

DeferredKind distinguishes when a memoized initializer starts.

const (
	EagerBinding DeferredKind = iota
	LazyBinding
	AsyncBinding
)

type Derived

type Derived struct {
	FieldDicts [][]*Dict
}

Derived describes an instance method the compiler writes (`derive`): FieldDicts holds the class's instance for each field of the type (for a sealed type, each variant's fields, variant by variant).

type Dict

type Dict struct {
	Class *Class
	Type  Type
	// A declared instance:
	Inst     *ClassInstance
	TypeArgs []Type
	Args     []*Dict
	// Or a bound of a type parameter in scope:
	Param *TypeParam
	// Or built in: Eq for comparable types, or Show for every value.
	Builtin bool
}

Dict is the instance a use of a class method or of a function with bounded type parameters gets: a declared instance for a type (with the instances its own bounds need), or the instance the enclosing function was given for one of its type parameters.

type EditorCallEdge added in v0.0.22

type EditorCallEdge struct {
	Caller, Callee, SourceCallee EditorNavigationItem
	Start, End                   diag.Pos
}

func EditorCalls added in v0.0.22

func EditorCalls(info *Info) []EditorCallEdge

EditorCalls retains checked source calls, including calls eliminated by constant folding. Indirect function-value calls have no static declaration.

type EditorExtraction added in v0.0.17

type EditorExtraction struct {
	Function      *Func
	Parameters    []EditorExtractionParameter
	Result        Type
	WrittenResult string
	Effects       Effects
}

func EditorExtractExpression added in v0.0.17

func EditorExtractExpression(info *Info, file *syntax.File, start, end diag.Pos) (*EditorExtraction, error)

EditorExtractExpression resolves an exact parser expression range against the checked graph. Captures use source identities, including references eliminated by constant folding; effects use the same traversal as signature checking.

type EditorExtractionParameter added in v0.0.17

type EditorExtractionParameter struct {
	Name        string
	Type        Type
	Site        diag.Pos
	WrittenType string
}

type EditorInlay added in v0.0.20

type EditorInlay struct {
	Pos       diag.Pos
	Label     string
	Parameter bool
}

func EditorInlays added in v0.0.20

func EditorInlays(info *Info, file *syntax.File, from *Package, options EditorInlayOptions) []EditorInlay

EditorInlays uses recorded source bindings and resolved argument identities. Optional facts share the hover prover, walking each function only once.

type EditorInlayOptions added in v0.0.20

type EditorInlayOptions struct{ Types, Parameters, Facts bool }

EditorInlayOptions selects compiler-backed annotations for a checked snapshot.

type EditorNavigationItem added in v0.0.22

type EditorNavigationItem struct {
	Name      string
	Pos       diag.Pos
	Kind      string
	Container string
}

EditorNavigationItem is a compiler declaration, before source-name mapping.

func EditorImplementations added in v0.0.22

func EditorImplementations(info *Info, declaration diag.Pos, typ Type) []EditorNavigationItem

EditorImplementations maps class declarations/methods to their checked instances, and sealed types to their source variants.

func EditorTypeDefinitions added in v0.0.22

func EditorTypeDefinitions(typ Type) []EditorNavigationItem

EditorTypeDefinitions follows checked types, including generic/container and union components, without resolving names a second time.

type EditorSignature added in v0.0.18

type EditorSignature struct {
	Name, Result, Effects string
	Callable              *CallableDescription
	Definition            *diag.Pos
	ImplicitParameters    int
}

EditorSignature describes a callable without evaluating its facts.

func EditorCheckedSignature added in v0.0.18

func EditorCheckedSignature(info *Info, from *Package, open diag.Pos) *EditorSignature

EditorCheckedSignature returns the exact instantiation at a checked call.

func EditorFunctionSignature added in v0.0.18

func EditorFunctionSignature(name string, typ Type, from *Package) *EditorSignature

EditorFunctionSignature exposes unnamed function-value parameters honestly.

func EditorNamedSignature added in v0.0.18

func EditorNamedSignature(info *Info, from *Package, name string, receiver Type, typeArgs []*syntax.TypeExpr, site diag.Pos) *EditorSignature

EditorNamedSignature resolves unfinished calls with normal package/method lookup and compiler substitution. Unsolved generic parameters remain named.

type Effects

type Effects uint8

Effects is a set of effects: what a function may do outside its arguments and result (see "Effects in signatures" in docs/requirements.md). The empty set is pure.

const (
	EffIO     Effects = 1 << iota // standard streams, files, the process
	EffNet                        // the network
	EffClock                      // time and waiting
	EffRandom                     // random numbers
	EffState                      // state shared between tasks
	EffBuild                      // captured module files, only inside comptime

	// EffOpen stands for the effects of an open function parameter:
	// one written without `uses`, which takes a function with any
	// effects, chosen by each call.
	EffOpen
)

func (Effects) String

func (e Effects) String() string

String writes the effects as a uses declaration lists them: "io + net", or "nothing". EffOpen is written "open".

type Embedded

type Embedded struct {
	Pos   diag.Pos
	Kind  string
	Path  string
	Files []EmbeddedFile
}

Embedded is a compile-time asset request. The driver fills Files before evaluating facts or generating Go; calls share this captured snapshot.

type EmbeddedFile

type EmbeddedFile struct {
	Name      string
	StagePath string
	Data      []byte
}

EmbeddedFile holds captured data and its relative name in a directory snapshot. StagePath is the compiler-owned path used by Go's embed directive.

type Evaluator

type Evaluator func(queries []Query) ([]bool, error)

Evaluator runs predicates on constants at compile time, returning one result per query.

type ExecutionAudit

type ExecutionAudit struct {
	Decline      string
	Declarations []ExecutionDeclaration
	Intrinsics   []ExecutionIntrinsic
	Priors       []ExecutionPriorSite
}

ExecutionAudit is owned static evidence only. It does not certify generated support/import initialization, the Go build closure, or native/policy inputs. Those independent inventories remain mandatory before any execution hit.

func AuditComptimeExecution

func AuditComptimeExecution(info *Info, node *Comptime) ExecutionAudit

func AuditExecutionQueries

func AuditExecutionQueries(info *Info, queries []Query) ExecutionAudit

AuditExecutionQueries inventories every actual query, including And/Or leaves and typed argument/setup expressions. Query.Text and Func.Calls are not closure evidence. Unknown nodes or targets produce an ordinary eligibility decline.

type ExecutionDeclaration

type ExecutionDeclaration struct {
	Package, Name, Signature string
	Position                 diag.Pos
}

type ExecutionIntrinsic

type ExecutionIntrinsic struct {
	Declaration    ExecutionDeclaration
	Contract       string
	Implementation [sha256.Size]byte
}

type ExecutionPriorSite

type ExecutionPriorSite struct {
	Position diag.Pos
	Type     string
}

type Expr

type Expr interface {
	// Pos is where the expression starts.
	Pos() diag.Pos
	// TokenPos is the operator, call parenthesis, or selected name that
	// identifies this expression in source queries. Pos remains its start.
	TokenPos() diag.Pos
	Type() Type
	// contains filtered or unexported methods
}

Expr is a typed expression.

func DecodeComptime

func DecodeComptime(node *Comptime, data []byte) (Expr, error)

DecodeComptime validates compiler transport against the concrete checked type.

type ExprStmt

type ExprStmt struct {
	X Expr
}

ExprStmt is an expression evaluated for its effect.

type Field

type Field struct {
	RuntimePackageReads bool

	Lazy         bool
	Computed     bool
	Dependencies []*Field
	DefaultVars  []*Var
	DefaultCalls []*Func

	GoTags  []syntax.GoTag
	Decl    *syntax.FieldDecl
	Pkg     *Package
	Prelude bool
	Doc     string
	Default Expr

	Name string
	Type Type
	// Constraints is the field's where clause.
	Constraints []*Constraint
	// contains filtered or unexported fields
}

func EditorRecordFields added in v0.0.4

func EditorRecordFields(info *Info, from *Package, head *syntax.TypeExpr) []*Field

EditorRecordFields also exposes a generic declaration before its literal's fields have supplied enough information to infer type arguments.

func EditorVariantFields added in v0.0.4

func EditorVariantFields(info *Info, from *Package, owner *syntax.TypeExpr, name string) []*Field

EditorVariantFields uses the same variant lookup and visibility as a specialized constructor. It returns declaration fields for an unresolved generic head and substituted fields for an explicitly specialized one.

type FieldUpdate

type FieldUpdate struct {
	Thunk *Lambda
	Lazy  *LazyDescription
	Path  []string
	Field *Field
	Value Expr
}

FieldUpdate is a (possibly nested) field a copy changes: Field is the last one on Path.

type FieldValue

type FieldValue struct {
	Thunk     *Lambda
	Lazy      *LazyDescription
	IsDefault bool
	Name      string
	Field     *Field
	Value     Expr
}

FieldValue is a field of a record literal.

type FloatBits

type FloatBits struct {
	Bits uint64
	// contains filtered or unexported fields
}

FloatBits preserves computed IEEE values, including NaN and negative zero.

func (*FloatBits) Pos

func (e *FloatBits) Pos() diag.Pos

func (*FloatBits) TokenPos

func (e *FloatBits) TokenPos() diag.Pos

func (*FloatBits) Type

func (e *FloatBits) Type() Type

type For

type For struct {
	Var   *Var
	Items Expr
	Body  *Block
	// contains filtered or unexported fields
}

func (*For) Pos

func (e *For) Pos() diag.Pos

func (*For) TokenPos

func (e *For) TokenPos() diag.Pos

func (*For) Type

func (e *For) Type() Type

type Func

type Func struct {
	RuntimePackageReads bool

	Decl *syntax.FuncDecl
	Pkg  *Package
	// Class is set for a class's method (which has no body), and Of for
	// the implementation of a method in an instance.
	Class *Class
	Of    *ClassInstance
	// Derived is set for an instance method the compiler writes.
	Derived *Derived
	// TypeParams lists a generic function's type parameters.
	TypeParams []*TypeParam
	Params     []Type
	Result     Type
	// Effects is what the function declares it may do (`uses io`).
	Effects Effects
	// Needs lists the ambient values it reads (`needs traceId`), in
	// the order of its hidden parameters, and NeedVars their variables.
	Needs    []*FuncNeed
	NeedVars []*Var
	// Prelude is set for the built-in functions of prelude.
	Prelude bool
	// TrackCaller adds a hidden source location for internal helper diagnostics.
	TrackCaller bool
	// Synthetic is set for a predicate that stands for a function
	// parameter (see facts.go); it has no body to run.
	Synthetic bool
	// Test is set for the function checking a test's body.
	Test *syntax.TestDecl
	// MockOf is set for the body of a `mock` statement in a test, checked
	// as a function with the signature of the function it mocks. Its
	// Decl.Params are the names the mock gives the parameters, and
	// MockIn is the test it is in.
	MockOf, MockIn *Func
	// Calls lists the functions this function's body calls.
	Calls []*Func
	// ParamVars are the variables of the parameters, and Body the typed
	// tree of the body (nil for a function implemented in Go).
	ParamVars []*Var
	Body      *Block
	Requires  Expr
	// ParamIn holds, per parameter, the index of the parameter (a Scope
	// or an OwnedScope) it is declared to belong to (`conn: Conn in
	// prev`), or -1.
	ParamIn []int

	ParamConstraints  [][]*Constraint
	ResultConstraints []MemberConstraints
	// contains filtered or unexported fields
}

Func is a declared function's signature.

func ComptimeHelpers

func ComptimeHelpers(node *Comptime, dictionaries ...*Dict) []*Func

ComptimeHelpers inventories implementations used by a recipe, including dictionary methods and captures. The driver separately evaluates dependencies.

func (*Func) InstanceFor

func (fn *Func) InstanceFor(subject Type) *Instance

InstanceFor instantiates fn (a predicate) for a value of type subject as its first argument. It returns nil if that does not decide fn's type parameters.

func (*Func) Mockable

func (fn *Func) Mockable(from *Package) bool

Mockable reports whether a test of package from can mock fn (see mockTarget): a declared function with effects, of from or exported, that is not a predicate, a class method, or the prelude's.

func (*Func) QualifiedName

func (fn *Func) QualifiedName(from *Package) string

QualifiedName is the function's name as code in package from refers to it: "money.add" for a function of a package from imports.

type FuncNeed

type FuncNeed struct {
	Ambient  *Ambient
	Optional bool
	Decl     *syntax.Need
	// Type is the type the function's body reads the value as.
	Type Type
}

FuncNeed is one ambient value a function reads (`needs traceId`, or `needs locale?` for an optional one, read as an Option).

type FuncRef

type FuncRef struct {
	Name string // as written
	Inst *Instance
	// Needs is what the reference binds for the function's needs, as
	// Call.Needs.
	Needs []Expr
	// contains filtered or unexported fields
}

FuncRef is a declared function used as a value: `xs.map(double)`.

func MockTargetRef

func MockTargetRef(m *Mock) *FuncRef

MockTargetRef is a mock's target as a function value, for code queries on its name.

func (*FuncRef) Pos

func (e *FuncRef) Pos() diag.Pos

func (*FuncRef) TokenPos

func (e *FuncRef) TokenPos() diag.Pos

func (*FuncRef) Type

func (e *FuncRef) Type() Type

type FuncType

type FuncType struct {
	Params []Type
	Result Type
	// Effects is what calling the function may do: `(A) uses io => C`.
	Effects Effects
}

FuncType is the type of a function value: `(A, B) => C`.

func (*FuncType) String

func (f *FuncType) String() string

type Generate

type Generate struct {
	Body        *Block
	Constraints []*Constraint
	// contains filtered or unexported fields
}

Generate constructs a producer without running its body.

func (*Generate) Pos

func (e *Generate) Pos() diag.Pos

func (*Generate) TokenPos

func (e *Generate) TokenPos() diag.Pos

func (*Generate) Type

func (e *Generate) Type() Type

type GoBinding

type GoBinding struct {
	// Path is the Go package's import path, and Name the function's.
	Path, Name   string
	Receiver     types.Type
	ParamIndices []int
	ScopeIndex   int
	Sig          *types.Signature
	Shape        GoResultShape
	// Value is the bork type the Go result value converts to: the
	// result's leftmost member (an Option for GoValueOk), or nil.
	Value Type
	// Fallible is set when converting the result from Go can fail, so
	// the bork result has GoValueError.
	Fallible bool
	// Contextual resource results share generated, attachable cancellation.
	Contextual bool
	// GoError and GoValueError are the prelude's records, when the
	// result has them.
	GoError, GoValueError Type
}

GoBinding is a checked binding of a bork function to a Go function.

type GoField

type GoField struct {
	Tag  string
	Path []string
	Type types.Type
}

Field is a named, typed field of a record or variant.

type GoNames

type GoNames interface {
	Names(paths []string) map[string]string
}

GoNames optionally supplies declared package names without loading their types. The driver provides it; checker-only tests may omit a Go environment.

type GoResultShape

type GoResultShape int

GoResultShape is the form of a bound Go function's results.

const (
	GoNoResult   GoResultShape = iota // f()
	GoValue                           // f() T
	GoErrorOnly                       // f() error
	GoValueError                      // f() (T, error)
	GoValueOk                         // f() (T, bool)
)

type GoTypes

type GoTypes interface {
	// Load returns the packages at the given import paths, and the
	// error of each that could not be loaded.
	Load(paths []string) (map[string]*types.Package, map[string]error)
}

GoTypes gives the checker the Go packages that bindings name. The driver loads them with go/packages; tests can give fakes.

type If

type If struct {
	Cond Expr
	Then *Block
	Else Expr
	// contains filtered or unexported fields
}

If is `if (cond) { ... } else ...`. Else is nil, a *Block, or an *If.

func (*If) Pos

func (e *If) Pos() diag.Pos

func (*If) TokenPos

func (e *If) TokenPos() diag.Pos

func (*If) Type

func (e *If) Type() Type

type Info

type Info struct {
	Interpolations       map[Expr]*InterpolationSource
	InterpolationBatches []*InterpolationBatch

	PackageBindings []*PackageBinding

	// GoImportNames resolves unsafe Go imports without mutating source syntax.
	GoImportNames map[*syntax.GoCode]map[string]string

	// Packages lists the program's packages.
	Packages []*Package
	// Ambients lists the program's ambient declarations, in order.
	Ambients []*Ambient
	// Classes and ClassInstances list every class and instance.
	Classes        []*Class
	ClassInstances []*ClassInstance
	// Funcs holds the functions visible to the root package by name: its
	// own, and the prelude's that it does not replace.
	Funcs map[string]*Func
	// FuncOf holds every declared function, including prelude functions
	// the package replaced (the prelude still uses its own).
	FuncOf map[*syntax.FuncDecl]*Func
	// Named holds every declared type: *Record, *Sealed, or (for an
	// alias) the aliased type.
	Named map[string]Type
	// TypeOrder lists declared records and sealed types in source order.
	TypeOrder []Type
	// OutOfRange is the prelude's OutOfRange record.
	OutOfRange Type
	// Tests holds the root package's tests, each checked as a function
	// without parameters.
	Tests []*Func
	// Lifetimes holds the scopes each expression's value belongs to, and
	// VarLifetimes each variable's (see lifetimes.go), for queries.
	Lifetimes    map[Expr][]string
	VarLifetimes map[*Var][]string
	// Mocks holds the bodies of the tests' `mock` statements (see
	// Func.MockOf), and mocks them by statement.
	Mocks []*Func

	// MockCalls are the records of calls of the functions tests mock
	// with a handle (see callRecord), declared only in test builds.
	MockCalls     map[*Func]*Record
	MockCallOrder []*Record

	// Rules holds the inference rules of every package.
	Rules []*Rule
	// GoBindings holds every checked binding to a Go function
	// (`unsafe go "os.Getenv"`).
	GoBindings map[*Func]*GoBinding
	// Comptimes lists explicit build-time computations in lowering order.
	Comptimes []*Comptime

	// Embeds lists compile-time asset requests in source order.
	Embeds []*Embedded

	BuildReads []*BuildRead

	ProviderBundles []*ProviderBundle
	// contains filtered or unexported fields
}

func Program

func Program(files []*syntax.File, root string, diags *diag.List, goTypes GoTypes) *Info

Program type-checks a program: the root package (whose import path is root), and the packages it imports. files holds the files of all of them, and the prelude's.

goTypes loads the Go packages that bindings name; it may be nil for a program without bindings.

func ProgramObserved

func ProgramObserved(files []*syntax.File, root string, diags *diag.List, goTypes GoTypes, observe func(string)) *Info

ProgramObserved is Program with optional phase notifications for benchmarks. observe is called before lowering and contract checks; checking starts in the caller.

func (*Info) LazyFieldDescription

func (info *Info) LazyFieldDescription(value Expr) *LazyDescription

LazyFieldDescription distinguishes a recipe from a transparent field read.

func (*Info) Mocked

func (info *Info) Mocked(fn *Func) bool

Mocked reports whether a test mocks fn. Such a function promises its callers only what its signature says, as another package's does, since a mock keeps only those promises.

func (*Info) PredicateDicts

func (info *Info) PredicateDicts(from *Package, inst *Instance) bool

PredicateDicts resolves dictionaries in the scope that declared a constraint. Runtime validation may instantiate that constraint at a concrete field type.

func (*Info) ProviderBundleAt

func (info *Info) ProviderBundleAt(pos diag.Pos) (*ProviderBundleDescription, *Package)

ProviderBundleAt returns metadata for a declaration or an assembly-use token.

func (*Info) Reaching

func (info *Info) Reaching(fn *Func, effects Effects) [][]*Func

Reaching lists a path from fn to each function doing one of effects in Go code that calling fn, with no mocks, can reach.

func (*Info) Unmocked

func (info *Info) Unmocked(test *Func, effects Effects) []UnmockedPath

Unmocked lists, for the test, a path to each function that does one of effects in Go code and that the test reaches with no mock of it, or of a function on the way, in force (one path per function, the first found).

type Instance

type Instance struct {
	Func     *Func
	TypeArgs []Type
	Params   []Type
	Result   Type
	// Dicts holds the class instances the use needs: for a class method,
	// the class's; for a function with bounded type parameters, one per
	// bound, in order.
	Dicts []*Dict
	// ArgFacts holds, per type parameter, the constraints of an explicit
	// type argument (json.Decode[Port]): arguments of that type must
	// satisfy them, and results of it do (see callFunc).
	ArgFacts [][]*Constraint
}

Instance is a use of a function: a call, or a reference to it as a value. For a generic function it records the type arguments, and the parameter and result types with them substituted.

type Interp

type Interp struct {
	Parts []string
	Exprs []Expr
	// contains filtered or unexported fields
}

Interp is an interpolated string: s"Hello $name". Parts holds the text around the expressions, one more than Exprs.

func (*Interp) Pos

func (e *Interp) Pos() diag.Pos

func (*Interp) TokenPos

func (e *Interp) TokenPos() diag.Pos

func (*Interp) Type

func (e *Interp) Type() Type

type InterpolationBatch

type InterpolationBatch struct {
	Recipe *Comptime
	Sites  []*InterpolationSite
}

InterpolationBatch evaluates distinct calls once for a source package.

type InterpolationSite

type InterpolationSite struct {
	Prefix    diag.Pos
	Holes     []diag.Pos
	Validator string
	Package   string
	Call      *Call
	Key       string
	Index     int
}

InterpolationSite retains only a constant validator call and source positions. Runtime factories, builders, and hole values never enter the recipe.

type InterpolationSource

type InterpolationSource struct {
	Prefix  SourceSpan
	Factory Expr
	Holes   []Expr
}

Info is what the checker learned about a program: the root package, and the packages it imports. Later passes (lifetimes, facts, and code generation) read it, and the typed tree of each function body (Func.Body), instead of re-deriving types. InterpolationSource retains source expressions hidden by named interpolation lowering. Holes refer to the expressions already lowered for execution.

type KnownFact

type KnownFact struct {
	Constraint string `json:"constraint"`
	Path       string `json:"path,omitempty"`
}

KnownFact is a conservative fact from a guard, declaration or promise. Path is empty for the whole value, or a field/element path such as .[].

type Lambda

type Lambda struct {
	Params []*Var
	Body   Expr
	// contains filtered or unexported fields
}

Lambda is a function value written in place. Its type is a *FuncType.

func ComptimeLambda

func ComptimeLambda(node *Comptime) *Lambda

ComptimeLambda gives generation an independent return boundary.

func ComputedFieldInitializer

func ComputedFieldInitializer(field *Field, rootName string, rootType Type) *Lambda

ComputedFieldInitializer rebuilds a checked recipe at a runtime data boundary. It does not change checker metadata, so cached programs remain immutable while independent emitters generate Go from the same checked result.

func (*Lambda) Pos

func (e *Lambda) Pos() diag.Pos

func (*Lambda) TokenPos

func (e *Lambda) TokenPos() diag.Pos

func (*Lambda) Type

func (e *Lambda) Type() Type

type LazyDescription

type LazyDescription struct {
	Kind         string   `json:"kind"`
	Effects      string   `json:"initializer_effects"`
	Captures     []string `json:"captures,omitempty"`
	Dependencies []string `json:"dependencies,omitempty"`
}

type Let

type Let struct {
	Deferred   DeferredKind
	AsyncScope Expr
	Async      *AsyncDescription
	// Initializer holds a deferred initializer's function boundary; Value retains
	// its ordinary source type for effects and static proof checking.
	Initializer *Lambda
	Lazy        *LazyDescription
	Pos         diag.Pos
	Var         *Var
	Value       Expr
	// Declared is set when the binding's type is written; Constraints
	// are then its where clauses.
	Declared    bool
	Constraints []*Constraint
}

Let binds a variable; name "_" only evaluates and drops its value.

type List

type List struct {
	Elem Type
}

List is the built-in immutable list type List[T].

func (*List) String

func (l *List) String() string

type ListLit

type ListLit struct {
	Nil   bool
	Elems []Expr
	// contains filtered or unexported fields
}

ListLit is a list literal: `[1, 2, 3]`.

func (*ListLit) Pos

func (e *ListLit) Pos() diag.Pos

func (*ListLit) TokenPos

func (e *ListLit) TokenPos() diag.Pos

func (*ListLit) Type

func (e *ListLit) Type() Type

type LoopControl

type LoopControl struct {
	Continue bool
	// contains filtered or unexported fields
}

func (*LoopControl) Pos

func (e *LoopControl) Pos() diag.Pos

func (*LoopControl) TokenPos

func (e *LoopControl) TokenPos() diag.Pos

func (*LoopControl) Type

func (e *LoopControl) Type() Type

type Map

type Map struct {
	Key, Value Type
}

Map is the built-in immutable map type Map[K, V]. It keeps its keys in the order they were first added.

func (*Map) String

func (m *Map) String() string

type MapLit

type MapLit struct {
	Keys, Values []Expr
	// contains filtered or unexported fields
}

MapLit is a map literal: `{"a": 1}`.

func (*MapLit) Pos

func (e *MapLit) Pos() diag.Pos

func (*MapLit) TokenPos

func (e *MapLit) TokenPos() diag.Pos

func (*MapLit) Type

func (e *MapLit) Type() Type

type Match

type Match struct {
	X    Expr
	Arms []*MatchArm
	// contains filtered or unexported fields
}

Match is `match (x) { pattern => value, ... }`.

func (*Match) Pos

func (e *Match) Pos() diag.Pos

func (*Match) TokenPos

func (e *Match) TokenPos() diag.Pos

func (*Match) Type

func (e *Match) Type() Type

type MatchArm

type MatchArm struct {
	Pat  *Pat
	Body Expr
}

MatchArm is an arm of a match: its checked pattern, and its value.

type MemberConstraints

type MemberConstraints struct {
	Type        Type
	Constraints []*Constraint
}

MemberConstraints are the constraints on the values of one member of a function's result (the whole result, if it is not a union).

type MethodDescription

type MethodDescription struct {
	Name       string               `json:"name"`
	Type       string               `json:"type,omitempty"`
	Definition *diag.Pos            `json:"definition,omitempty"`
	Ambiguity  string               `json:"ambiguity,omitempty"`
	Requires   []string             `json:"requires,omitempty"`
	Callable   *CallableDescription `json:"callable,omitempty"`
}

MethodDescription is a method as seen from the querying package. Ambiguous names are reported separately from callable methods.

func VisibleMethods

func VisibleMethods(info *Info, from *Package, t Type) []MethodDescription

VisibleMethods uses the same precedence and visibility rules as a call.

type Mock

type Mock struct {
	Pos    diag.Pos
	Target *Func
	// Text is the target as written, at TargetPos.
	Text      string
	TargetPos diag.Pos
	Var       *Var
	Func      *Func
}

Mock is `mock target(a, b) { ... }` in a test: until the end of the block, calls of Target run Func's body instead. Func is the mock's body as a function, with Target's signature (see Func.MockOf); Var is the handle that records the calls, or nil. Text is the target as written, which recorded calls are shown with.

type Opaque

type Opaque struct {
	Name   string
	Decl   *syntax.TypeDecl
	Pkg    *Package
	GoType types.Type
}

Resource is a resource type (`type File = resource`): a handle to something outside the program that a scope closes. Its values are made by `unsafe go` functions, which register the finalizer.

func (*Opaque) String

func (o *Opaque) String() string

type Package

type Package struct {
	Path string // the import path; "" for the prelude
	Name string // the last element of the path
	// Root is set for the package being built or tested; the others are
	// the packages it imports, directly or not.
	Root bool
	// GoPrefix starts the Go names of the package's functions and types
	// ("" for the root package and the prelude).
	GoPrefix string
	// Funcs holds the package's own functions by name.
	Funcs map[string]*Func
	// contains filtered or unexported fields
}

Package is a bork package: a directory of .bork files.

func (*Package) TypeNamed

func (p *Package) TypeNamed(name string) Type

TypeNamed is the record, sealed, or resource type the package declares with the given name, or nil.

type PackageAPI added in v0.0.13

type PackageAPI struct {
	Path, Documentation string
	Unsafe              bool
	Declarations        []APIDeclaration
}

PackageAPI is an owned view of the declarations an importer can use.

func API added in v0.0.13

func API(info *Info, files []*syntax.File, path string) *PackageAPI

type PackageBinding

type PackageBinding struct {
	Decl         *syntax.Binding
	Pkg          *Package
	Type         Type
	Var          *Var
	Value        *Let
	Boundary     *Func
	Dependencies []*PackageBinding
	// contains filtered or unexported fields
}

PackageBinding is a transparent immutable value, memoized on first read.

func ComptimePackageBindings

func ComptimePackageBindings(info *Info, node *Comptime) []*PackageBinding

ComptimePackageBindings inventories package reads through the same helpers, dictionaries, renderers and computed fields as package cycle checking.

type ParameterDescription

type ParameterDescription struct {
	Doc      string `json:"doc,omitempty"`
	Name     string `json:"name"`
	Type     string `json:"type"`
	Receiver bool   `json:"receiver,omitempty"`
	Default  string `json:"default,omitempty"`
}

func EditorRemainingParameters added in v0.0.4

func EditorRemainingParameters(callable *CallableDescription, args []syntax.Argument) []ParameterDescription

EditorRemainingParameters follows the same name/position assignment as calls.

type Pat

type Pat struct {
	Kind PatKind
	// Type is the type of the value matched at this position.
	Type Type
	// Bind, if not empty, names the value matched here; BindType is its
	// type (narrowed, for PatType), and bindNode the syntax node that
	// introduced it.
	Bind     string
	BindType Type

	// Var is the variable of the bound name in the typed tree, set
	// when the tree is built (see lower.go).
	Var *Var
	// Lit is the value of a PatLit (a number, string, or bool constant).
	Lit constant.Value
	// Variant is the variant of a PatVariant.
	Variant *Variant
	// Fields are the field patterns of a PatVariant or PatRecord, in
	// the order written. Missing fields match anything.
	Fields []*PatField
	// Members are the union members a PatType tests for, and Sub the
	// pattern for the narrowed value (nil: anything).
	Members []Type
	Sub     *Pat
	// Elems and Rest are the parts of a PatList; Rest (a wildcard,
	// possibly binding the remaining elements) is nil for a list of
	// exactly len(Elems) elements.
	Elems []*Pat
	Rest  *Pat
	// Guard is the runtime predicate condition, evaluated after the
	// structural tests succeed. guard is its syntax before lowering.
	Guard Expr
	// contains filtered or unexported fields
}

Pat is a checked match pattern. Code generation lowers matches from these, and exhaustiveness is decided on them.

func (*Pat) Guards

func (p *Pat) Guards() []Expr

Guards lists the predicate conditions in the order they are tested.

func (*Pat) HasGuard

func (p *Pat) HasGuard() bool

HasGuard reports whether any part of the pattern tests a predicate.

func (*Pat) Narrowed

func (p *Pat) Narrowed() Type

Narrowed is the type of the value a PatType lets through.

type PatField

type PatField struct {
	Name string
	Pat  *Pat
}

PatField is one field of a destructuring pattern.

type PatKind

type PatKind int

PatKind says what a checked pattern tests.

const (
	// PatWild matches anything (`_`, or a name that binds the value).
	PatWild PatKind = iota
	// PatLit matches one literal value.
	PatLit
	// PatVariant matches one variant of a sealed type, and its fields.
	PatVariant
	// PatRecord destructures a record, matching its fields.
	PatRecord
	// PatType matches the members Members of a union, and then the
	// narrowed value against Sub.
	PatType
	// PatList matches a list with as many elements as Elems (or, with
	// Rest, at least as many), and its elements against them.
	PatList
)

type Proof

type Proof struct {
	Where  string `json:"where"`
	Proven bool   `json:"proven"`
	Reason string `json:"reason,omitempty"`
}

Proof answers an explicit where-clause query using the compiler's prover.

type ProviderBundle

type ProviderBundle struct {
	Decl    *syntax.ProviderBundle
	Pkg     *Package
	Entries []*ProviderBundleEntry
}

ProviderBundle retains declaration identity across package boundaries.

type ProviderBundleDescription

type ProviderBundleDescription struct {
	Name       string                     `json:"name"`
	Definition diag.Pos                   `json:"definition"`
	Entries    []ProviderEntryDescription `json:"entries"`
}

ProviderBundleDescription is static wiring metadata, not a value type.

type ProviderBundleEntry

type ProviderBundleEntry struct {
	Decl *syntax.ProviderEntry
	Func *Func
}

type ProviderEntryDescription

type ProviderEntryDescription struct {
	Needs        []string `json:"needs,omitempty"`
	Name         string   `json:"name"`
	Function     string   `json:"function"`
	Position     diag.Pos `json:"position"`
	Product      string   `json:"product"`
	Dependencies []string `json:"dependencies"`
	Effects      string   `json:"effects"`
	Failures     []string `json:"failures"`
	Replaced     bool     `json:"replaced,omitempty"`
}

type Query

type Query struct {
	Pred *Func
	// Values retain each closed argument's type for instantiated predicate calls.
	Values     []Expr
	ValueTexts []string
	Args       []constant.Value // the constrained value first
	// Subject, when set, is the constrained value as an expression of
	// constants (a list or record literal), shown as SubjectText; Args
	// then holds only the other arguments.
	Subject     Expr
	SubjectText string
	// TypeArgs are a generic predicate's type arguments, and Params its
	// parameter types with them filled in.
	TypeArgs []Type
	Params   []Type
	Dicts    []*Dict
	ArgFacts [][]*Constraint
	Or       []Query
	And      []Query
	// Via names the function whose result the constant is, when the
	// query comes from a derived result (see derive).
	Via string
}

Query is a predicate call on constants, for evaluation at compile time.

A query may also combine others: with Or set it holds if any of them does, with And if all of them do; Pred is then nil.

func (Query) String

func (q Query) String() string

func (Query) Text

func (q Query) Text(from *Package) string

Text renders the query as code in package from would write it.

type Record

type Record struct {
	GoGenerated  bool
	GoStruct     bool
	GoTo, GoFrom bool
	GoMirror     types.Type
	GoFields     []GoField
	Name         string
	Fields       []*Field
	Constraints  []*Constraint
	Decl         *syntax.TypeDecl
	Prelude      bool     // declared in prelude
	Pkg          *Package // the declaring package
	// MockCall is a mock's call record (see callRecord), which only
	// test builds declare.
	MockCall bool

	TypeParams []*TypeParam
	Base       *Record
	Args       []Type
	// contains filtered or unexported fields
}

Record is a named record type: `type User = { name: String }`.

A generic record (`type Pair[A, B] = { first: A, second: B }`) has TypeParams; its instances (`Pair[Int, String]`) have Base set to it, Args, and Fields with the arguments filled in.

func (*Record) Field

func (r *Record) Field(name string) *Field

func (*Record) Instance

func (r *Record) Instance(args []Type) *Record

Instance is the generic record r with the given type arguments.

func (*Record) String

func (r *Record) String() string

type RecordLit

type RecordLit struct {
	Candidate *Var
	// Promoted marks an implicit Some around a source expression.
	Promoted    bool
	Record      *Record
	Variant     *Variant
	Fields      []*FieldValue
	Head        *ConstructorHead
	Constraints []*Constraint
	// contains filtered or unexported fields
}

RecordLit builds a record (Variant nil) or a variant of a sealed type: `User { name: "Ada" }`, `Shape.Circle { radius: 3 }`. Fields are in the order written.

func (*RecordLit) Pos

func (e *RecordLit) Pos() diag.Pos

func (*RecordLit) TokenPos

func (e *RecordLit) TokenPos() diag.Pos

func (*RecordLit) Type

func (e *RecordLit) Type() Type

type Resource

type Resource struct {
	GoType  types.Type
	Name    string
	Decl    *syntax.TypeDecl
	Prelude bool
	Pkg     *Package
}

func (*Resource) String

func (r *Resource) String() string

type Return

type Return struct {
	Value Expr
	// contains filtered or unexported fields
}

Return is `return` or `return value`.

func (*Return) Pos

func (e *Return) Pos() diag.Pos

func (*Return) TokenPos

func (e *Return) TokenPos() diag.Pos

func (*Return) Type

func (e *Return) Type() Type

type Rule

type Rule struct {
	Decl     *syntax.RuleDecl
	Pkg      *Package
	VarTypes []Type // the types of Decl.Params
	Premises []*RuleAtom
	// Conditions are the premises that compute with the variables'
	// values, as typed expressions. They are evaluated on constants or
	// matched against branch comparisons; conditions holds
	// them as written.
	Conditions []Expr

	Conclusions []*RuleAtom
	// Vars are the rule's variables. PremiseExprs and ConclusionExprs
	// are its premises and conclusions as typed expressions, which test
	// mode runs, and ConclusionTexts the conclusions as written.
	Vars            []*Var
	PremiseExprs    []Expr
	ConclusionExprs []Expr
	ConclusionTexts []string
	// contains filtered or unexported fields
}

Rule is a checked inference rule: when facts matching Premises hold (and the Conditions are established), the Conclusions hold too.

type RuleArg

type RuleArg struct {
	Var       string
	Const     constant.Value
	ConstType Type
}

RuleArg is a rule variable, or a constant.

type RuleAtom

type RuleAtom struct {
	Inst *Instance
	Pred *Func
	Args []RuleArg // the subject first
}

RuleAtom is a predicate applied to rule variables and constants.

type ScopeBlock

type ScopeBlock struct {
	Var      *Var
	Policies []Expr
	Body     *Block
	// contains filtered or unexported fields
}

ScopeBlock is `scope s { ... }`.

func (*ScopeBlock) Pos

func (e *ScopeBlock) Pos() diag.Pos

func (*ScopeBlock) TokenPos

func (e *ScopeBlock) TokenPos() diag.Pos

func (*ScopeBlock) Type

func (e *ScopeBlock) Type() Type

type Sealed

type Sealed struct {
	Name        string
	Variants    []*Variant
	Constraints []*Constraint
	Decl        *syntax.TypeDecl
	Prelude     bool     // declared in prelude
	Pkg         *Package // the declaring package

	TypeParams []*TypeParam
	Base       *Sealed
	Args       []Type
	// contains filtered or unexported fields
}

Sealed is a type with a closed set of variants: `type Shape = sealed { Circle { radius: Int }, Empty }`.

Like records, sealed types can be generic: the prelude's `type Option[T] = sealed { Some { value: T }, None }` is one.

func (*Sealed) Instance

func (s *Sealed) Instance(args []Type) *Sealed

Instance is the generic sealed type s with the given type arguments.

func (*Sealed) String

func (s *Sealed) String() string

func (*Sealed) Variant

func (s *Sealed) Variant(name string) *Variant

type Select

type Select struct {
	X     Expr
	Name  string
	Field *Field
	// contains filtered or unexported fields
}

Select reads a record's field: `user.name`.

func (*Select) Pos

func (e *Select) Pos() diag.Pos

func (*Select) TokenPos

func (e *Select) TokenPos() diag.Pos

func (*Select) Type

func (e *Select) Type() Type

type SemanticToken added in v0.0.16

type SemanticToken struct {
	Start, End                             diag.Pos
	Kind                                   string
	Declaration, Readonly, Static, Builtin bool
	GoBinding, Rebinding                   bool
}

SemanticToken describes a compiler-owned source classification. Positions use byte columns; protocol adapters choose their own encoding and legend.

func LexicalSemanticTokens added in v0.0.16

func LexicalSemanticTokens(path, source string) []SemanticToken

LexicalSemanticTokens is the current-source fallback when checking fails. Interpolated strings and raw Go are left to the editor's embedded grammar.

func SemanticTokens added in v0.0.16

func SemanticTokens(file *syntax.File, info *Info) []SemanticToken

SemanticTokens uses resolved checker identities, including names that share spelling but denote different declarations. It never resolves names again.

type Seq

type Seq struct {
	Elem    Type
	Effects Effects
}

Seq is a lazy sequence whose effects are charged when traversed.

func (*Seq) String

func (s *Seq) String() string

type SeqCall

type SeqCall struct {
	Op      string
	Args    []Expr
	Effects Effects
	// contains filtered or unexported fields
}

func (*SeqCall) Pos

func (e *SeqCall) Pos() diag.Pos

func (*SeqCall) TokenPos

func (e *SeqCall) TokenPos() diag.Pos

func (*SeqCall) Type

func (e *SeqCall) Type() Type

type SourceReference added in v0.0.21

type SourceReference struct {
	Start, End, Definition diag.Pos
	Name                   string
	Declaration            bool
	Prefix, Suffix         string
}

SourceReference is an owned source range and its checked declaration identity. Prefix/Suffix expand shorthand patterns without renaming their bound variable.

type SourceSpan

type SourceSpan struct {
	Start diag.Pos `json:"start"`
	End   diag.Pos `json:"end"`
}

type Stmt

type Stmt interface {
	// contains filtered or unexported methods
}

Stmt is a statement of a block.

type Symbol added in v0.0.21

type Symbol struct {
	Name, Kind, Package, Container string
	Declaration, Definition, End   diag.Pos
	Exported                       bool
}

Symbol identifies a source declaration. Definition points at its identifier, so independently checked import graphs agree on the same source identity.

type SymbolIndex added in v0.0.21

type SymbolIndex struct {
	// contains filtered or unexported fields
}

func BuildSourceIndex added in v0.0.21

func BuildSourceIndex(files []*syntax.File, info *Info) *SymbolIndex

BuildSourceIndex adapts existing checker metadata. No name lookup occurs in the protocol adapter, and the resulting index retains no compiler graph.

func (*SymbolIndex) AllReferences added in v0.0.21

func (index *SymbolIndex) AllReferences() []SourceReference

func (*SymbolIndex) At added in v0.0.21

func (index *SymbolIndex) At(pos diag.Pos) *SourceReference

func (*SymbolIndex) References added in v0.0.21

func (index *SymbolIndex) References(def diag.Pos) []SourceReference

func (*SymbolIndex) Symbols added in v0.0.21

func (index *SymbolIndex) Symbols() []Symbol

type Trust

type Trust struct {
	Pos         diag.Pos
	Call        Expr
	Text        string
	SubjectText string
}

Trust is `trust p(x, ...)`: Call is the call, a *Call of a predicate (or a *CallValue of a predicate parameter, which the facts pass reports). Text is the call as written, and SubjectText its first argument (x).

type Try

type Try struct {
	X Expr
	TryInfo
	// contains filtered or unexported fields
}

Try is `x?`.

func (*Try) Pos

func (e *Try) Pos() diag.Pos

func (*Try) TokenPos

func (e *Try) TokenPos() diag.Pos

func (*Try) Type

func (e *Try) Type() Type

type TryInfo

type TryInfo struct {
	// Kept is the type `?` produces.
	Kept Type
	// Rest lists the union members returned from the function (for a
	// union operand).
	Rest []Type
	// Option is the operand's type when it is an Option, and NoneOf the
	// Option type that `None` is returned as.
	Option *Sealed
	NoneOf *Sealed
}

TryInfo describes a `?` expression.

type Type

type Type interface {
	String() string
}

Type is a bork type as the checker models it. Constraints (`where`) are not modelled yet; they arrive with facts (milestone M1).

var (
	Int    Type = &Basic{name: "Int", kind: signedInt, bits: 64}
	Bool   Type = &Basic{name: "Bool"}
	String Type = &Basic{name: "String"}
	Rune   Type = &Basic{name: "Rune"}
	Bytes  Type = &Basic{name: "Bytes"}
	// Ok is the type of expressions that produce no meaningful value.
	Ok Type = &Basic{name: "Ok"}
	// Never is the type of expressions that never finish normally, such
	// as `return`. It can be used wherever any type is expected.
	Never Type = &Basic{name: "Never"}
	// Scope is the type of a scope (`scope s { ... }`): resources are
	// opened in a scope, and closed when it closes.
	Scope Type = &Basic{name: "Scope"}
	// OwnedScope is the type of an owned child scope (openScope): the
	// right to end it, which is passed on, never copied (see owners.go).
	OwnedScope Type = &Basic{name: "OwnedScope"}
	// Invalid marks an expression that already failed to type-check, to
	// avoid cascades of follow-up errors.
	Invalid Type = &Basic{name: "invalid"}

	// Sized numeric types. Int is Int64, and Float is Float64.
	Int8    Type = &Basic{name: "Int8", kind: signedInt, bits: 8}
	Int16   Type = &Basic{name: "Int16", kind: signedInt, bits: 16}
	Int32   Type = &Basic{name: "Int32", kind: signedInt, bits: 32}
	Uint8   Type = &Basic{name: "Uint8", kind: unsignedInt, bits: 8}
	Uint16  Type = &Basic{name: "Uint16", kind: unsignedInt, bits: 16}
	Uint32  Type = &Basic{name: "Uint32", kind: unsignedInt, bits: 32}
	Uint64  Type = &Basic{name: "Uint64", kind: unsignedInt, bits: 64}
	Float32 Type = &Basic{name: "Float32", kind: floatNum, bits: 32}
	Float   Type = &Basic{name: "Float", kind: floatNum, bits: 64}
)

func EditorDeclaredType added in v0.0.22

func EditorDeclaredType(info *Info, decl *syntax.TypeDecl) Type

func EditorType added in v0.0.4

func EditorType(info *Info, from *Package, typ *syntax.TypeExpr) Type

EditorType resolves written type syntax with the compiler's normal package, alias and generic rules. Invalid or inaccessible types return Invalid.

func EditorWrittenType added in v0.0.22

func EditorWrittenType(info *Info, pos diag.Pos) Type

EditorWrittenType uses recorded compiler resolution at the written name.

func TypeArgs

func TypeArgs(t Type) []Type

TypeArgs is a generic type's type arguments; for the generic type itself (inside its own declaration), its parameters.

type TypeParam

type TypeParam struct {
	Name string
	Decl *syntax.TypeParam
	// Bounds lists the classes the type must have instances of.
	Bounds []*Class
	// contains filtered or unexported fields
}

TypeParam is a type parameter of a generic function: `T` in `fn first[T](xs: List[T]): Option[T]`. Inside the function it stands for any type, and callers' arguments decide which.

func (*TypeParam) HasBound

func (t *TypeParam) HasBound(class *Class) bool

HasBound reports whether the type parameter is bounded by class.

func (*TypeParam) String

func (t *TypeParam) String() string

type TypeReference

type TypeReference struct {
	Pos        diag.Pos
	Name       string
	Type       Type
	Definition *diag.Pos
}

type Unary

type Unary struct {
	Op syntax.Kind
	X  Expr
	// contains filtered or unexported fields
}

Unary is `-x` or `!x`.

func (*Unary) Pos

func (e *Unary) Pos() diag.Pos

func (*Unary) TokenPos

func (e *Unary) TokenPos() diag.Pos

func (*Unary) Type

func (e *Unary) Type() Type

type Union

type Union struct {
	Members []Type
}

Union is `A | B | ...`. Members are kept in written order, because `?` keeps the leftmost member. Members are never unions themselves (nested unions are flattened) and never repeat.

func (*Union) String

func (u *Union) String() string

type UnmockedPath

type UnmockedPath struct {
	Pos    diag.Pos
	Funcs  []*Func
	InMock *Func
}

UnmockedPath is how a test reaches, unmocked, a function that does an effect in Go code: the call in the test, and the functions from there to it (the last). InMock is the target of the mock whose body makes the call, if one does.

type Var

type Var struct {
	PackageBinding *PackageBinding

	Sibling     *Field
	Unvalidated bool
	// Label describes a compiler-generated variable in diagnostics.
	Label string
	Name  string
	// GoName is the variable's name in the generated Go, when it is not
	// Name (an ambient value's binding or hidden parameter).
	GoName string
	Pos    diag.Pos
	Type   Type
	Kind   VarKind
	// Index is a parameter's position among its function's (or
	// lambda's, or rule's) parameters.
	Index int
	// Let is a VarLet's binding.
	Let *Let
	// Source is where a VarPattern's value comes from.
	Source *VarSource
	// Need is the need a VarAmbient reads.
	Need *FuncNeed
	// Ambient is the ambient value a with binding (a VarLet) binds.
	Ambient *Ambient
	// Unused is set for a binding or pattern name that is never read.
	Unused bool
}

Var is a variable: a parameter, a binding, a name bound by a pattern, or a scope.

type VarKind

type VarKind int

VarKind says what declared a variable.

const (
	VarParam        VarKind = iota // a function's parameter, or a rule's variable
	VarLambdaParam                 // a lambda's parameter
	VarLet                         // a binding: name = value
	VarPattern                     // a name a match pattern binds
	VarLoop                        // an iteration binding
	VarScope                       // the scope of `scope s { ... }`
	VarAmbient                     // an ambient value a function needs
	VarDefaultField                // a computed default's synthetic sibling parameter
	VarMockHandle                  // a mock's call inspection handle
)

type VarRef

type VarRef struct {
	Var *Var
	// contains filtered or unexported fields
}

VarRef is a use of a variable.

func Reference

func Reference(v *Var) *VarRef

Reference gives a variable declaration a typed reference for code queries.

func (*VarRef) Pos

func (e *VarRef) Pos() diag.Pos

func (*VarRef) TokenPos

func (e *VarRef) TokenPos() diag.Pos

func (*VarRef) Type

func (e *VarRef) Type() Type

type VarSource

type VarSource struct {
	Subject Expr
	Member  Type
	Path    string
	Field   *Field
}

VarSource is where a value bound by a match pattern comes from: the matched value, Subject, narrowed to Member (nil if not narrowed). A name bound inside the pattern (`Option.Some { value: v }`) is the part of that member at Path (".value"), the field Field.

type Variant

type Variant struct {
	Name        string
	Fields      []*Field
	Constraints []*Constraint
	Parent      *Sealed
	Index       int
}

Variant is one variant of a sealed type. It is not a type of its own: constructing a variant produces a value of the sealed type.

func EditorVisibleVariants added in v0.0.4

func EditorVisibleVariants(info *Info, from *Package, sealed *Sealed) []*Variant

EditorVisibleVariants applies the compiler's constructor/pattern visibility.

func (*Variant) Field

func (v *Variant) Field(name string) *Field

type VariantValue

type VariantValue struct {

	// ProofSource retains facts when a proof-only value narrows its source.
	ProofSource Expr
	Variant     *Variant
	Text        string
	Head        *ConstructorHead
	Constraints []*Constraint
	// contains filtered or unexported fields
}

VariantValue is a variant without fields: `Shape.Empty`. Text is the variant as written.

func (*VariantValue) Pos

func (e *VariantValue) Pos() diag.Pos

func (*VariantValue) TokenPos

func (e *VariantValue) TokenPos() diag.Pos

func (*VariantValue) Type

func (e *VariantValue) Type() Type

type Yield

type Yield struct {
	Value Expr
	Elem  Type
	// contains filtered or unexported fields
}

func (*Yield) Pos

func (e *Yield) Pos() diag.Pos

func (*Yield) TokenPos

func (e *Yield) TokenPos() diag.Pos

func (*Yield) Type

func (e *Yield) Type() Type

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL