compiler

package
v0.26.7 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// RugoExt is the preferred file extension for Rugo source files.
	RugoExt = ".rugo"
	// DeprecatedExt is the old file extension, still supported but deprecated.
	DeprecatedExt = ".rg"
)

Variables

View Source
var Sources embed.FS

Sources embeds all non-test Go source files and templates needed to reconstruct the compiler package in an external module cache.

Functions

func FindLocalEntryPoint added in v0.11.0

func FindLocalEntryPoint(dir string) (string, error)

FindLocalEntryPoint resolves the entry point Rugo file within a local directory. Resolution order: <dirname>.rugo → <dirname>.rg → main.rugo → main.rg → sole Rugo file.

func FindRugoFile added in v0.12.0

func FindRugoFile(basePath string) string

FindRugoFile looks for a Rugo source file, preferring .rugo over .rg. Given a base path without extension, returns the path if found, empty string otherwise.

func IsRugoBenchFile added in v0.12.0

func IsRugoBenchFile(name string) bool

IsRugoBenchFile returns true if the filename is a Rugo benchmark file (_bench.rugo or _bench.rg).

func IsRugoFile added in v0.12.0

func IsRugoFile(name string) bool

IsRugoFile returns true if the filename has a Rugo extension (.rugo or .rg).

func IsRugoTestFile added in v0.12.0

func IsRugoTestFile(name string) bool

IsRugoTestFile returns true if the filename is a Rugo test file (_test.rugo or _test.rg).

func PrintGoFile added in v0.25.0

func PrintGoFile(f *GoFile) string

PrintGoFile serializes a GoFile tree to formatted Go source code.

func TrimRugoExt added in v0.12.0

func TrimRugoExt(name string) string

TrimRugoExt removes the Rugo file extension (.rugo or .rg) from a filename.

func UndefinedIdentCheck added in v0.25.0

func UndefinedIdentCheck(sourceFile string) ast.Check

UndefinedIdentCheck returns a Check that reports undefined identifier references.

func WalkExprs added in v0.15.0

func WalkExprs(prog *ast.Program, fn func(ast.Expr) bool) bool

WalkExprs traverses the entire AST and calls fn on every ast.Expr node. Returns true as soon as fn returns true for any expression.

func WalkStmts added in v0.15.0

func WalkStmts(prog *ast.Program, fn func(ast.Statement) bool)

WalkStmts traverses all statements in a ast.Program, calling fn for each. If fn returns false, children of that statement are not visited. Recurses into block bodies (ast.FuncDef, ast.TestDef, ast.BenchDef, ast.IfStmt, ast.WhileStmt, ast.ForStmt).

func WarnDeprecatedExt added in v0.12.0

func WarnDeprecatedExt(filename string)

WarnDeprecatedExt prints a deprecation warning to stderr if the file uses the old .rg extension.

Types

type CapturedOutput added in v0.17.0

type CapturedOutput struct {
	Output   string
	ExitCode int
}

CapturedOutput holds the result of RunCapture.

type CompileResult

type CompileResult struct {
	GoSource   string
	Program    *ast.Program
	SourceFile string         // original source filename
	Sandbox    *SandboxConfig // sandbox config (nil = no sandbox)
	// GoModuleRequires maps Go module paths to local cache directories
	// for Go modules discovered via require. Used by go.mod generation.
	GoModuleRequires map[string]string
}

CompileResult holds the output of a compilation.

type Compiler

type Compiler struct {
	// BaseDir is the directory of the main source file (for resolving requires).
	BaseDir string
	// TestMode enables test harness generation (rats blocks are included).
	// When false (default), rats blocks are silently skipped during codegen.
	TestMode bool
	// ModuleDir overrides the default module cache directory (~/.rugo/modules).
	// Used for testing. When empty, the default is used.
	ModuleDir string
	// Frozen errors if the lock file is stale or a new dependency is resolved.
	Frozen bool
	// ShowWarnings enables bridge skipping warnings during compilation.
	// When false (default), warnings about unbridgeable functions are suppressed.
	ShowWarnings bool
	// Sandbox, when non-nil, overrides any sandbox directive in the script.
	// Populated by CLI flags (--sandbox --ro, --rw, etc.).
	Sandbox *SandboxConfig
	// Resolver overrides the default remote resolver. When set, the compiler
	// uses this resolver instead of creating one. Used by mod tidy to share
	// a single resolver across multiple compilations.
	Resolver *remote.Resolver
	// contains filtered or unexported fields
}

Compiler orchestrates the full compilation pipeline.

func (*Compiler) Build

func (c *Compiler) Build(filename, output string) error

Build compiles a Rugo source file to a native binary.

func (*Compiler) Compile

func (c *Compiler) Compile(filename string) (*CompileResult, error)

Compile reads a Rugo source file, resolves requires, and produces Go source.

func (*Compiler) Emit

func (c *Compiler) Emit(filename string) (string, error)

Emit compiles a Rugo source file and outputs the Go source.

func (*Compiler) ParseFile added in v0.15.0

func (c *Compiler) ParseFile(filename string) (*ast.Program, error)

ParseFile reads a Rugo source file and parses it into a ast.Program AST without compiling to Go. Useful for tooling such as linters, formatters, and refactoring tools that need AST access without full compilation.

func (*Compiler) ParseSource added in v0.15.0

func (c *Compiler) ParseSource(source, name string) (*ast.Program, error)

ParseSource parses raw Rugo source code into a ast.Program AST without compiling to Go. The name parameter is used for error messages.

func (*Compiler) Run

func (c *Compiler) Run(filename string, extraArgs ...string) error

Run compiles and runs a Rugo source file, passing extraArgs to the compiled binary.

func (*Compiler) RunCapture added in v0.17.0

func (c *Compiler) RunCapture(filename string, extraArgs ...string) (*CapturedOutput, error)

RunCapture compiles and runs a Rugo source file, capturing combined stdout/stderr output instead of passing it through. Returns the captured output and exit code. A non-zero exit code is not treated as an error.

type FuncTypeInfo

type FuncTypeInfo struct {
	ParamTypes  []RugoType
	ReturnType  RugoType
	HasDefaults bool // true if the function has params with default values (variadic signature)
}

FuncTypeInfo holds the inferred signature for a function.

type GoAssignStmt added in v0.25.0

type GoAssignStmt struct {
	Target string // variable name
	Op     string // ":=" or "="
	Value  GoExpr
}

GoAssignStmt represents: target op value (e.g., x := expr, x = expr)

type GoBinaryExpr added in v0.25.0

type GoBinaryExpr struct {
	Left  GoExpr
	Op    string
	Right GoExpr
}

GoBinaryExpr represents: left op right

type GoBlankLine added in v0.25.0

type GoBlankLine struct{}

GoBlankLine emits a blank line in the output.

type GoBoolLit added in v0.25.0

type GoBoolLit struct {
	Value bool
}

GoBoolLit represents a boolean literal.

type GoBreakStmt added in v0.25.0

type GoBreakStmt struct{}

GoBreakStmt represents: break

type GoCallExpr added in v0.25.0

type GoCallExpr struct {
	Func string
	Args []GoExpr
}

GoCallExpr represents a function call: func(args...)

type GoCase added in v0.25.0

type GoCase struct {
	Values []GoExpr
	Body   []GoStmt
}

GoCase represents one case in a switch statement.

type GoCastExpr added in v0.25.0

type GoCastExpr struct {
	Type  string
	Value GoExpr
}

GoCastExpr represents a type conversion: type(value)

type GoComment added in v0.25.0

type GoComment struct {
	Text string
}

GoComment represents: // text

type GoContinueStmt added in v0.25.0

type GoContinueStmt struct{}

GoContinueStmt represents: continue

type GoDecl added in v0.25.0

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

GoDecl is a top-level declaration (function, variable, raw code).

type GoDeferStmt added in v0.25.0

type GoDeferStmt struct {
	Body []GoStmt
}

GoDeferStmt represents: defer func() { body }()

type GoDotExpr added in v0.25.0

type GoDotExpr struct {
	Object GoExpr
	Field  string
}

GoDotExpr represents field access: obj.Field

type GoElseIf added in v0.25.0

type GoElseIf struct {
	Cond GoExpr
	Body []GoStmt
}

GoElseIf represents one else-if branch.

type GoExpr added in v0.25.0

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

GoExpr is an expression in the Go output AST.

type GoExprStmt added in v0.25.0

type GoExprStmt struct {
	Expr GoExpr
}

GoExprStmt is an expression used as a statement.

type GoFile added in v0.25.0

type GoFile struct {
	Package string
	Imports []GoImport
	Decls   []GoDecl // top-level declarations (vars, funcs, runtime)
	Init    []GoStmt // main() or test/bench harness body
}

GoFile represents a complete Go source file.

type GoFloatLit added in v0.25.0

type GoFloatLit struct {
	Value string
}

GoFloatLit represents a float literal.

type GoFmtSprintf added in v0.25.0

type GoFmtSprintf struct {
	Format string
	Args   []GoExpr
}

GoFmtSprintf represents: fmt.Sprintf(format, args...)

type GoForRangeStmt added in v0.25.0

type GoForRangeStmt struct {
	Key        string // "_" if unused
	Value      string // empty for single-var range
	Collection GoExpr
	Body       []GoStmt
}

GoForRangeStmt represents: for key, value := range collection { body }

type GoForStmt added in v0.25.0

type GoForStmt struct {
	Init string // empty for while-style: for cond { }
	Cond string
	Post string
	Body []GoStmt
}

GoForStmt represents: for [init]; [cond]; [post] { body }

type GoFuncDecl added in v0.25.0

type GoFuncDecl struct {
	Name   string
	Params []GoParam
	Return string   // empty for no return type
	Body   []GoStmt // nil for declaration-only (not used, but complete)
}

GoFuncDecl represents: func name(params) returnType { body }

type GoGoStmt added in v0.25.0

type GoGoStmt struct {
	Body []GoStmt
}

GoGoStmt represents: go func() { body }()

type GoIIFEExpr added in v0.25.0

type GoIIFEExpr struct {
	ReturnType string   // e.g., "interface{}", "(r interface{})"
	Body       []GoStmt // statements inside the IIFE
	Result     GoExpr   // final return expression; nil to omit
}

GoIIFEExpr represents a self-calling function: func() T { body; return expr }()

type GoIdentExpr added in v0.25.0

type GoIdentExpr struct {
	Name string
}

GoIdentExpr represents a Go identifier reference.

type GoIfStmt added in v0.25.0

type GoIfStmt struct {
	Cond   GoExpr
	Body   []GoStmt
	ElseIf []GoElseIf
	Else   []GoStmt // nil for no else
}

GoIfStmt represents: if cond { body } [else if ...] [else { body }]

type GoImport added in v0.25.0

type GoImport struct {
	Path  string
	Alias string // empty for default alias
}

GoImport represents a single import.

type GoIndexExpr added in v0.25.0

type GoIndexExpr struct {
	Object GoExpr
	Index  GoExpr
}

GoIndexExpr represents indexing: obj[idx]

type GoIntLit added in v0.25.0

type GoIntLit struct {
	Value string
}

GoIntLit represents an integer literal.

type GoLambdaExpr added in v0.25.0

type GoLambdaExpr struct {
	Body []GoStmt // lambda body (preamble + user code + return nil)
}

GoLambdaExpr represents a Rugo lambda: interface{}(func(_args ...interface{}) interface{} { body })

type GoLineDirective added in v0.25.0

type GoLineDirective struct {
	File string
	Line int
}

GoLineDirective represents: //line file:N

type GoMapLit added in v0.25.0

type GoMapLit struct {
	KeyType string
	ValType string
	Pairs   []GoMapPair
}

GoMapLit represents a map literal: map[K]V{k: v, ...}

type GoMapPair added in v0.25.0

type GoMapPair struct {
	Key   GoExpr
	Value GoExpr
}

GoMapPair represents a key-value pair in a map literal.

type GoMethodCallExpr added in v0.25.0

type GoMethodCallExpr struct {
	Object GoExpr
	Method string
	Args   []GoExpr
}

GoMethodCallExpr represents a method call: obj.Method(args...)

type GoMultiAssignStmt added in v0.25.0

type GoMultiAssignStmt struct {
	Targets []string
	Op      string // ":=" or "="
	Value   GoExpr
}

GoMultiAssignStmt represents: t1, t2 := expr

type GoNilExpr added in v0.25.0

type GoNilExpr struct{}

GoNilExpr represents the nil value.

type GoParam added in v0.25.0

type GoParam struct {
	Name string
	Type string
}

GoParam represents a function parameter.

type GoParenExpr added in v0.25.0

type GoParenExpr struct {
	Inner GoExpr
}

GoParenExpr represents a parenthesized expression: (expr)

type GoRawDecl added in v0.25.0

type GoRawDecl struct {
	Code string
}

GoRawDecl is an escape hatch for raw Go code at the declaration level (runtime templates, complex generated blocks).

type GoRawExpr added in v0.25.0

type GoRawExpr struct {
	Code string
}

GoRawExpr wraps a raw Go expression string.

type GoRawStmt added in v0.25.0

type GoRawStmt struct {
	Code string
}

GoRawStmt is an escape hatch for raw Go code at the statement level.

type GoReturnStmt added in v0.25.0

type GoReturnStmt struct {
	Value GoExpr // nil for bare return
}

GoReturnStmt represents: return [expr]

type GoSliceLit added in v0.25.0

type GoSliceLit struct {
	Type     string
	Elements []GoExpr
}

GoSliceLit represents a slice literal: []T{a, b, c}

type GoStmt added in v0.25.0

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

GoStmt is a statement inside a function body.

type GoStringConcat added in v0.25.0

type GoStringConcat struct {
	Parts []GoExpr
}

GoStringConcat represents string concatenation: a + b + c

type GoStringLit added in v0.25.0

type GoStringLit struct {
	Value string // Go-escaped content WITHOUT quotes
}

GoStringLit represents a Go string literal (with quotes).

type GoSwitchStmt added in v0.25.0

type GoSwitchStmt struct {
	Tag     GoExpr // nil for tagless switch
	Cases   []GoCase
	Default []GoStmt // nil for no default
}

GoSwitchStmt represents: switch [tag] { case ...: ... default: ... }

type GoTypeAssert added in v0.25.0

type GoTypeAssert struct {
	Value GoExpr
	Type  string
}

GoTypeAssert represents a type assertion: value.(type)

type GoUnaryExpr added in v0.25.0

type GoUnaryExpr struct {
	Op      string
	Operand GoExpr
}

GoUnaryExpr represents: op operand

type GoVarDecl added in v0.25.0

type GoVarDecl struct {
	Name  string
	Type  string
	Value GoExpr // nil for uninitialized
}

GoVarDecl represents: var name type [= value]

type GoVarStmt added in v0.25.0

type GoVarStmt struct {
	Name  string
	Type  string
	Value GoExpr // nil for uninitialized
}

GoVarStmt represents: var name type [= value]

type RugoType

type RugoType int
const (
	// TypeUnknown means inference hasn't resolved the type yet.
	TypeUnknown RugoType = iota
	// TypeInt is an integer type (Go int).
	TypeInt
	// TypeFloat is a floating-point type (Go float64).
	TypeFloat
	// TypeString is a string type.
	TypeString
	// TypeBool is a boolean type.
	TypeBool
	// TypeNil is the nil literal type.
	TypeNil
	// TypeArray is []interface{} (element types not tracked).
	TypeArray
	// TypeHash is map[interface{}]interface{}.
	TypeHash
	// TypeDynamic means the type is explicitly unresolvable (mixed types,
	// external calls, etc.). Falls back to interface{} in codegen.
	TypeDynamic
)

func (RugoType) GoType

func (t RugoType) GoType() string

GoType returns the Go type string for codegen, or "" for untyped.

func (RugoType) IsNumeric

func (t RugoType) IsNumeric() bool

IsNumeric returns true for int and float types.

func (RugoType) IsResolved

func (t RugoType) IsResolved() bool

IsResolved returns true if the type is concrete (not unknown or dynamic).

func (RugoType) IsTyped

func (t RugoType) IsTyped() bool

IsTyped returns true if the type can be used for typed codegen (resolved and not a compound type like array/hash).

func (RugoType) String

func (t RugoType) String() string

type SandboxConfig added in v0.18.0

type SandboxConfig struct {
	RO      []string // read-only paths
	RW      []string // read-write paths
	ROX     []string // read + execute paths
	RWX     []string // read + write + execute paths
	Connect []int    // allowed TCP connect ports
	Bind    []int    // allowed TCP bind ports
	Env     []string // allowed environment variable names
	EnvSet  bool     // true when env: was explicitly specified (even if empty)
}

SandboxConfig holds Landlock sandbox permissions for the compiled binary. A non-nil config with all empty fields means maximum restriction (deny everything).

type TypeInfo

type TypeInfo struct {
	// ExprTypes maps expressions to their inferred types.
	ExprTypes map[ast.Expr]RugoType
	// FuncTypes maps function names to their inferred signatures.
	FuncTypes map[string]*FuncTypeInfo
	// VarTypes maps (scope, variable name) to their final inferred type.
	// Scope is the function name (or "" for top-level).
	VarTypes map[string]map[string]RugoType
}

TypeInfo holds inferred type information for a program.

func Infer added in v0.15.0

func Infer(prog *ast.Program) *TypeInfo

Infer runs type inference on a parsed program, returning type annotations for expressions and function signatures. The inference is conservative: anything that can't be proven typed remains TypeDynamic (interface{}).

func (*TypeInfo) ExprType

func (ti *TypeInfo) ExprType(e ast.Expr) RugoType

ExprType returns the inferred type of an expression, or TypeDynamic if unknown.

func (*TypeInfo) VarType

func (ti *TypeInfo) VarType(scope, name string) RugoType

VarType returns the inferred type of a variable in a given scope.

Jump to

Keyboard shortcuts

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