ast

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package ast defines the Abstract Syntax Tree (AST) for openCypher 9.

Every production reachable in the read + write + DDL + procedure scope is represented here (FOREACH, CALL{}, and multi-graph syntax are excluded). The AST is the IR-input contract consumed by later compiler stages (semantic analysis, planning, execution).

All types embed a Position struct for source-location tracking; the fields are populated by the parser in a later task.

Concurrency: AST nodes are value types produced once by the parser and then treated as immutable. Concurrent reads are safe without external locking.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Print

func Print(q Query) string

Print returns the canonical Cypher representation of q.

The output is deterministic and differs from q.String() in one critical respect: string literals are emitted with double-quotes ("value") rather than single-quotes ('value'). This is required for the round-trip property (see package-level documentation): the grammar's CHAR_LITERAL rule matches only a single character in single-quotes, so multi-character values enclosed in single-quotes are lexed as identifiers rather than string literals. Double-quoted STRING_LITERAL has no such restriction.

All other formatting rules are inherited from the existing String() methods:

  • Keywords in UPPER CASE
  • Single-space token separators
  • Explicit parentheses around every binary and unary operator

Round-trip guarantee: for any Cypher query Q that github.com/FlavioCFOliveira/GoGraph/cypher/parser.Parse accepts, Parse(Print(Parse(Q))) produces an AST that is structurally equal to Parse(Q) when Position fields are ignored.

Example

ExamplePrint renders a parsed AST back to canonical Cypher source text. Print is the inverse-direction helper used by tooling and debug output.

package main

import (
	"fmt"

	"github.com/FlavioCFOliveira/GoGraph/cypher/ast"
	"github.com/FlavioCFOliveira/GoGraph/cypher/parser"
)

func main() {
	q, err := parser.Parse("MATCH (n:Person) RETURN n.name")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(ast.Print(q))
}
Output:
MATCH (n:Person) RETURN n.name

Types

type BinaryOp

type BinaryOp struct {
	Pos      Position
	EndPos   Position
	Left     Expression
	Operator string // e.g. "+", "-", "=", "<>", "AND", "OR", "IN", "CONTAINS"
	Right    Expression
	// Parenthesized records that this BinaryOp was explicitly parenthesized in
	// the source. The precedence-rebalancing pass in cypher/parser uses this
	// flag to suppress lifting list/string-predicate operators (IN, CONTAINS,
	// STARTS WITH, ENDS WITH) out of arithmetic chains when the user wrote the
	// parentheses explicitly: `[1] + (2 IN [3]) + 4` must remain `[1] +
	// bool + 4`, but `[1] + 2 IN [3] + 4` must rebalance to `([1] + 2) IN
	// ([3] + 4)`. The flag is cleared once the rebalance pass completes;
	// downstream consumers ignore it.
	Parenthesized bool
}

BinaryOp is a binary operator expression: left OP right.

func (*BinaryOp) String

func (b *BinaryOp) String() string

String returns the Cypher infix expression.

type BoolLiteral

type BoolLiteral struct {
	Pos    Position
	EndPos Position
	Value  bool
}

BoolLiteral is the literal true or false.

func (*BoolLiteral) String

func (n *BoolLiteral) String() string

String returns "true" or "false".

type Call

type Call struct {
	Pos       Position
	EndPos    Position
	Namespace []string
	Procedure string
	Args      []Expression // nil or empty means no argument list
	Yield     []*YieldItem // nil means no YIELD clause; empty slice means YIELD *
	Where     *Where       // nil when no WHERE predicate on YIELD
}

Call is a CALL procedure clause.

CALL namespace.procedure(args) YIELD items WHERE predicate

func (*Call) String

func (c *Call) String() string

String returns the CALL clause.

type CaseAlternative

type CaseAlternative struct {
	Pos        Position
	EndPos     Position
	Condition  Expression
	Consequent Expression
}

CaseAlternative is a single WHEN … THEN … arm in a CASE expression.

func (*CaseAlternative) String

func (c *CaseAlternative) String() string

String returns the WHEN…THEN arm.

type CaseExpression

type CaseExpression struct {
	Pos          Position
	EndPos       Position
	Subject      Expression // nil for generic CASE
	Alternatives []*CaseAlternative
	ElseExpr     Expression // nil when no ELSE clause
}

CaseExpression is a CASE expression, either generic or value-form.

CASE [subject] WHEN … THEN … [ELSE …] END

func (*CaseExpression) String

func (c *CaseExpression) String() string

String returns the Cypher CASE expression.

type Clause

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

Clause is implemented by every top-level clause node.

type CountSubquery

type CountSubquery struct {
	Pos     Position
	EndPos  Position
	Pattern *Pattern     // pattern form
	Query   *SingleQuery // full subquery form
}

CountSubquery is a COUNT { … } subquery expression.

func (*CountSubquery) String

func (c *CountSubquery) String() string

String returns the Cypher COUNT subquery.

type Create

type Create struct {
	Pos     Position
	EndPos  Position
	Pattern *Pattern
}

Create is a CREATE clause.

func (*Create) String

func (c *Create) String() string

String returns the CREATE clause.

type Delete

type Delete struct {
	Pos         Position
	EndPos      Position
	Expressions []Expression
}

Delete is a DELETE clause.

func (*Delete) String

func (d *Delete) String() string

String returns the DELETE clause.

type DetachDelete

type DetachDelete struct {
	Pos         Position
	EndPos      Position
	Expressions []Expression
}

DetachDelete is a DETACH DELETE clause.

func (*DetachDelete) String

func (d *DetachDelete) String() string

String returns the DETACH DELETE clause.

type ExistsSubquery

type ExistsSubquery struct {
	Pos     Position
	EndPos  Position
	Pattern *Pattern     // pattern form: EXISTS { (a)-[r]->(b) }
	Where   *Where       // optional inline WHERE clause for the pattern form
	Query   *SingleQuery // full subquery form: EXISTS { MATCH … RETURN … }
}

ExistsSubquery is an EXISTS { … } subquery expression.

func (*ExistsSubquery) String

func (e *ExistsSubquery) String() string

String returns the Cypher EXISTS subquery.

type Expression

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

Expression is implemented by every AST node that can appear in an expression context (right-hand sides, WHERE predicates, RETURN items, etc.).

type FloatLiteral

type FloatLiteral struct {
	Pos    Position
	EndPos Position
	Value  float64
}

FloatLiteral is a floating-point literal value.

func (*FloatLiteral) String

func (n *FloatLiteral) String() string

String returns the decimal representation of the float. Always emits a fractional or exponent marker so the literal round-trips back to a float when re-parsed by downstream property-value parsers — strconv.FormatFloat drops the trailing ".0" for whole-number values like 10.0, but the downstream parser uses presence of "." or "eE" to discriminate float from integer literals.

type FunctionInvocation

type FunctionInvocation struct {
	Pos       Position
	EndPos    Position
	Namespace []string // e.g. ["apoc", "path"] for apoc.path.expand
	Name      string
	Distinct  bool
	// CountStar is true when this is COUNT(*). String() renders it as
	// "count(*)" and downstream aggregation detects it without needing
	// a wildcard argument expression.
	CountStar bool
	Args      []Expression
}

FunctionInvocation is a function call: func(args…) or func(DISTINCT args…).

func (*FunctionInvocation) String

func (f *FunctionInvocation) String() string

String returns the Cypher function call.

type IntLiteral

type IntLiteral struct {
	Pos    Position
	EndPos Position
	Value  int64
}

IntLiteral is an integer literal value.

func (*IntLiteral) String

func (n *IntLiteral) String() string

String returns the decimal representation of the integer.

type LabelPredicate

type LabelPredicate struct {
	Pos      Position
	EndPos   Position
	Receiver Expression
	Labels   []string
}

LabelPredicate is the conjunctive-label test on a node-valued expression: `n:Foo:Bar` evaluates to true when n is a node carrying every named label. The form appears both in WHERE filters and as a stand-alone projection (`RETURN (n:Foo)`). Receiver may be any expression; at evaluation time non-Node values yield NULL.

func (*LabelPredicate) String

func (l *LabelPredicate) String() string

String returns the Cypher predicate `(receiver:Label1:Label2)`. The parentheses match the canonical openCypher column-header form projected by `RETURN (n:Foo)`, so RETURN columns line up with the TCK comparison table.

type ListComprehension

type ListComprehension struct {
	Pos        Position
	EndPos     Position
	Variable   string
	Source     Expression
	Predicate  Expression // nil when no WHERE clause
	Projection Expression // nil when no projection expression
}

ListComprehension is a list comprehension: [var IN list WHERE pred | expr].

func (*ListComprehension) String

func (l *ListComprehension) String() string

String returns the Cypher list comprehension.

type ListLiteral

type ListLiteral struct {
	Pos      Position
	EndPos   Position
	Elements []Expression
}

ListLiteral is a bracketed list of expressions: [e1, e2, …].

func (*ListLiteral) String

func (n *ListLiteral) String() string

String returns the Cypher list literal.

type MapLiteral

type MapLiteral struct {
	Pos    Position
	EndPos Position
	Keys   []string
	Values []Expression
}

MapLiteral is a map expression: {key1: expr1, key2: expr2, …}.

func (*MapLiteral) String

func (n *MapLiteral) String() string

String returns the Cypher map literal.

type MapProjection

type MapProjection struct {
	Pos     Position
	EndPos  Position
	Subject Expression
	Items   []*MapProjectionItem
}

MapProjection is a map projection expression: n {.name, .age, extra: $x}.

func (*MapProjection) String

func (m *MapProjection) String() string

String returns the Cypher map projection.

type MapProjectionItem

type MapProjectionItem struct {
	Pos    Position
	EndPos Position
	Key    string     // explicit key when present; otherwise empty
	Value  Expression // nil for the property-selector shorthand (`.key`)
	IsAll  bool       // true for the .*  selector
}

MapProjectionItem represents one item in a map projection.

func (*MapProjectionItem) String

func (m *MapProjectionItem) String() string

String returns the item representation.

type Match

type Match struct {
	Pos     Position
	EndPos  Position
	Pattern *Pattern
	Where   *Where // nil when no WHERE predicate
}

Match is a MATCH clause.

func (*Match) String

func (m *Match) String() string

String returns the MATCH clause.

type Merge

type Merge struct {
	Pos      Position
	EndPos   Position
	Pattern  *PathPattern
	OnCreate []*SetItem // actions on ON CREATE SET
	OnMatch  []*SetItem // actions on ON MATCH SET
}

Merge is a MERGE clause, with optional ON CREATE and ON MATCH actions.

func (*Merge) String

func (m *Merge) String() string

String returns the MERGE clause.

type MultiQuery

type MultiQuery struct {
	Pos    Position
	EndPos Position
	Parts  []*SingleQuery
	All    bool // true for UNION ALL; false for UNION (deduplicating)
}

MultiQuery is a UNION of SingleQuery nodes.

func (*MultiQuery) String

func (m *MultiQuery) String() string

String returns the Cypher UNION query.

type Node

type Node interface {
	String() string
	// contains filtered or unexported methods
}

Node is the root interface implemented by every AST node. String returns a canonical Cypher representation.

type NodePattern

type NodePattern struct {
	Pos        Position
	EndPos     Position
	Variable   *string    // nil when anonymous
	Labels     []string   // zero or more labels
	Properties Expression // nil or a MapLiteral / Parameter
}

NodePattern represents a node within a path pattern: (n:Label {prop: val}).

func (*NodePattern) String

func (n *NodePattern) String() string

String returns the Cypher node pattern.

type NullLiteral

type NullLiteral struct {
	Pos    Position
	EndPos Position
}

NullLiteral is the literal null.

func (*NullLiteral) String

func (n *NullLiteral) String() string

String returns "null".

type OptionalMatch

type OptionalMatch struct {
	Pos     Position
	EndPos  Position
	Pattern *Pattern
	Where   *Where // nil when no WHERE predicate
}

OptionalMatch is an OPTIONAL MATCH clause.

func (*OptionalMatch) String

func (o *OptionalMatch) String() string

String returns the OPTIONAL MATCH clause.

type Parameter

type Parameter struct {
	Pos    Position
	EndPos Position
	Name   string // the name/index without the leading '$'
}

Parameter is a query parameter: $name or $0.

func (*Parameter) String

func (p *Parameter) String() string

String returns the Cypher parameter reference.

type PathElement

type PathElement struct {
	Node         *NodePattern
	Relationship *RelationshipPattern // nil for the first node
	Next         *PathElement         // nil for the last node
}

PathElement is one alternating step in a path: node (rel node)*. It holds exactly one NodePattern followed by zero or more (rel, node) pairs.

type PathPattern

type PathPattern struct {
	Pos      Position
	EndPos   Position
	Variable *string      // path variable, nil when absent
	Head     *PathElement // linked list of alternating node/rel steps
}

PathPattern represents a single path within a pattern: (a)-[r]->(b)-[s]->(c).

func (*PathPattern) String

func (p *PathPattern) String() string

String returns the Cypher path pattern.

type Pattern

type Pattern struct {
	Pos    Position
	EndPos Position
	Paths  []*PathPattern
}

Pattern represents the comma-separated list of path patterns in a MATCH or CREATE clause.

func (*Pattern) String

func (p *Pattern) String() string

String returns the comma-separated path patterns.

type PatternComprehension

type PatternComprehension struct {
	Pos        Position
	EndPos     Position
	Variable   *string // optional path variable
	Pattern    *PathPattern
	Predicate  Expression // nil when no WHERE clause
	Projection Expression
}

PatternComprehension is a pattern comprehension: [(a)-[r]->(b) WHERE pred | expr].

func (*PatternComprehension) String

func (p *PatternComprehension) String() string

String returns the Cypher pattern comprehension.

type Position

type Position struct {
	Line   uint32
	Column uint32
	Offset uint32
}

Position carries the source location of an AST node. Fields are populated by the parser (task 208); zero values are acceptable during construction.

func (Position) String

func (p Position) String() string

String returns "line:col" for diagnostic output.

type Projection

type Projection struct {
	Pos      Position
	EndPos   Position
	Distinct bool
	All      bool // SELECT *
	Items    []*ProjectionItem
	OrderBy  []*SortItem
	Skip     Expression // nil if absent
	Limit    Expression // nil if absent
}

Projection carries the column list shared by RETURN and WITH.

func (*Projection) String

func (p *Projection) String() string

String returns the Cypher representation of the projection body (without the leading RETURN / WITH keyword).

type ProjectionItem

type ProjectionItem struct {
	Pos    Position
	EndPos Position
	Expr   Expression
	Alias  *string // nil when no AS alias is present
}

ProjectionItem represents a single item in a RETURN or WITH projection, optionally aliased.

func (*ProjectionItem) String

func (p *ProjectionItem) String() string

String returns the Cypher representation of a projection item.

type Property

type Property struct {
	Pos      Position
	EndPos   Position
	Receiver Expression
	Key      string
}

Property is a property access: expr.key.

func (*Property) String

func (p *Property) String() string

String returns the Cypher property access.

type Query

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

Query is the top-level AST node. A query is either a single query or a UNION of single queries.

type RangeQuantifier

type RangeQuantifier struct {
	Pos    Position
	EndPos Position
	Min    *int64 // nil means no lower bound specified
	Max    *int64 // nil means no upper bound specified
}

RangeQuantifier represents a variable-length range on a relationship: *1..3.

func (*RangeQuantifier) String

func (r *RangeQuantifier) String() string

String returns the Cypher range quantifier.

type ReadingClause

type ReadingClause interface {
	Clause
	// contains filtered or unexported methods
}

ReadingClause is implemented by clauses that read from the graph without modifying it: MATCH, OPTIONAL MATCH, UNWIND, CALL (read-only).

type RelDirection

type RelDirection int8

RelDirection indicates the directionality of a relationship pattern.

const (
	// RelDirectionNone means the relationship has no specified direction: -[r]-
	RelDirectionNone RelDirection = iota
	// RelDirectionOutgoing means left-to-right: -[r]->
	RelDirectionOutgoing
	// RelDirectionIncoming means right-to-left: <-[r]-
	RelDirectionIncoming
)

func (RelDirection) String

func (d RelDirection) String() string

String returns the Cypher token pair for the direction (left side, right side).

type RelationshipPattern

type RelationshipPattern struct {
	Pos        Position
	EndPos     Position
	Variable   *string    // nil when anonymous
	Types      []string   // zero or more relationship types (OR semantics)
	Properties Expression // nil or MapLiteral / Parameter
	Direction  RelDirection
	Range      *RangeQuantifier // nil for fixed-length
}

RelationshipPattern represents a relationship within a path pattern.

-[r:REL_TYPE {prop: val}]->

func (*RelationshipPattern) String

func (r *RelationshipPattern) String() string

String returns the Cypher relationship pattern (including direction arrows).

type Remove

type Remove struct {
	Pos    Position
	EndPos Position
	Items  []*RemoveItem
}

Remove is a REMOVE clause.

func (*Remove) String

func (r *Remove) String() string

String returns the REMOVE clause.

type RemoveItem

type RemoveItem struct {
	Pos    Position
	EndPos Position
	Target Expression // Property or Variable
	Labels []string   // populated for REMOVE n:Label form
}

RemoveItem represents one item in a REMOVE clause.

func (*RemoveItem) String

func (r *RemoveItem) String() string

String returns the Cypher representation of a REMOVE item.

type Return

type Return struct {
	Pos        Position
	EndPos     Position
	Projection *Projection
}

Return is a RETURN clause.

func (*Return) String

func (r *Return) String() string

String returns the RETURN clause.

type Set

type Set struct {
	Pos    Position
	EndPos Position
	Items  []*SetItem
}

Set is a SET clause.

func (*Set) String

func (s *Set) String() string

String returns the SET clause.

type SetItem

type SetItem struct {
	Pos      Position
	EndPos   Position
	Target   Expression // Property or Variable
	Value    Expression // right-hand side; nil for label-set forms
	Operator string     // "=", "+=", or "" for label operations
	Labels   []string   // populated for SET n:Label1:Label2 form
}

SetItem represents one assignment in a SET clause: variable.property = expr or label assignment patterns.

func (*SetItem) String

func (s *SetItem) String() string

String returns the Cypher representation of a SET assignment.

type SingleQuery

type SingleQuery struct {
	Pos             Position
	EndPos          Position
	ReadingClauses  []ReadingClause
	UpdatingClauses []UpdatingClause
	Return          *Return // nil when the query has no RETURN
	With            []*With // WITH clauses that appear before RETURN
	// LeadingClauseCount records how many ReadingClauses precede the first
	// With clause in the original query text.  Only meaningful when
	// LeadingCountSet is true; set by the parser for MultiPartQ queries.
	// Used by the IR translator to interleave reading clauses and WITH clauses
	// in the correct order: leading[0..LeadingClauseCount-1] → With[*] →
	// trailing[LeadingClauseCount..].
	//
	// When LeadingCountSet is false (the zero value, or manually-constructed
	// ASTs), the translator falls back to the legacy order: all ReadingClauses
	// first, then all With clauses.
	LeadingClauseCount int
	// LeadingCountSet is true when the parser has explicitly populated
	// LeadingClauseCount.  False for SinglePartQ queries and for AST nodes
	// constructed directly in tests without going through the parser.
	LeadingCountSet bool
}

SingleQuery is a sequence of reading and updating clauses, terminated by an optional RETURN.

Example

ExampleSingleQuery shows how to inspect the clause structure of a parsed query by type-switching the typed AST nodes.

package main

import (
	"fmt"

	"github.com/FlavioCFOliveira/GoGraph/cypher/ast"
	"github.com/FlavioCFOliveira/GoGraph/cypher/parser"
)

func main() {
	q, err := parser.Parse("MATCH (n:Person) WHERE n.age > 18 RETURN n.name")
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	sq, ok := q.(*ast.SingleQuery)
	if !ok {
		fmt.Printf("unexpected root: %T\n", q)
		return
	}

	for _, clause := range sq.ReadingClauses {
		switch c := clause.(type) {
		case *ast.Match:
			fmt.Println("MATCH with WHERE:", c.Where != nil)
		default:
			fmt.Printf("other reading clause: %T\n", c)
		}
	}
	fmt.Println("RETURN present:", sq.Return != nil)
}
Output:
MATCH with WHERE: true
RETURN present: true

func (*SingleQuery) String

func (q *SingleQuery) String() string

String returns the Cypher representation of the single query.

type SliceExpr

type SliceExpr struct {
	Pos    Position
	EndPos Position
	Expr   Expression
	From   Expression // nil when absent
	To     Expression // nil when absent
}

SliceExpr is a slice expression: expr[from..to].

func (*SliceExpr) String

func (s *SliceExpr) String() string

String returns the Cypher slice expression.

type SortItem

type SortItem struct {
	Pos        Position
	EndPos     Position
	Expr       Expression
	Descending bool
}

SortItem represents a single ORDER BY term.

func (*SortItem) String

func (s *SortItem) String() string

String returns the Cypher representation of a sort item.

type StarLiteral

type StarLiteral struct {
	Pos    Position
	EndPos Position
}

StarLiteral represents the wildcard * used in COUNT(*) and similar constructs. Its String() returns "*" so that FunctionInvocation.String() produces "count(*)" rather than "count()".

func (*StarLiteral) String

func (*StarLiteral) String() string

String returns "*".

type StringLiteral

type StringLiteral struct {
	Pos    Position
	EndPos Position
	Value  string
}

StringLiteral is a single-quoted or double-quoted string literal.

func (*StringLiteral) String

func (n *StringLiteral) String() string

String returns the value enclosed in single quotes with internal single quotes escaped.

type SubscriptExpr

type SubscriptExpr struct {
	Pos    Position
	EndPos Position
	Expr   Expression
	Index  Expression
}

SubscriptExpr is a subscript access: expr[index].

func (*SubscriptExpr) String

func (s *SubscriptExpr) String() string

String returns the Cypher subscript expression.

type UnaryOp

type UnaryOp struct {
	Pos      Position
	EndPos   Position
	Operator string // e.g. "-", "NOT", "IS NULL", "IS NOT NULL"
	Operand  Expression
}

UnaryOp is a unary operator expression: OP expr.

func (*UnaryOp) String

func (u *UnaryOp) String() string

String returns the Cypher prefix expression.

type Union

type Union struct {
	Pos    Position
	EndPos Position
	All    bool
	Query  *SingleQuery
}

Union is a standalone UNION clause (used as an intermediate representation for some parsing strategies). MultiQuery is preferred for the final AST.

func (*Union) String

func (u *Union) String() string

String returns the UNION clause.

type Unwind

type Unwind struct {
	Pos      Position
	EndPos   Position
	Expr     Expression
	Variable string
}

Unwind is an UNWIND clause: UNWIND expr AS variable.

func (*Unwind) String

func (u *Unwind) String() string

String returns the UNWIND clause.

type UpdatingClause

type UpdatingClause interface {
	Clause
	// contains filtered or unexported methods
}

UpdatingClause is implemented by clauses that mutate the graph: CREATE, MERGE, SET, REMOVE, DELETE, DETACH DELETE, CALL (write).

type Variable

type Variable struct {
	Pos    Position
	EndPos Position
	Name   string
}

Variable is a named reference: n, r, x.

func (*Variable) String

func (v *Variable) String() string

String returns the variable name.

type Where

type Where struct {
	Pos       Position
	EndPos    Position
	Predicate Expression
}

Where represents a WHERE predicate attached to MATCH, WITH, or similar. It is modelled as a standalone node rather than a field because it can carry its own position and is shared between reading and filtering clauses.

func (*Where) String

func (w *Where) String() string

String returns the WHERE clause.

type With

type With struct {
	Pos        Position
	EndPos     Position
	Projection *Projection
	Where      *Where // nil when no WHERE predicate
}

With is a WITH clause, used for intermediate projections and filtering.

func (*With) String

func (w *With) String() string

String returns the WITH clause.

type YieldItem

type YieldItem struct {
	Pos    Position
	EndPos Position
	Name   string
	Alias  *string // nil when no AS alias
}

YieldItem represents a single item in a YIELD clause.

func (*YieldItem) String

func (y *YieldItem) String() string

String returns the YIELD item.

Jump to

Keyboard shortcuts

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