backend

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const SemanticDocumentSchema = "r2many.semantic-program"

SemanticDocument is the stable interchange format for SemanticProgram. It intentionally contains no Canonical R text and can therefore move between a source frontend, a route decoder and every target backend without R carrying semantic state. The source-specific parser remains an adapter at the edge.

View Source
const SemanticDocumentVersion = 1

Variables

View Source
var Languages = []Language{
	{"go", "Go", ".go", "//"},
	{"rust", "Rust", ".rs", "//"},
	{"cpp", "C++", ".cpp", "//"},
	{"c", "C", ".c", "//"},
	{"python", "Python", ".py", "#"},
	{"zig", "Zig", ".zig", "//"},
	{"julia", "Julia", ".jl", "#"},
	{"nim", "Nim", ".nim", "#"},
	{"csharp", "C#", ".cs", "//"},
	{"java", "Java", ".java", "//"},
	{"kotlin", "Kotlin", ".kt", "//"},
	{"swift", "Swift", ".swift", "//"},
}
View Source
var PrimitiveMatrix = []PrimitiveSpec{}/* 702 elements not displayed */

Functions

func BackendCapabilities

func BackendCapabilities(name string) []string

func EmitSemantic

func EmitSemantic(target string, p *SemanticProgram) (string, error)

func EquivalentSemanticObservations

func EquivalentSemanticObservations(a, b SemanticObservation) bool

func HasBackend

func HasBackend(name string) bool

func HasFrontend

func HasFrontend(name string) bool

func NormalizeLanguage

func NormalizeLanguage(name string) string

func Run

func Run(src string) (string, error)

func RunSemantic

func RunSemantic(program *SemanticProgram) (string, error)

RunSemantic executes the semantic tree directly. It is used for IR round-trip equivalence checks and never reconstructs source text.

func RuntimeSource

func RuntimeSource(target string) (string, error)

RuntimeSource returns the actual support code embedded in generated programs. It does not contain a compiler or an external language installation.

func SupportsCapability

func SupportsCapability(caps []string, capability string) bool

func Transpile

func Transpile(target, src string) (string, error)

func TranspileFrom

func TranspileFrom(source, target, src string) (string, error)

TranspileFrom retains argument-evaluation semantics when the canonical syntax originated in an eager source language rather than R.

func WalkSemanticDocument

func WalkSemanticDocument(doc *SemanticDocument, visitor SemanticVisitor) error

Types

type Arg

type Arg struct {
	Name    string
	Value   Expr
	Missing bool
}

type AssignStmt

type AssignStmt struct {
	Name, Op string
	Value    Expr
}

type BackendSpec

type BackendSpec struct {
	ID           string
	Aliases      []string
	Capabilities []string
	Dialects     []string
}

func Backends

func Backends() []BackendSpec

type BinaryExpr

type BinaryExpr struct {
	Op   string
	L, R Expr
}

type BlockStmt

type BlockStmt struct{ List []Stmt }

type BreakStmt

type BreakStmt struct{}

type CallExpr

type CallExpr struct {
	Fun   Expr
	Args  []Arg
	Eager bool // explicit call boundary, including decoded R force wrappers
}

type CapabilityResult

type CapabilityResult struct {
	Feature string           `json:"feature"`
	Backend string           `json:"backend"`
	Status  CapabilityStatus `json:"status"`
	Reason  string           `json:"reason,omitempty"`
}

CapabilityResult is a backend contract, not a success prediction. The caller can display it before emitting and refuse any non-exact policy.

func BackendCapability

func BackendCapability(feature, backend string) CapabilityResult

type CapabilityStatus

type CapabilityStatus string
const (
	CapabilityNative      CapabilityStatus = "native"
	CapabilityLowering    CapabilityStatus = "lowering"
	CapabilityEmulated    CapabilityStatus = "emulated"
	CapabilityUnsupported CapabilityStatus = "unsupported"
)

type Expr

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

type ExprStmt

type ExprStmt struct{ X Expr }

type ForStmt

type ForStmt struct {
	Name string
	Seq  Expr
	Body Stmt
}

type FrontendSpec

type FrontendSpec struct {
	ID           string
	Aliases      []string
	Extensions   []string
	Capabilities []string
	Dialects     []string
}

FrontendSpec and BackendSpec are declarative registries. They keep language selection, aliases, file extensions, dialects and feature boundaries out of growing switch statements. Their implementation remains local Go code; no CrossTL source is included.

func Frontends

func Frontends() []FrontendSpec

type FunctionExpr

type FunctionExpr struct {
	Params []Param
	Body   *BlockStmt
}

type FunctionFlowEvidence

type FunctionFlowEvidence struct {
	Name         string              `json:"name"`
	Entry        int                 `json:"entry"`
	Nodes        []string            `json:"nodes"`
	Always       matrixir.Matrix     `json:"always"`
	WhenTrue     matrixir.Matrix     `json:"when_true"`
	WhenFalse    matrixir.Matrix     `json:"when_false"`
	Reachable    matrixir.Vector     `json:"reachable"`
	Error        string              `json:"error,omitempty"`
	Cycles       matrixir.Vector     `json:"cycles"`
	StateMachine bool                `json:"state_machine"`
	Slots        []string            `json:"slots"`
	Reads        matrixir.Matrix     `json:"reads"`
	Writes       matrixir.Matrix     `json:"writes"`
	Defined      matrixir.Matrix     `json:"defined"`
	Initial      matrixir.Vector     `json:"initial"`
	Iterations   []IterationEvidence `json:"iterations,omitempty"`
}

FunctionFlowEvidence exposes the very matrices used by the generator, not a second graph reconstructed from emitted text. It is intended for audit tools.

func AnalyzeFunctionFlows

func AnalyzeFunctionFlows(canonical string) ([]FunctionFlowEvidence, error)

func AnalyzeSemanticFunctionFlows

func AnalyzeSemanticFunctionFlows(program *SemanticProgram) ([]FunctionFlowEvidence, error)

AnalyzeSemanticFunctionFlows is the semantic-IR entry point. The older string function above remains solely a compatibility adapter for callers that still have R text; no target generator needs that text as state.

type IdentExpr

type IdentExpr struct{ Name string }

type IfStmt

type IfStmt struct {
	Cond Expr
	Then Stmt
	Else Stmt
}

type IndexExpr

type IndexExpr struct {
	X      Expr
	Args   []Arg
	Double bool
}

type IterationEvidence

type IterationEvidence struct {
	Sequence        string          `json:"sequence_slot"`
	Position        string          `json:"position_slot"`
	Length          string          `json:"length_slot"`
	Element         string          `json:"element_slot"`
	Advance         matrixir.Matrix `json:"advance"`
	InitialPosition float64         `json:"initial_position"`
}

type IterationExpr

type IterationExpr struct {
	Kind  string
	Value Expr
}

IterationExpr is an internal intrinsic, never resolved as a user function. Snapshot normalizes null/scalar/vector to a private outer vector; size then operates on that vector. Element gathers use the existing IndexExpr node.

type Language

type Language struct {
	ID        string
	Name      string
	Extension string
	Comment   string
}

func ByID

func ByID(id string) (Language, bool)

type LiteralExpr

type LiteralExpr struct{ Kind, Text string }

type NextStmt

type NextStmt struct{}

type Param

type Param struct {
	Name    string
	Default Expr
}

type PrimitiveSpec

type PrimitiveSpec struct {
	TableIndex string
	Name       string
	Kernel     string
	Arity      string
}

func PrimitiveRoute

func PrimitiveRoute(target, name string) (PrimitiveSpec, bool)

type RepeatStmt

type RepeatStmt struct{ Body Stmt }

type ReturnStmt

type ReturnStmt struct{ X Expr }

type SemanticArgument

type SemanticArgument struct {
	Name    string              `json:"name,omitempty"`
	Missing bool                `json:"missing,omitempty"`
	Value   *SemanticExpression `json:"value,omitempty"`
}

type SemanticBinding

type SemanticBinding struct {
	ID         int    `json:"id"`
	Name       string `json:"name"`
	Scope      int    `json:"scope"`
	Mutable    bool   `json:"mutable"`
	Definition int    `json:"definition"`
	TypeOrigin string `json:"type_origin"`
}

type SemanticContracts

type SemanticContracts struct {
	Requires   []string `json:"requires,omitempty"`
	Ensures    []string `json:"ensures,omitempty"`
	Invariants []string `json:"invariants,omitempty"`
}

SemanticContracts state assertions made by a producer. They are data, not executable checks: backends must reject contracts they cannot preserve.

type SemanticDialect

type SemanticDialect struct {
	Name         string                     `json:"name"`
	Capabilities []string                   `json:"capabilities"`
	Operations   []SemanticDialectOperation `json:"operations"`
}

SemanticDialect keeps specialist domains out of the universal core. A backend may emit it only after declaring every required capability.

type SemanticDialectOperation

type SemanticDialectOperation struct {
	ID         string         `json:"id"`
	Kind       string         `json:"kind"`
	Attributes map[string]any `json:"attributes,omitempty"`
}

type SemanticDocument

type SemanticDocument struct {
	SchemaVersion int                  `json:"schema_version"`
	Schema        string               `json:"schema"`
	Evaluation    string               `json:"evaluation"`
	ValueModel    string               `json:"value_model"`
	IndexBase     int                  `json:"index_base"`
	Types         SemanticTypeContract `json:"type_contract"`
	Origin        SemanticOrigin       `json:"origin"`
	Metadata      map[string]string    `json:"metadata,omitempty"`
	Extensions    map[string]any       `json:"extensions,omitempty"`
	Contracts     SemanticContracts    `json:"contracts,omitempty"`
	Dialects      []SemanticDialect    `json:"dialects,omitempty"`
	Root          SemanticStatement    `json:"root"`
	Evidence      SemanticEvidence     `json:"evidence"`
}

type SemanticEffectSummary

type SemanticEffectSummary struct {
	Counts           map[string]int `json:"counts"`
	ConservativePure bool           `json:"conservative_pure"`
	Unknown          bool           `json:"unknown"`
}

SemanticEffectSummary is computed from the effect matrix. ConservativePure becomes true only when every observed effect is proven non-observable.

func SummarizeEffects

func SummarizeEffects(program *SemanticProgram) SemanticEffectSummary

type SemanticEvidence

type SemanticEvidence struct {
	Nodes        []SemanticNode        `json:"nodes"`
	TypeAxes     []string              `json:"type_axes"`
	EffectAxes   []string              `json:"effect_axes"`
	Types        matrixir.SparseMatrix `json:"types"`
	Effects      matrixir.SparseMatrix `json:"effects"`
	Syntax       matrixir.SparseMatrix `json:"syntax"`
	Control      matrixir.SparseMatrix `json:"control"`
	Data         matrixir.SparseMatrix `json:"data"`
	Binding      matrixir.SparseMatrix `json:"binding"`
	Order        matrixir.SparseMatrix `json:"evaluation_order"`
	CallModes    matrixir.SparseMatrix `json:"call_modes"`
	CallModeAxes []string              `json:"call_mode_axes"`
	Scope        matrixir.SparseMatrix `json:"scope_membership"`
	Scopes       []SemanticScope       `json:"scopes"`
	Bindings     []SemanticBinding     `json:"bindings"`
	Contract     matrixir.Vector       `json:"contract"`
	ContractAxes []string              `json:"contract_axes"`
}

type SemanticExpression

type SemanticExpression struct {
	ID          int                 `json:"id"`
	Kind        string              `json:"kind"`
	Scope       int                 `json:"scope"`
	Type        SemanticType        `json:"type,omitempty"`
	TypeOrigin  string              `json:"type_origin,omitempty"`
	Semantics   SemanticSemantics   `json:"semantics,omitempty"`
	Effects     []string            `json:"effects,omitempty"`
	Binding     *int                `json:"binding,omitempty"`
	Source      *SemanticSourceSpan `json:"source,omitempty"`
	Attributes  map[string]any      `json:"attributes,omitempty"`
	Extensions  map[string]any      `json:"extensions,omitempty"`
	Name        string              `json:"name,omitempty"`
	Operator    string              `json:"operator,omitempty"`
	LiteralKind string              `json:"literal_kind,omitempty"`
	Text        string              `json:"text,omitempty"`
	Left        *SemanticExpression `json:"left,omitempty"`
	Right       *SemanticExpression `json:"right,omitempty"`
	Value       *SemanticExpression `json:"value,omitempty"`
	Function    *SemanticFunction   `json:"function,omitempty"`
	Arguments   []SemanticArgument  `json:"arguments,omitempty"`
	DoubleIndex bool                `json:"double_index,omitempty"`
}

type SemanticField

type SemanticField struct {
	Name string       `json:"name"`
	Type SemanticType `json:"type"`
}

type SemanticFunction

type SemanticFunction struct {
	Parameters []SemanticParameter `json:"parameters"`
	Body       SemanticStatement   `json:"body"`
}

type SemanticNode

type SemanticNode struct {
	ID     int    `json:"id"`
	Kind   string `json:"kind"`
	Symbol string `json:"symbol,omitempty"`
	Scope  int    `json:"scope"`
}

type SemanticObservation

type SemanticObservation struct {
	Stdout  string                `json:"stdout"`
	Error   string                `json:"error,omitempty"`
	Effects SemanticEffectSummary `json:"effects"`
}

SemanticObservation is the deterministic observation available from the embedded semantic runtime. External native tests may extend this with files, state snapshots and process exit information.

func ObserveSemantic

func ObserveSemantic(program *SemanticProgram) SemanticObservation

type SemanticOrigin

type SemanticOrigin struct {
	SourceLanguage string   `json:"source_language"`
	SourceVersion  string   `json:"source_version,omitempty"`
	EntryPoint     string   `json:"entry_point"`
	Modules        []string `json:"modules"`
}

type SemanticParameter

type SemanticParameter struct {
	ID      int                 `json:"id"`
	Name    string              `json:"name"`
	Type    SemanticType        `json:"type,omitempty"`
	Passing string              `json:"passing,omitempty"`
	Default *SemanticExpression `json:"default,omitempty"`
}

type SemanticParameterVisitor

type SemanticParameterVisitor interface {
	EnterParameter(*SemanticParameter) error
}

type SemanticProgram

type SemanticProgram struct {
	Body       *BlockStmt           `json:"-"`
	Evaluation string               `json:"evaluation"`
	ValueModel string               `json:"value_model"`
	IndexBase  int                  `json:"index_base"`
	Types      SemanticTypeContract `json:"type_contract"`
	Origin     SemanticOrigin       `json:"origin"`
	Metadata   map[string]string    `json:"metadata,omitempty"`
	Extensions map[string]any       `json:"extensions,omitempty"`
	Contracts  SemanticContracts    `json:"contracts,omitempty"`
	Dialects   []SemanticDialect    `json:"dialects,omitempty"`
	Evidence   SemanticEvidence     `json:"evidence"`
}

SemanticProgram owns the executable tree. Canonical R is now a diagnostic serialization, not the only carrier of evaluation semantics. Numeric values here have the existing runtime's binary64 contract, NOT source integer-width equivalence. Unknown types/effects are represented explicitly in the matrices.

func DecodeGenerated

func DecodeGenerated(source, code string) (*SemanticProgram, bool, error)

DecodeGenerated reads the actual emitted program. Only an exact known runtime prefix may be removed; every remaining token must be decoded and reproduced. There is no original-source payload, comment recovery or cache. The shared emitter functions define the inverse operation templates.

func LowerMatrixActions

func LowerMatrixActions(source string, nodes []matrixir.CanonicalNode) (*SemanticProgram, error)

LowerMatrixActions is the common-subset frontend boundary. MatrixIR has already recognized the source grammar and selected normalized actions; this function consumes those actions rather than CanonicalProgram.R. The action payload is deliberately kept local to the frontend and never becomes a transport representation of Program.

This is a migration boundary, not a claim that every language already has a complete native parser. Source-specific lowerers can replace this function one language at a time without changing SemanticProgram or emitters.

func LowerMatrixEvents

func LowerMatrixEvents(source string, events []matrixir.CanonicalEvent) (*SemanticProgram, error)

LowerMatrixEvents consumes the ordered structural stream emitted by the source matrix adapter. It replaces the old CanonicalProgram.R handoff.

func NewSemanticProgram

func NewSemanticProgram(body *BlockStmt, evaluation string) *SemanticProgram

func ParseSemantic

func ParseSemantic(source, code string) (*SemanticProgram, error)

func ParseSemanticDocument

func ParseSemanticDocument(doc SemanticDocument) (*SemanticProgram, error)

func ParseSemanticJSON

func ParseSemanticJSON(data []byte) (*SemanticProgram, error)

func (*SemanticProgram) Document

func (p *SemanticProgram) Document() (SemanticDocument, error)

func (*SemanticProgram) MarshalSemanticJSON

func (p *SemanticProgram) MarshalSemanticJSON() ([]byte, error)

func (*SemanticProgram) RSource

func (p *SemanticProgram) RSource(enforce bool) (string, error)

RSource writes executable R syntax from the typed tree. In eager mode calls with user functions are handled by the explicit call-boundary lowering below.

type SemanticScope

type SemanticScope struct {
	ID     int    `json:"id"`
	Kind   string `json:"kind"`
	Parent int    `json:"parent"`
}

type SemanticSemantics

type SemanticSemantics struct {
	Operation       string `json:"operation,omitempty"`
	Dispatch        string `json:"dispatch,omitempty"`
	Overflow        string `json:"overflow,omitempty"`
	EvaluationOrder string `json:"evaluation_order,omitempty"`
	ShortCircuit    bool   `json:"short_circuit,omitempty"`
	IndexBase       int    `json:"index_base,omitempty"`
	NegativeIndex   string `json:"negative_index,omitempty"`
	OutOfBounds     string `json:"out_of_bounds,omitempty"`
	Slicing         string `json:"slicing,omitempty"`
	ErrorModel      string `json:"error_model,omitempty"`
	Confidence      string `json:"confidence,omitempty"`
}

type SemanticSourceSpan

type SemanticSourceSpan struct {
	File        string `json:"file,omitempty"`
	StartOffset int    `json:"start_offset,omitempty"`
	EndOffset   int    `json:"end_offset,omitempty"`
	StartLine   int    `json:"start_line,omitempty"`
	StartColumn int    `json:"start_column,omitempty"`
	EndLine     int    `json:"end_line,omitempty"`
	EndColumn   int    `json:"end_column,omitempty"`
}

type SemanticStatement

type SemanticStatement struct {
	ID         int                 `json:"id"`
	Kind       string              `json:"kind"`
	Scope      int                 `json:"scope"`
	Type       SemanticType        `json:"type,omitempty"`
	TypeOrigin string              `json:"type_origin,omitempty"`
	Semantics  SemanticSemantics   `json:"semantics,omitempty"`
	Effects    []string            `json:"effects,omitempty"`
	Source     *SemanticSourceSpan `json:"source,omitempty"`
	Attributes map[string]any      `json:"attributes,omitempty"`
	Extensions map[string]any      `json:"extensions,omitempty"`
	Name       string              `json:"name,omitempty"`
	AssignOp   string              `json:"assign_op,omitempty"`
	Expression *SemanticExpression `json:"expression,omitempty"`
	Condition  *SemanticExpression `json:"condition,omitempty"`
	Sequence   *SemanticExpression `json:"sequence,omitempty"`
	Then       *SemanticStatement  `json:"then,omitempty"`
	Else       *SemanticStatement  `json:"else,omitempty"`
	Body       *SemanticStatement  `json:"body,omitempty"`
	Statements []SemanticStatement `json:"statements,omitempty"`
}

type SemanticType

type SemanticType struct {
	Kind        string          `json:"kind,omitempty"`
	Name        string          `json:"name,omitempty"`
	Bits        int             `json:"bits,omitempty"`
	Signed      *bool           `json:"signed,omitempty"`
	IEEE754     bool            `json:"ieee754,omitempty"`
	Element     *SemanticType   `json:"element,omitempty"`
	Key         *SemanticType   `json:"key,omitempty"`
	Value       *SemanticType   `json:"value,omitempty"`
	Parameters  []SemanticType  `json:"parameters,omitempty"`
	Result      *SemanticType   `json:"result,omitempty"`
	Fields      []SemanticField `json:"fields,omitempty"`
	Length      int             `json:"length,omitempty"`
	Rows        int             `json:"rows,omitempty"`
	Columns     int             `json:"columns,omitempty"`
	Constraints []string        `json:"constraints,omitempty"`
	Nullable    string          `json:"nullable,omitempty"`
	Ownership   string          `json:"ownership,omitempty"`
	Lifetime    string          `json:"lifetime,omitempty"`
	TypeOrigin  string          `json:"type_origin,omitempty"`
}

SemanticType is recursive so no JSON number has to carry type information. The textual literal value remains exact even for values JSON cannot represent.

type SemanticTypeContract

type SemanticTypeContract struct {
	SchemaVersion int    `json:"schema_version"`
	Numeric       string `json:"numeric"`
	IntegerWidth  string `json:"integer_width"`
	Text          string `json:"text"`
	Truth         string `json:"truth"`
	Null          string `json:"null"`
	Collection    string `json:"collection"`
	Pointer       string `json:"pointer"`
	Ownership     string `json:"ownership"`
	ABI           string `json:"abi"`
}

SemanticTypeContract is deliberately explicit about what is not yet known. It is part of the language-neutral program contract, not a target profile.

type SemanticVisitor

type SemanticVisitor interface {
	EnterStatement(*SemanticStatement) error
	LeaveStatement(*SemanticStatement) error
	EnterExpression(*SemanticExpression) error
	LeaveExpression(*SemanticExpression) error
}

SemanticVisitor provides deterministic pre-order traversal of a complete SemanticDocument. Visitors can analyze, validate, optimize or annotate a document without embedding target-specific logic in AST node types.

type Stmt

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

type UnaryExpr

type UnaryExpr struct {
	Op string
	X  Expr
}

type WhileStmt

type WhileStmt struct {
	Cond Expr
	Body Stmt
}

Jump to

Keyboard shortcuts

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