builtins

package
v0.14.3 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: Apache-2.0 Imports: 40 Imported by: 0

Documentation

Overview

Package builtins provides numeric conversion builtins for AILANG. These support JSON encoding/decoding which requires int<->float conversions.

Index

Constants

This section is empty.

Variables

View Source
var Registry = make(map[string]*BuiltinMeta)

Registry holds all registered builtin function metadata This is a simple data structure with no dependencies on eval or runtime

View Source
var StdlibIndex = make(map[string]string)

StdlibIndex maps stdlib function names (e.g., "trim", "map") to their internal builtin names (e.g., "_str_trim", "_list_map"). M-CODEGEN-SUSTAINABILITY: Built automatically from GoCodegenSpec.StdlibName fields. The codegen queries this to resolve VarGlobal references from stdlib imports.

Functions

func AllNames

func AllNames() []string

AllNames returns all registered builtin names

func AllSpecs

func AllSpecs() map[string]*BuiltinSpec

AllSpecs returns all registered builtin specifications

func FormatReport

func FormatReport(report *MigrationReport) string

FormatReport formats a migration report for display

func GetBuiltinNames

func GetBuiltinNames() []string

GetBuiltinNames returns all registered builtin names

func GroupByEffect

func GroupByEffect() map[string][]string

GroupByEffect groups builtin names by their effect type

func GroupByModule

func GroupByModule() map[string][]string

GroupByModule groups builtin names by their module

func HammingDistance

func HammingDistance(a, b int64) int

HammingDistance computes the number of differing bits between two 64-bit integers. Lower distance = more similar documents. Typical thresholds:

  • 0-3: Very similar (likely near-duplicates)
  • 4-10: Somewhat similar
  • 10+: Different documents

func Init

func Init() error

Init freezes the registry after all registrations are complete This wires up the registry to runtime dispatch and link interface

func IsBuiltin

func IsBuiltin(name string) bool

IsBuiltin checks if a name is a registered builtin

func IsFrozen

func IsFrozen() bool

IsFrozen returns whether the registry has been initialized

func RebuildStdlibIndex

func RebuildStdlibIndex()

RebuildStdlibIndex populates StdlibIndex from all registered builtins. Called after all builtins are registered.

func RegisterEffectBuiltin

func RegisterEffectBuiltin(spec BuiltinSpec) error

RegisterEffectBuiltin registers a new effect builtin with complete validation

This is the ONLY function you should use to register new builtins. It performs comprehensive validation and consolidates all registration steps.

Example:

RegisterEffectBuiltin(BuiltinSpec{
    Module:  "std/net",
    Name:    "_net_httpRequest",
    NumArgs: 4,
    IsPure:  false,
    Effect:  "Net",
    Type:    makeHTTPRequestType,
    Impl:    effects.NetHTTPRequest,
})

Validation performed:

  • Name must not be empty
  • Type function must not be nil
  • Type function must return non-nil
  • NumArgs must match type signature arity
  • No duplicate registrations
  • Impl function must not be nil

func SafeAsBool

func SafeAsBool(v eval.Value) (bool, error)

SafeAsBool extracts the boolean value from an eval.Value Returns a descriptive error if the value is not a BoolValue

func SafeAsFloat

func SafeAsFloat(v eval.Value) (float64, error)

SafeAsFloat extracts the float value from an eval.Value Returns a descriptive error if the value is not a FloatValue

func SafeAsInt

func SafeAsInt(v eval.Value) (int, error)

SafeAsInt extracts the integer value from an eval.Value Returns a descriptive error if the value is not an IntValue

func SafeAsList

func SafeAsList(v eval.Value) ([]eval.Value, error)

SafeAsList extracts the list value from an eval.Value Returns a descriptive error if the value is not a ListValue

func SafeAsRecord

func SafeAsRecord(v eval.Value) (map[string]eval.Value, error)

SafeAsRecord extracts the record value from an eval.Value Returns a descriptive error if the value is not a RecordValue

func SafeAsString

func SafeAsString(v eval.Value) (string, error)

SafeAsString extracts the string value from an eval.Value Returns a descriptive error if the value is not a StringValue

func SafeAsTagged

func SafeAsTagged(v eval.Value) (*eval.TaggedValue, error)

SafeAsTagged extracts the tagged value from an eval.Value Returns a descriptive error if the value is not a TaggedValue

func SetGameClock

func SetGameClock(deltaTime, totalTime float64, frameCount int)

SetGameClock sets the frame timing state. Call this at the start of each frame from the game loop.

func SetRandSeed

func SetRandSeed(seed int64)

SetRandSeed sets the random seed for deterministic random generation. Call this at the start of a game session with a known seed for reproducible results.

func SimHash

func SimHash(text string) int64

SimHash computes a 64-bit locality-sensitive hash of a string. The algorithm: 1. Tokenize the input into words (or n-grams) 2. Hash each token to a 64-bit value using FNV-1a 3. For each bit position, sum +1 if bit is 1, -1 if bit is 0 4. Final hash has bit=1 if sum>0, bit=0 otherwise

This produces a fingerprint where similar documents have similar hashes.

Types

type BuiltinMeta

type BuiltinMeta struct {
	Name    string
	NumArgs int
	IsPure  bool

	// GoCodegen holds the Go code generation specification for this builtin.
	// M-CODEGEN-SUSTAINABILITY: When set, the Go codegen can emit this builtin
	// without hardcoded mapping tables. Each builtin registers BOTH its interpreter
	// implementation (in the eval package) and its codegen equivalent (here).
	GoCodegen *GoCodegenSpec
}

BuiltinMeta holds metadata about a builtin function This is a lightweight struct that doesn't depend on eval types

type BuiltinMetadata

type BuiltinMetadata struct {

	// Description is a one-line summary of what the builtin does
	// Example: "Make an HTTP request with custom headers and body"
	Description string

	// LongDesc is a detailed multi-line description (optional)
	// Can include usage notes, caveats, performance characteristics
	LongDesc string

	// Params documents each parameter (optional but recommended)
	Params []ParamDoc

	// Returns documents the return value (optional but recommended)
	// Example: "Result[HttpResponse, NetError] where HttpResponse contains status, headers, and body"
	Returns string

	// Examples provides usage examples (optional)
	// Highly recommended for complex builtins
	Examples []Example

	// SeeAlso lists related builtins (optional)
	// Example: []string{"_net_httpGet", "_net_httpPost"}
	SeeAlso []string

	// Since indicates when the builtin was added (optional)
	// Example: "v0.2.0"
	Since string

	// Deprecated contains a deprecation message if this builtin is being phased out (optional)
	// Should explain what to use instead
	// Example: "Use _net_httpRequest instead, which supports custom headers"
	Deprecated string

	// Stability indicates API stability guarantees (optional, defaults to Stable for old builtins)
	Stability Stability

	// Tags are searchable keywords (optional)
	// Example: []string{"http", "network", "request", "api"}
	Tags []string

	// Category is a high-level grouping (optional)
	// Examples: "network", "string", "math", "io"
	Category string
}

BuiltinMetadata contains optional enhanced metadata for a builtin All fields are optional to maintain backward compatibility

func (*BuiltinMetadata) GetStabilityString

func (m *BuiltinMetadata) GetStabilityString() string

GetStabilityString returns a human-readable stability level

func (*BuiltinMetadata) HasDocumentation

func (m *BuiltinMetadata) HasDocumentation() bool

HasDocumentation returns true if this builtin has meaningful documentation

func (*BuiltinMetadata) HasExamples

func (m *BuiltinMetadata) HasExamples() bool

HasExamples returns true if this builtin has usage examples

func (*BuiltinMetadata) IsDeprecated

func (m *BuiltinMetadata) IsDeprecated() bool

IsDeprecated returns true if this builtin has been deprecated

type BuiltinSpec

type BuiltinSpec struct {
	// === Core Metadata (v0.3.10 - Required) ===
	Module  string            // Module path (e.g., "std/net", "std/io")
	Name    string            // Builtin name with _ prefix (e.g., "_net_httpRequest")
	NumArgs int               // Number of arguments (for arity checking)
	IsPure  bool              // true = no side effects, false = has effects
	Effect  string            // "" for pure functions, "Net"/"IO"/"FS" for effects
	Type    func() types.Type // Type signature constructor (must return non-nil)
	Impl    EffectImpl        // Implementation function

	// === Enhanced Metadata (v0.3.15+ - Optional) ===
	// All fields in Metadata are optional for backward compatibility.
	// See internal/builtins/metadata.go for field documentation.
	Metadata *BuiltinMetadata // Enhanced documentation and versioning info
}

BuiltinSpec defines a complete specification for a builtin function This consolidates all the information needed for registration: - Metadata (name, arity, purity) - Type signature - Implementation - Optional enhanced metadata (M-DX1.11)

func GetSpec

func GetSpec(name string) (*BuiltinSpec, bool)

GetSpec retrieves a builtin specification by name

type EffectImpl

type EffectImpl func(*effects.EffContext, []eval.Value) (eval.Value, error)

EffectImpl is the function signature for effect builtin implementations

func GetJSONDecodeImpl

func GetJSONDecodeImpl() EffectImpl

GetJSONDecodeImpl exports the implementation for legacy registry integration

func GetJSONEncodeImpl

func GetJSONEncodeImpl() EffectImpl

GetJSONEncodeImpl exports the implementation for legacy registry integration

type Example

type Example struct {
	Code        string // AILANG code demonstrating the builtin
	Description string // What the example demonstrates
}

Example provides a usage example for a builtin

type GameClockState

type GameClockState struct {
	DeltaTime  float64 // Time since last frame in seconds (e.g., 0.016 for 60fps)
	TotalTime  float64 // Total game time in seconds since start
	FrameCount int     // Current frame number (starts at 0)
}

GameClockState holds the current frame timing state. Set by the game engine via SetGameClock before each frame.

func GetGameClock

func GetGameClock() GameClockState

GetGameClock returns the current frame timing state.

type GoCodegenSpec

type GoCodegenSpec struct {
	// Inline is a Go expression template for simple builtins.
	// Use {{arg0}}, {{arg1}}, etc. as placeholders for arguments.
	// Example: "strings.TrimSpace({{arg0}}.(string))"
	// When set, the codegen substitutes arguments and emits the expression inline.
	Inline string

	// Helper defines a runtime helper function for complex builtins.
	// The function is emitted once in runtime.go and called by name.
	// Use this for builtins that need control flow (loops, conditionals).
	Helper *GoHelperSpec

	// Imports lists Go packages needed by Inline or Helper.
	// These are added to the generated file's import block.
	// Example: []string{"strings", "strconv"}
	Imports []string

	// StdlibName is the AILANG stdlib function name that wraps this builtin.
	// Example: "_str_trim" has StdlibName "trim" (from std/string.trim).
	// Used by the codegen to resolve VarGlobal references from stdlib imports.
	StdlibName string

	// RequiresADT specifies which ADT must be registered for this helper to be emitted.
	// Values: "Json", "Option", "Result", or "" (always emit).
	// Helpers with RequiresADT are eagerly emitted when their ADT is registered,
	// ensuring inter-dependent helpers (e.g., GetString depends on JsonGet, IsNone)
	// are always available as a group.
	RequiresADT string
}

GoCodegenSpec describes how a builtin function should be emitted in generated Go code. M-CODEGEN-SUSTAINABILITY: This is the single source of truth for builtin → Go mapping. It replaces mapPureMathBuiltin, mapPureListBuiltin, and mapStdlibBuiltin.

func GetCodegenSpec

func GetCodegenSpec(name string) *GoCodegenSpec

GetCodegenSpec returns the Go codegen specification for a builtin. Returns nil if the builtin has no codegen spec.

func GetCodegenSpecByStdlibName

func GetCodegenSpecByStdlibName(stdlibName string) *GoCodegenSpec

GetCodegenSpecByStdlibName looks up a codegen spec by stdlib function name. Example: GetCodegenSpecByStdlibName("trim") returns the spec for _str_trim.

func GetHelpersRequiringADT

func GetHelpersRequiringADT(adtName string) []*GoCodegenSpec

GetHelpersRequiringADT returns all helper specs that require a specific ADT. Used by the codegen to eagerly emit all helpers for a registered ADT as a group.

type GoHelperSpec

type GoHelperSpec struct {
	// FuncName is the Go function name (PascalCase).
	// Example: "Map", "Filter", "Trim"
	FuncName string

	// Signature is the full Go function signature.
	// Example: "func Map(f, xs interface{}) interface{}"
	Signature string

	// Body is the Go function body (without enclosing braces).
	// Example: "return strings.TrimSpace(s.(string))"
	Body string
}

GoHelperSpec describes a Go runtime helper function to emit in generated code.

type JSONBuilder

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

type LegacyBuiltinLocation

type LegacyBuiltinLocation struct {
	FilePath    string   // Path to the file
	Description string   // What used to be there
	Patterns    []string // Code patterns to search for
}

LegacyBuiltinLocation represents a location where builtins used to be registered

func GetLegacyLocations

func GetLegacyLocations(projectRoot string) []LegacyBuiltinLocation

GetLegacyLocations returns all locations where builtins used to be registered

type LegacyLocationReport

type LegacyLocationReport struct {
	Location      LegacyBuiltinLocation
	FileExists    bool
	FoundBuiltins []string
	Notes         string
}

LegacyLocationReport reports on one legacy location

type MigrationReport

type MigrationReport struct {
	LegacyLocations      []LegacyLocationReport
	CurrentRegistryCount int
	OrphanedBuiltins     []OrphanedBuiltin
	Warnings             []string
	IsClean              bool
}

MigrationReport contains the results of a migration validation

func ValidateMigration

func ValidateMigration(projectRoot string) (*MigrationReport, error)

ValidateMigration checks if all builtins have been migrated to the new registry

type OrphanedBuiltin

type OrphanedBuiltin struct {
	Name     string
	Location string
	Hint     string
}

OrphanedBuiltin represents a builtin found in old locations but not in new registry

type ParamDoc

type ParamDoc struct {
	Name        string // Parameter name (e.g., "url", "method")
	Description string // What the parameter does and any constraints
}

ParamDoc documents a single function parameter

type RegistryStats

type RegistryStats struct {
	Total    int            // Total builtins registered
	Pure     int            // Pure functions (no side effects)
	Effect   int            // Functions with effects
	ByModule map[string]int // Count by module
	ByEffect map[string]int // Count by effect type
}

RegistryStats holds statistics about registered builtins

func GetRegistryStats

func GetRegistryStats() RegistryStats

GetRegistryStats returns statistics about registered builtins

type Stability

type Stability int

Stability indicates the maturity level of a builtin

const (
	// StabilityUnspecified means stability hasn't been declared yet
	StabilityUnspecified Stability = iota

	// StabilityExperimental means the API may change in any release
	// Use with caution in production code
	StabilityExperimental

	// StabilityStable means the API is backwards compatible
	// Breaking changes will only occur in major version bumps
	StabilityStable

	// StabilityDeprecated means the builtin is being phased out
	// Users should migrate to the recommended alternative
	StabilityDeprecated
)

func ParseStability

func ParseStability(s string) Stability

ParseStability converts a string to a Stability constant

func (Stability) String

func (s Stability) String() string

String returns the string representation of a Stability level

type ValidationError

type ValidationError struct {
	Builtin  string // Builtin name
	Message  string // Error description
	Fix      string // Suggested fix with example code
	Location string // File where fix should be applied
	Severity string // "error" or "warning"
}

ValidationError represents a builtin registration issue

func ValidateBuiltins

func ValidateBuiltins() []ValidationError

ValidateBuiltins performs comprehensive validation on all registered builtins Returns a list of validation errors (empty if all valid)

Jump to

Keyboard shortcuts

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