ast

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package ast defines the Abstract Syntax Tree for CodeAI specifications. It provides node types for all language constructs including declarations, statements, and expressions.

Package ast defines the Abstract Syntax Tree for CodeAI specifications.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Equal

func Equal(a, b Node) bool

Equal performs a deep equality check between two AST nodes.

Example

ExampleEqual demonstrates comparing AST nodes for equality.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	a := &ast.NumberLiteral{Value: 42}
	b := &ast.NumberLiteral{Value: 42}
	c := &ast.NumberLiteral{Value: 100}

	fmt.Println("a == b:", ast.Equal(a, b))
	fmt.Println("a == c:", ast.Equal(a, c))
}
Output:

a == b: true
a == c: false

func Print

func Print(node Node) string

Print returns a pretty-printed string representation of the AST.

Example

ExamplePrint demonstrates pretty-printing an AST.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	prog := &ast.Program{
		Statements: []ast.Statement{
			&ast.VarDecl{
				Name:  "x",
				Value: &ast.NumberLiteral{Value: 42},
			},
		},
	}

	output := ast.Print(prog)
	fmt.Println(output)
}
Output:

Program
  VarDecl: x
    NumberLiteral: NumberLiteral{42}

func Walk

func Walk(node Node, visitor Visitor) bool

Walk traverses the AST in depth-first order, calling the visitor function for each node. If the visitor returns false, traversal stops immediately. Walk returns true if traversal completed normally, false if it was stopped early.

Example

ExampleWalk demonstrates traversing an AST to count nodes.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	prog := &ast.Program{
		Statements: []ast.Statement{
			&ast.VarDecl{
				Name:  "x",
				Value: &ast.NumberLiteral{Value: 1},
			},
			&ast.VarDecl{
				Name:  "y",
				Value: &ast.NumberLiteral{Value: 2},
			},
		},
	}

	count := 0
	ast.Walk(prog, func(n ast.Node) bool {
		count++
		return true
	})

	fmt.Println("Node count:", count)
}
Output:

Node count: 5
Example (FindIdentifiers)

ExampleWalk_findIdentifiers demonstrates using Walk to find all identifiers.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	prog := &ast.Program{
		Statements: []ast.Statement{
			&ast.VarDecl{
				Name:  "result",
				Value: &ast.Identifier{Name: "input"},
			},
		},
	}

	identifiers := []string{}
	ast.Walk(prog, func(n ast.Node) bool {
		if id, ok := n.(*ast.Identifier); ok {
			identifiers = append(identifiers, id.Name)
		}
		return true
	})

	fmt.Println("Identifiers found:", identifiers)
}
Output:

Identifiers found: [input]

Types

type ArrayLiteral

type ArrayLiteral struct {
	Elements []Expression
	// contains filtered or unexported fields
}

ArrayLiteral represents an array literal: [a, b, c]

Example

ExampleArrayLiteral demonstrates creating array literals.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	arr := &ast.ArrayLiteral{
		Elements: []ast.Expression{
			&ast.StringLiteral{Value: "a"},
			&ast.StringLiteral{Value: "b"},
			&ast.StringLiteral{Value: "c"},
		},
	}

	fmt.Println("Type:", arr.Type())
	fmt.Println("Elements:", len(arr.Elements))
}
Output:

Type: ArrayLiteral
Elements: 3

func (*ArrayLiteral) Pos

func (a *ArrayLiteral) Pos() Position

func (*ArrayLiteral) String

func (a *ArrayLiteral) String() string

func (*ArrayLiteral) Type

func (a *ArrayLiteral) Type() NodeType

type Assignment

type Assignment struct {
	Name  string
	Value Expression
	// contains filtered or unexported fields
}

Assignment represents an assignment statement: `x = value`

func (*Assignment) Pos

func (a *Assignment) Pos() Position

func (*Assignment) String

func (a *Assignment) String() string

func (*Assignment) Type

func (a *Assignment) Type() NodeType

type BinaryExpr

type BinaryExpr struct {
	Left     Expression
	Operator string
	Right    Expression
	// contains filtered or unexported fields
}

BinaryExpr represents a binary operation: a + b, x == y, etc.

Example

ExampleBinaryExpr demonstrates creating binary expressions.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	// Represents: 1 + 2 * 3
	expr := &ast.BinaryExpr{
		Left:     &ast.NumberLiteral{Value: 1},
		Operator: "+",
		Right: &ast.BinaryExpr{
			Left:     &ast.NumberLiteral{Value: 2},
			Operator: "*",
			Right:    &ast.NumberLiteral{Value: 3},
		},
	}

	fmt.Println("Type:", expr.Type())
	fmt.Println("Operator:", expr.Operator)
}
Output:

Type: BinaryExpr
Operator: +

func (*BinaryExpr) Pos

func (b *BinaryExpr) Pos() Position

func (*BinaryExpr) String

func (b *BinaryExpr) String() string

func (*BinaryExpr) Type

func (b *BinaryExpr) Type() NodeType

type Block

type Block struct {
	Statements []Statement
	// contains filtered or unexported fields
}

Block represents a block of statements enclosed in braces.

func (*Block) Pos

func (b *Block) Pos() Position

func (*Block) String

func (b *Block) String() string

func (*Block) Type

func (b *Block) Type() NodeType

type BoolLiteral

type BoolLiteral struct {
	Value bool
	// contains filtered or unexported fields
}

BoolLiteral represents a boolean literal (true or false).

func (*BoolLiteral) Pos

func (b *BoolLiteral) Pos() Position

func (*BoolLiteral) String

func (b *BoolLiteral) String() string

func (*BoolLiteral) Type

func (b *BoolLiteral) Type() NodeType

type CollectionDecl

type CollectionDecl struct {
	Name        string
	Description string
	Fields      []*MongoFieldDecl
	Indexes     []*MongoIndexDecl
	// contains filtered or unexported fields
}

CollectionDecl represents a MongoDB collection declaration. Example: collection User { _id: objectid, primary ... }

func (*CollectionDecl) Pos

func (c *CollectionDecl) Pos() Position

func (*CollectionDecl) String

func (c *CollectionDecl) String() string

func (*CollectionDecl) Type

func (c *CollectionDecl) Type() NodeType

type ConfigDecl

type ConfigDecl struct {
	DatabaseType DatabaseType // "postgres" or "mongodb"
	MongoDBURI   string       // MongoDB connection URI
	MongoDBName  string       // MongoDB database name
	Properties   map[string]Expression
	// contains filtered or unexported fields
}

ConfigDecl represents a config block declaration. Example: config { database_type: "mongodb" }

func (*ConfigDecl) Pos

func (c *ConfigDecl) Pos() Position

func (*ConfigDecl) String

func (c *ConfigDecl) String() string

func (*ConfigDecl) Type

func (c *ConfigDecl) Type() NodeType

type DatabaseBlock

type DatabaseBlock struct {
	DBType     DatabaseType // "postgres" or "mongodb"
	Name       string       // optional name for the database
	Statements []Statement
	// contains filtered or unexported fields
}

DatabaseBlock represents a database definition block. Example: database postgres { table users { ... } } Example: database mongodb { collection users { ... } }

func (*DatabaseBlock) Pos

func (d *DatabaseBlock) Pos() Position

func (*DatabaseBlock) String

func (d *DatabaseBlock) String() string

func (*DatabaseBlock) Type

func (d *DatabaseBlock) Type() NodeType

type DatabaseType

type DatabaseType string

DatabaseType represents the supported database backends.

const (
	DatabaseTypePostgres DatabaseType = "postgres"
	DatabaseTypeMongoDB  DatabaseType = "mongodb"
)

type EmbeddedDocDecl

type EmbeddedDocDecl struct {
	Fields []*MongoFieldDecl
	// contains filtered or unexported fields
}

EmbeddedDocDecl represents an embedded document type in MongoDB.

func (*EmbeddedDocDecl) Pos

func (e *EmbeddedDocDecl) Pos() Position

func (*EmbeddedDocDecl) String

func (e *EmbeddedDocDecl) String() string

func (*EmbeddedDocDecl) Type

func (e *EmbeddedDocDecl) Type() NodeType

type ExecBlock

type ExecBlock struct {
	Command string
	// contains filtered or unexported fields
}

ExecBlock represents a shell command execution block.

func (*ExecBlock) Pos

func (e *ExecBlock) Pos() Position

func (*ExecBlock) String

func (e *ExecBlock) String() string

func (*ExecBlock) Type

func (e *ExecBlock) Type() NodeType

type Expression

type Expression interface {
	Node
	// contains filtered or unexported methods
}

Expression is a marker interface for expression nodes. Expressions are constructs that evaluate to values.

type FieldDecl

type FieldDecl struct {
	Name      string
	FieldType *TypeRef
	Modifiers []*Modifier
	// contains filtered or unexported fields
}

FieldDecl represents a field in a PostgreSQL model.

func (*FieldDecl) Pos

func (f *FieldDecl) Pos() Position

func (*FieldDecl) String

func (f *FieldDecl) String() string

func (*FieldDecl) Type

func (f *FieldDecl) Type() NodeType

type ForLoop

type ForLoop struct {
	Variable string
	Iterable Expression
	Body     *Block
	// contains filtered or unexported fields
}

ForLoop represents a for-in loop: `for item in items { ... }`

Example

ExampleForLoop demonstrates creating for-in loops.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	forLoop := &ast.ForLoop{
		Variable: "item",
		Iterable: &ast.Identifier{Name: "items"},
		Body: &ast.Block{
			Statements: []ast.Statement{
				&ast.VarDecl{
					Name:  "processed",
					Value: &ast.Identifier{Name: "item"},
				},
			},
		},
	}

	fmt.Println("Type:", forLoop.Type())
	fmt.Println("Variable:", forLoop.Variable)
}
Output:

Type: ForLoop
Variable: item

func (*ForLoop) Pos

func (f *ForLoop) Pos() Position

func (*ForLoop) String

func (f *ForLoop) String() string

func (*ForLoop) Type

func (f *ForLoop) Type() NodeType

type FunctionCall

type FunctionCall struct {
	Name string
	Args []Expression
	// contains filtered or unexported fields
}

FunctionCall represents a function invocation with arguments.

Example

ExampleFunctionCall demonstrates creating a function call expression.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	call := &ast.FunctionCall{
		Name: "add",
		Args: []ast.Expression{
			&ast.NumberLiteral{Value: 1},
			&ast.NumberLiteral{Value: 2},
		},
	}

	fmt.Println("Type:", call.Type())
	fmt.Println("Function:", call.Name)
	fmt.Println("Arguments:", len(call.Args))
}
Output:

Type: FunctionCall
Function: add
Arguments: 2

func (*FunctionCall) Pos

func (f *FunctionCall) Pos() Position

func (*FunctionCall) String

func (f *FunctionCall) String() string

func (*FunctionCall) Type

func (f *FunctionCall) Type() NodeType

type FunctionDecl

type FunctionDecl struct {
	Name   string
	Params []Parameter
	Body   *Block
	// contains filtered or unexported fields
}

FunctionDecl represents a function declaration.

func (*FunctionDecl) Pos

func (f *FunctionDecl) Pos() Position

func (*FunctionDecl) String

func (f *FunctionDecl) String() string

func (*FunctionDecl) Type

func (f *FunctionDecl) Type() NodeType

type Identifier

type Identifier struct {
	Name string
	// contains filtered or unexported fields
}

Identifier represents a variable or function name reference.

func (*Identifier) Pos

func (i *Identifier) Pos() Position

func (*Identifier) String

func (i *Identifier) String() string

func (*Identifier) Type

func (i *Identifier) Type() NodeType

type IfStmt

type IfStmt struct {
	Condition Expression
	Then      *Block
	Else      *Block // may be nil
	// contains filtered or unexported fields
}

IfStmt represents an if/else conditional statement.

Example

ExampleIfStmt demonstrates creating if statements.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	ifStmt := &ast.IfStmt{
		Condition: &ast.BoolLiteral{Value: true},
		Then: &ast.Block{
			Statements: []ast.Statement{
				&ast.ReturnStmt{Value: &ast.NumberLiteral{Value: 1}},
			},
		},
		Else: &ast.Block{
			Statements: []ast.Statement{
				&ast.ReturnStmt{Value: &ast.NumberLiteral{Value: 0}},
			},
		},
	}

	fmt.Println("Type:", ifStmt.Type())
	fmt.Println("Has else:", ifStmt.Else != nil)
}
Output:

Type: IfStmt
Has else: true

func (*IfStmt) Pos

func (i *IfStmt) Pos() Position

func (*IfStmt) String

func (i *IfStmt) String() string

func (*IfStmt) Type

func (i *IfStmt) Type() NodeType

type IndexDecl

type IndexDecl struct {
	Fields []string
	Unique bool
	// contains filtered or unexported fields
}

IndexDecl represents a PostgreSQL index declaration.

func (*IndexDecl) Pos

func (i *IndexDecl) Pos() Position

func (*IndexDecl) String

func (i *IndexDecl) String() string

func (*IndexDecl) Type

func (i *IndexDecl) Type() NodeType

type ModelDecl

type ModelDecl struct {
	Name        string
	Description string
	Fields      []*FieldDecl
	Indexes     []*IndexDecl
	// contains filtered or unexported fields
}

ModelDecl represents a PostgreSQL model declaration. Example: model User { id: uuid, primary, auto ... }

func (*ModelDecl) Pos

func (m *ModelDecl) Pos() Position

func (*ModelDecl) String

func (m *ModelDecl) String() string

func (*ModelDecl) Type

func (m *ModelDecl) Type() NodeType

type Modifier

type Modifier struct {
	Name  string
	Value Expression // may be nil
	// contains filtered or unexported fields
}

Modifier represents a field modifier (e.g., required, unique, default(value)).

func (*Modifier) Pos

func (m *Modifier) Pos() Position

func (*Modifier) String

func (m *Modifier) String() string

func (*Modifier) Type

func (m *Modifier) Type() NodeType

type MongoFieldDecl

type MongoFieldDecl struct {
	Name      string
	FieldType *MongoTypeRef
	Modifiers []*Modifier
	// contains filtered or unexported fields
}

MongoFieldDecl represents a field in a MongoDB collection.

func (*MongoFieldDecl) Pos

func (f *MongoFieldDecl) Pos() Position

func (*MongoFieldDecl) String

func (f *MongoFieldDecl) String() string

func (*MongoFieldDecl) Type

func (f *MongoFieldDecl) Type() NodeType

type MongoIndexDecl

type MongoIndexDecl struct {
	Fields    []string
	Unique    bool
	IndexKind string // "", "text", "geospatial"
	// contains filtered or unexported fields
}

MongoIndexDecl represents a MongoDB index declaration. Supports: single, compound, text, geospatial indexes

func (*MongoIndexDecl) Pos

func (i *MongoIndexDecl) Pos() Position

func (*MongoIndexDecl) String

func (i *MongoIndexDecl) String() string

func (*MongoIndexDecl) Type

func (i *MongoIndexDecl) Type() NodeType

type MongoTypeRef

type MongoTypeRef struct {
	Name        string           // e.g., "objectid", "string", "array"
	Params      []string         // e.g., for array(string) -> ["string"]
	EmbeddedDoc *EmbeddedDocDecl // for embedded document types
	// contains filtered or unexported fields
}

MongoTypeRef represents a MongoDB-specific type reference. Supports: objectid, string, int, double, bool, date, binary, array(T), embedded { ... }

func (*MongoTypeRef) Pos

func (t *MongoTypeRef) Pos() Position

func (*MongoTypeRef) String

func (t *MongoTypeRef) String() string

func (*MongoTypeRef) Type

func (t *MongoTypeRef) Type() NodeType

type Node

type Node interface {
	// Pos returns the source position of the node
	Pos() Position
	// Type returns the node type enum value
	Type() NodeType
	// String returns a human-readable representation for debugging
	String() string
}

Node is the interface implemented by all AST nodes. Every node tracks its source position and provides type information.

func Clone

func Clone(node Node) Node

Clone creates a deep copy of the given AST node.

Example

ExampleClone demonstrates deep copying an AST node.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	original := &ast.VarDecl{
		Name:  "x",
		Value: &ast.NumberLiteral{Value: 42},
	}

	cloned := ast.Clone(original).(*ast.VarDecl)

	// Modify the clone
	cloned.Name = "y"

	fmt.Println("Original name:", original.Name)
	fmt.Println("Cloned name:", cloned.Name)
}
Output:

Original name: x
Cloned name: y

type NodeType

type NodeType int

NodeType represents the type of an AST node.

const (
	NodeProgram NodeType = iota
	NodeVarDecl
	NodeAssignment
	NodeIfStmt
	NodeForLoop
	NodeFunctionDecl
	NodeExecBlock
	NodeStringLiteral
	NodeNumberLiteral
	NodeBoolLiteral
	NodeIdentifier
	NodeFunctionCall
	NodeArrayLiteral
	NodeBlock
	NodeReturnStmt
	NodeBinaryExpr
	NodeUnaryExpr
	NodeConfigDecl
	NodeDatabaseBlock
	// PostgreSQL model types
	NodeModelDecl
	NodeFieldDecl
	NodeTypeRef
	NodeModifier
	NodeIndexDecl
	// MongoDB collection types
	NodeCollectionDecl
	NodeMongoFieldDecl
	NodeMongoTypeRef
	NodeEmbeddedDocDecl
	NodeMongoIndexDecl
)

Node type constants for all AST node kinds.

func (NodeType) String

func (nt NodeType) String() string

String returns the string representation of the NodeType.

type NumberLiteral

type NumberLiteral struct {
	Value float64
	// contains filtered or unexported fields
}

NumberLiteral represents a numeric literal value (integer or float).

func (*NumberLiteral) Pos

func (n *NumberLiteral) Pos() Position

func (*NumberLiteral) String

func (n *NumberLiteral) String() string

func (*NumberLiteral) Type

func (n *NumberLiteral) Type() NodeType

type Parameter

type Parameter struct {
	Name    string
	Type    string
	Default Expression // may be nil
}

Parameter represents a function parameter.

type Position

type Position struct {
	// Filename is the name of the source file
	Filename string
	// Line is the 1-indexed line number
	Line int
	// Column is the 1-indexed column number
	Column int
	// Offset is the byte offset from the start of the file
	Offset int
}

Position represents a source code position within a file. It tracks the filename, line number, column number, and byte offset.

Example

ExamplePosition demonstrates creating and using Position values.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	pos := ast.Position{
		Filename: "example.cai",
		Line:     10,
		Column:   5,
		Offset:   150,
	}

	fmt.Println(pos.String())
	fmt.Println("Valid:", pos.IsValid())
}
Output:

example.cai:10:5
Valid: true

func (Position) IsValid

func (p Position) IsValid() bool

IsValid returns true if the position has been set (non-zero line).

func (Position) String

func (p Position) String() string

String returns a human-readable representation of the position in the format "filename:line:column".

type Program

type Program struct {
	Statements []Statement
	// contains filtered or unexported fields
}

Program is the root node of the AST, containing all top-level statements.

Example

ExampleProgram demonstrates creating a Program node with statements.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	prog := &ast.Program{
		Statements: []ast.Statement{
			&ast.VarDecl{
				Name:  "greeting",
				Value: &ast.StringLiteral{Value: "hello"},
			},
		},
	}

	fmt.Println("Type:", prog.Type())
	fmt.Println("Statements:", len(prog.Statements))
}
Output:

Type: Program
Statements: 1

func (*Program) Pos

func (p *Program) Pos() Position

func (*Program) String

func (p *Program) String() string

func (*Program) Type

func (p *Program) Type() NodeType

type ReturnStmt

type ReturnStmt struct {
	Value Expression // may be nil for bare return
	// contains filtered or unexported fields
}

ReturnStmt represents a return statement.

func (*ReturnStmt) Pos

func (r *ReturnStmt) Pos() Position

func (*ReturnStmt) String

func (r *ReturnStmt) String() string

func (*ReturnStmt) Type

func (r *ReturnStmt) Type() NodeType

type Statement

type Statement interface {
	Node
	// contains filtered or unexported methods
}

Statement is a marker interface for statement nodes. Statements are executable constructs that don't produce values.

type StringLiteral

type StringLiteral struct {
	Value string
	// contains filtered or unexported fields
}

StringLiteral represents a string literal value.

func (*StringLiteral) Pos

func (s *StringLiteral) Pos() Position

func (*StringLiteral) String

func (s *StringLiteral) String() string

func (*StringLiteral) Type

func (s *StringLiteral) Type() NodeType

type TypeRef

type TypeRef struct {
	Name   string
	Params []*TypeRef
	// contains filtered or unexported fields
}

TypeRef represents a type reference (e.g., string, uuid, ref(User), list(string)).

func (*TypeRef) Pos

func (t *TypeRef) Pos() Position

func (*TypeRef) String

func (t *TypeRef) String() string

func (*TypeRef) Type

func (t *TypeRef) Type() NodeType

type UnaryExpr

type UnaryExpr struct {
	Operator string
	Operand  Expression
	// contains filtered or unexported fields
}

UnaryExpr represents a unary operation: -x, not flag

func (*UnaryExpr) Pos

func (u *UnaryExpr) Pos() Position

func (*UnaryExpr) String

func (u *UnaryExpr) String() string

func (*UnaryExpr) Type

func (u *UnaryExpr) Type() NodeType

type VarDecl

type VarDecl struct {
	Name  string
	Value Expression
	// contains filtered or unexported fields
}

VarDecl represents a variable declaration: `let x = value`

Example

ExampleVarDecl demonstrates creating a variable declaration.

package main

import (
	"fmt"

	"github.com/bargom/codeai/internal/ast"
)

func main() {
	decl := &ast.VarDecl{
		Name:  "count",
		Value: &ast.NumberLiteral{Value: 42},
	}

	fmt.Println("Type:", decl.Type())
	fmt.Println("Name:", decl.Name)
}
Output:

Type: VarDecl
Name: count

func (*VarDecl) Pos

func (v *VarDecl) Pos() Position

func (*VarDecl) String

func (v *VarDecl) String() string

func (*VarDecl) Type

func (v *VarDecl) Type() NodeType

type Visitor

type Visitor func(node Node) bool

Visitor is a function type for AST traversal. It receives each node and returns true to continue traversal or false to stop.

Jump to

Keyboard shortcuts

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