codegen

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: Apache-2.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package codegen compiles the value subset of SysML v2 calcs to native code; see docs/project/native-compilation.md for the subset and its semantics.

Index

Constants

View Source
const CCompilerEnvVar = "OPENSYSML_CC"

CCompilerEnvVar names the C compiler TargetC drives (default: cc).

View Source
const GoCommandEnvVar = "OPENSYSML_GO"

GoCommandEnvVar names the go command TargetGo drives (default: go).

Variables

View Source
var (
	MultAny = Mult{Lower: 0, Upper: -1}
	MultOne = Mult{Lower: 1, Upper: 1}
)

MultAny admits every count; MultOne is `[1]`.

View Source
var CFlags = []string{"-O3", "-flto", "-ffp-contract=off", "-std=gnu11", "-Wall", "-Wextra", "-Wno-unused-function", "-Wno-unused-parameter"}

CFlags are the C compiler options; the prelude's explicit checks keep -O3 safe, and no contraction keeps every Real operation rounded as the interpreter rounds it.

View Source
var ErrUnsupported = errors.New("not compilable")

ErrUnsupported reports notation outside the compiled subset. The message names the construct so the model can be adjusted or run interpreted.

Functions

func Build

func Build(p *Program, target Target, output string) error

Build compiles program for target into the executable at output, leaving the generated source beside it as output plus the target's extension.

func EmitC

func EmitC(w io.Writer, p *Program, withMain bool) error

EmitC writes program as a self-contained C translation unit, with a main that reads argv and prints the result when withMain is set (errors: status 1, stderr).

func EmitGo

func EmitGo(w io.Writer, p *Program) error

EmitGo writes program as a self-contained Go main package whose command line and output match the C program's.

func Source

func Source(p *Program, target Target) ([]byte, error)

Source renders program for target, as a complete program with a main.

func SourceExtension

func SourceExtension(target Target) string

SourceExtension is the file extension of target's source.

Types

type Arg

type Arg struct {
	Param int
	Value Expr
}

Arg is one supplied argument of a Call.

type Assign

type Assign struct {
	Name  string
	Range Range
	Value Expr
}

Assign writes a body-local variable or parameter; a scalar is checked against Range, a collection by the Checked or ToOne that Value is.

type Binary

type Binary struct {
	Op   ast.OperatorKind
	L, R Expr
	T    Type
}

Binary applies an arithmetic, comparison or logical operator. Operands are already coerced to a common type; T is the result type.

func (Binary) Type

func (b Binary) Type() Type

type BoolLit

type BoolLit struct{ Value bool }

func (BoolLit) Type

func (BoolLit) Type() Type

type Call

type Call struct {
	Fn   *Func
	Args []Arg
}

Call invokes another compiled function, arguments coerced to parameter types. Call invokes Fn. Args are evaluated in source order, each binding the parameter at Param; a parameter named twice takes the later value.

func (Call) Type

func (c Call) Type() Type

type Checked

type Checked struct {
	X      Expr
	M      Mult
	R      Range
	Unique bool
	Where  string
}

Checked binds a collection to a feature of multiplicity M and range R at Where, refusing a repeated element when Unique, failing as the interpreter's binding does.

func (Checked) Type

func (c Checked) Type() Type

type Coalesce

type Coalesce struct {
	L, R Expr
	T    Type
}

Coalesce is `L ?? R`: L unless it is null. Both are of collection type T.

func (Coalesce) Type

func (c Coalesce) Type() Type

type Compiler

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

Compiler lowers calc definitions to the codegen IR. One Compiler compiles one Program; the functions it produces are shared across calls within it.

func New

func New(model *semantics.Model, resolver *resolve.Resolver) *Compiler

New returns a Compiler resolving names through resolver and typing through model.

func (*Compiler) Compile

func (c *Compiler) Compile(entry *symbols.Symbol) (*Program, error)

Compile compiles entry and every calc it invokes, transitively.

type Cond

type Cond struct {
	C, Then, Else Expr
	T             Type
}

Cond is `if c ? a else b`, both branches of type T.

func (Cond) Type

func (c Cond) Type() Type

type Declare

type Declare struct {
	Name  string
	T     Type
	Range Range
	Init  Expr
}

Declare introduces a body-local variable with its initial value, null (a collection) when Init is nil. A scalar Init is checked against Range, a collection by the Checked or ToOne that Init is, as an Assign is.

type Expr

type Expr interface {
	Type() Type
}

Expr is a typed expression.

type Fold

type Fold struct {
	Op   SeqOp
	Seq  Expr
	Body Lambda
	T    Type
}

Fold applies a body operation (seqops.go) over the elements of Seq; T is its result type.

func (Fold) Type

func (f Fold) Type() Type

type ForEach

type ForEach struct {
	Var  string
	Seq  Expr
	Body []Stmt
}

ForEach runs Body once per element of Seq, bound to Var; a bare scalar is not iterable and fails, as the interpreter's `for` does.

type Framed added in v0.8.0

type Framed struct{ X Expr }

Framed evaluates X as the inlined body of a library calc: one frame deeper against the recursion budget, left once X has answered.

func (Framed) Type added in v0.8.0

func (f Framed) Type() Type

type Func

type Func struct {
	Name   string // qualified SysML name
	Ident  string // identifier valid in every target language
	Params []Param
	Result Type
	// ResultRange is checked on every return; a collection result's
	// multiplicity is checked by the Checked the return wraps.
	ResultRange Range
	Body        []Stmt
}

Func is one compiled calculation.

type If

type If struct {
	Cond Expr
	Then []Stmt
	Else []Stmt
}

If runs Then or Else on a Boolean condition.

type Index

type Index struct {
	Seq, I Expr
}

Index is `Seq#(I)`, one-based over the elements of Seq; I is an Integer.

func (Index) Type

func (i Index) Type() Type

type IntLit

type IntLit struct{ Value int64 }

IntLit, RealLit and BoolLit are literals.

func (IntLit) Type

func (IntLit) Type() Type

type Lambda

type Lambda struct {
	Params []Param
	Body   Expr
}

Lambda is a body expression `{in x; …}`: Params are bound to the operation's per-element arguments in order, then Body is evaluated; locals the body declares are inlined into Body where it names them.

type Let

type Let struct {
	Name  string
	Value Expr
	In    Expr
}

Let evaluates Value into the temporary Name, then In, which reads it as a Var.

func (Let) Type

func (l Let) Type() Type

type LibCall

type LibCall struct {
	Op   LibOp
	Args []Arg
}

LibCall applies a library function operation (library.go); Args bind its operands as a Call's do, each coerced to the operand's type.

func (LibCall) Type

func (l LibCall) Type() Type

type LibOp

type LibOp int

LibOp is one library function operation over scalars, chosen from the function the model calls and the types of its operands (runtime/library_functions.go).

const (
	LibSqrt LibOp = iota
	LibAbsReal
	LibAbsInt
	LibFloor
	LibRound
	LibMaxReal
	LibMinReal
	LibMaxInt
	LibMinInt
	LibMaxNatural
	LibMinNatural
	LibIsZero
	LibIsUnit
	LibSin
	LibCos
	LibTan
	LibCot
	LibArcsin
	LibArccos
	LibArctan
	LibDeg
	LibRad
	LibExp
	LibLn
	LibLog
	LibAtan2
)

func (LibOp) Operands

func (op LibOp) Operands() []Type

Operands is the types the operation's operands are coerced to.

func (LibOp) Result

func (op LibOp) Result() Type

Result is the operation's result type.

func (LibOp) String

func (op LibOp) String() string

type Mult

type Mult struct {
	Lower, Upper int64
}

Mult is a declared multiplicity, checked on the count of values a collection feature is bound to. Upper is negative for an unbounded feature.

func (Mult) Admits

func (m Mult) Admits(n int64) bool

Admits reports whether a value count n satisfies m.

type NullLit

type NullLit struct{ T Type }

NullLit is `null`, the empty value of collection type T (or TypeNull).

func (NullLit) Type

func (n NullLit) Type() Type

type Param

type Param struct {
	Name   string
	Type   Type
	Range  Range
	Mult   Mult
	Unique bool
}

Param is one input parameter; Range and, for a collection, Mult and Unique are checked on entry.

type Program

type Program struct {
	Funcs       []*Func
	Entry       *Func
	Collections bool
}

Program is a set of compiled functions with one entry point. Collections is set when any function handles a collection, which the emitters' element budget and per-statement release then track.

type Range

type Range int

Range narrows an Integer to the values its declared library subtype admits: Natural the non-negative Integers, Positive those above zero.

const (
	RangeAny Range = iota
	RangeNatural
	RangePositive
)

func (Range) Lower added in v0.8.0

func (r Range) Lower() int64

Lower is the least Integer the range admits.

func (Range) String

func (r Range) String() string

String is the library type name the range comes from; empty for RangeAny.

type RangeExpr

type RangeExpr struct{ Lo, Hi Expr }

RangeExpr is `Lo..Hi`, the Integers from Lo to Hi, empty when Lo > Hi.

func (RangeExpr) Type

func (RangeExpr) Type() Type

type RealLit

type RealLit struct{ Value float64 }

func (RealLit) Type

func (RealLit) Type() Type

type Return

type Return struct{ Value Expr }

Return answers the function's result.

type Sample added in v0.8.0

type Sample struct {
	Dom, Rng string
	Seq      Expr
	Body     Lambda
}

Sample takes `Sample(f, Seq)` one frame deeper: Dom gets the domain values, Rng Body at each in order, every sample charged as the interpreter's pair is.

func (Sample) DomType added in v0.8.0

func (s Sample) DomType() Type

DomType and RngType are the collection types of Dom and Rng.

func (Sample) RngType added in v0.8.0

func (s Sample) RngType() Type

type Sampled added in v0.8.0

type Sampled struct {
	S  Sample
	In Expr
}

Sampled takes the sample S for the duration of In, which reads S.Dom and S.Rng as Vars.

func (Sampled) Type added in v0.8.0

func (s Sampled) Type() Type

type SeqCall

type SeqCall struct {
	Op   SeqOp
	Args []Expr
	T    Type
}

SeqCall applies a collection operation (seqops.go) to operands in parameter order; T is its result type.

func (SeqCall) Type

func (s SeqCall) Type() Type

type SeqEq

type SeqEq struct {
	L, R  Expr
	Neq   bool
	Ident bool
}

SeqEq is `==` (Neq negated) over collections of one type: same shape, same elements in order. Ident is `===`, which no coercion precedes.

func (SeqEq) Type

func (SeqEq) Type() Type

type SeqLit

type SeqLit struct {
	Elems []Expr
	T     Type
}

SeqLit is `(a, b, …)`: the elements of each collection operand, in order, as a sequence of type T.

func (SeqLit) Type

func (s SeqLit) Type() Type

type SeqOp

type SeqOp int

SeqOp is a collection operation of the Kernel Function Library, computed by the generated runtime as internal/core/runtime/collections.go computes it.

const (
	SeqInvalid SeqOp = iota
	SeqSize
	SeqIsEmpty
	SeqNotEmpty
	SeqIncludes
	SeqIncludesOnly
	SeqExcludes
	SeqEquals
	SeqSame
	SeqUnion
	SeqIntersection
	SeqIncluding
	SeqIncludingAt
	SeqExcluding
	SeqSubsequence
	SeqExcludingAt
	SeqHead
	SeqTail
	SeqLast
	SeqAllTrue
	SeqAnyTrue
	SeqSum
	SeqProduct
	// Body operations: the last parameter is a body applied per element.
	SeqSelect
	SeqSelectOne
	SeqReject
	SeqCollect
	SeqForAll
	SeqExists
	SeqReduce
	SeqMinimize
	SeqMaximize
)

func (SeqOp) Body

func (op SeqOp) Body() int

Body is the number of parameters of the body the operation applies, 0 for a value operation.

func (SeqOp) Name

func (op SeqOp) Name() string

Name is the qualified library function the operation computes.

func (SeqOp) String

func (op SeqOp) String() string

String is Name without its library, the way the runtime's diagnostics name it.

type Stmt

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

Stmt is a statement of a function body.

type Target

type Target string

Target is a code generation backend.

const (
	// TargetC emits C and builds it with the system C compiler.
	TargetC Target = "c"
	// TargetGo emits Go and builds it with the Go toolchain.
	TargetGo Target = "go"
)

func Targets

func Targets() []Target

Targets lists the backends in the order they are documented.

type ToMany

type ToMany struct{ X Expr }

ToMany views a scalar as the collection holding it, as the interpreter does.

func (ToMany) Type

func (t ToMany) Type() Type

type ToOne

type ToOne struct {
	X        Expr
	Where    string
	Fail     string
	Bare     bool
	Other    Expr
	OtherOne string
}

ToOne is the one scalar X holds; Where names a `[1]` binding, else Fail's %s is the shape found ("a sequence", bare "sequence") and Other's a second %s.

func (ToOne) Type

func (t ToOne) Type() Type

type ToReal

type ToReal struct{ X Expr }

ToReal widens an Integer to a Real; over a collection, every element.

func (ToReal) Type

func (t ToReal) Type() Type

type Type

type Type int

Type is a type of the compiled subset: a scalar, or a collection of scalars. A collection value is the interpreter's dynamic view of a multi-valued feature: null, one bare scalar, or a sequence of any length (its shape).

const (
	TypeInvalid Type = iota
	TypeInt          // Integer and its subtypes, int64 with reported overflow
	TypeReal         // Real and Rational, IEEE 754 binary64
	TypeBool
	TypeNull    // `null` before context fixes its collection type
	TypeSeqInt  // collection of Integers
	TypeSeqReal // collection of Reals
	TypeSeqBool // collection of Booleans
)

func (Type) Elem

func (t Type) Elem() Type

Elem is the scalar type of t's values: t itself for a scalar.

func (Type) Many

func (t Type) Many() bool

Many reports whether t is a collection type.

func (Type) Scalar

func (t Type) Scalar() bool

Scalar reports whether t is exactly one Integer, Real or Boolean.

func (Type) Seq

func (t Type) Seq() Type

Seq is the collection type over t's scalar type.

func (Type) String

func (t Type) String() string

type Unary

type Unary struct {
	Op ast.OperatorKind
	X  Expr
	T  Type
}

Unary applies `-`, `+` or `not`.

func (Unary) Type

func (u Unary) Type() Type

type UnsupportedError

type UnsupportedError struct {
	Calc string
	What string
}

UnsupportedError is an ErrUnsupported with the construct and calc it was met in.

func (*UnsupportedError) Error

func (e *UnsupportedError) Error() string

func (*UnsupportedError) Unwrap

func (e *UnsupportedError) Unwrap() error

type Var

type Var struct {
	Name string
	T    Type
}

Var reads a parameter or a body-local variable.

func (Var) Type

func (v Var) Type() Type

type While

type While struct {
	Cond  Expr
	Until Expr
	Body  []Stmt
}

While runs Body while Cond holds; Until, if set, is tested after each pass and stops the loop when it holds.

Jump to

Keyboard shortcuts

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