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 ¶
- func Print(q Query) string
- type BinaryOp
- type BoolLiteral
- type Call
- type CaseAlternative
- type CaseExpression
- type Clause
- type CountSubquery
- type Create
- type Delete
- type DetachDelete
- type ExistsSubquery
- type Expression
- type FloatLiteral
- type FunctionInvocation
- type IntLiteral
- type LabelPredicate
- type ListComprehension
- type ListLiteral
- type MapLiteral
- type MapProjection
- type MapProjectionItem
- type Match
- type Merge
- type MultiQuery
- type Node
- type NodePattern
- type NullLiteral
- type OptionalMatch
- type OverflowIntLit
- type Parameter
- type PathElement
- type PathPattern
- type Pattern
- type PatternComprehension
- type Position
- type Projection
- type ProjectionItem
- type Property
- type Query
- type RangeQuantifier
- type ReadingClause
- type ReduceExpr
- type RelDirection
- type RelationshipPattern
- type Remove
- type RemoveItem
- type Return
- type Set
- type SetItem
- type ShortestKind
- type SingleQuery
- type SliceExpr
- type SortItem
- type StarLiteral
- type StringLiteral
- type SubscriptExpr
- type UnaryOp
- type Union
- type Unwind
- type UpdatingClause
- type Variable
- type Where
- type With
- type YieldItem
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Print ¶
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.
type BoolLiteral ¶
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
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 Delete ¶
type Delete struct {
Pos Position
EndPos Position
Expressions []Expression
}
Delete is a 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 ¶
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 ¶
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}.
The map-projection production lives in the ANTLR grammar (cypher/parser/grammar/CypherParser.g4, the mapProjection / mapProjectionItem rules); the parser visitor (github.com/FlavioCFOliveira/GoGraph/cypher/parser VisitMapProjection) constructs this node, which is then evaluated by (github.com/FlavioCFOliveira/GoGraph/cypher/expr evalMapProjection) and type-checked by the semantic analyser. Map projection is an accepted openCypher extension (CIP2014-12-12); it is NOT part of the openCypher TCK, so it does not affect TCK conformance.
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.
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.
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 ¶
NullLiteral is the literal 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 OverflowIntLit ¶ added in v0.3.0
type OverflowIntLit struct {
Pos Position
EndPos Position
// Text holds the raw decimal digits including any leading sign character.
Text string
}
OverflowIntLit is a sentinel for decimal integer tokens that exceed the int64 range. In most expression contexts it becomes an IntegerOverflow compile error; in the special case where a fractional accessor follows (e.g. NNN.0 lexed as NNN + . + 0), visitPropertyExpression promotes it to a FloatLiteral instead.
func (*OverflowIntLit) String ¶ added in v0.3.0
func (o *OverflowIntLit) String() string
String returns the raw decimal text of the overflowing integer.
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.
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
// Shortest classifies a shortestPath()/allShortestPaths() wrapper around
// this path (ShortestNone for an ordinary path). Set by the parser's
// post-AST shortest-path pass (rmp #1690).
Shortest ShortestKind
}
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, re-wrapping a shortestPath / allShortestPaths pattern in its function form so the rendering round-trips.
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.
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 ¶
Position carries the source location of an AST node. Fields are populated by the parser (task 208); zero values are acceptable during construction.
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.
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 ReduceExpr ¶ added in v0.3.0
type ReduceExpr struct {
Pos Position
EndPos Position
AccVar string
Init Expression
ElemVar string
Source Expression
Projection Expression
}
ReduceExpr is a reduce expression: reduce(acc = init, x IN list | expr). AccVar is the accumulator variable name, Init is the initial value expression, ElemVar is the loop variable name, Source is the list expression, and Projection is the accumulation expression evaluated on each iteration.
func (*ReduceExpr) String ¶ added in v0.3.0
func (r *ReduceExpr) String() string
String returns the Cypher reduce expression.
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.
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.
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.
type ShortestKind ¶ added in v0.6.0
type ShortestKind uint8
ShortestKind classifies a path pattern wrapped in shortestPath(...) or allShortestPaths(...). ShortestNone (the zero value) means an ordinary (non-shortest) path. The parser records the kind by stripping the wrapper keyword in a pre-lex normalizer and stamping it back onto the matching named PathPattern after the AST is built (rmp #1690): the grammar itself is left untouched, so the proven TCK-green parser is unchanged.
const ( // ShortestNone is an ordinary path pattern (no shortest-path wrapper). ShortestNone ShortestKind = iota // ShortestSingle is shortestPath(...): a single minimum-hop path. ShortestSingle // ShortestAll is allShortestPaths(...): every minimum-hop path. ShortestAll )
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].
type SortItem ¶
type SortItem struct {
Pos Position
EndPos Position
Expr Expression
Descending bool
}
SortItem represents a single ORDER BY term.
type StarLiteral ¶
StarLiteral represents the wildcard * used in COUNT(*) and similar constructs. Its String() returns "*" so that FunctionInvocation.String() produces "count(*)" rather than "count()".
type StringLiteral ¶
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.
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.
type Unwind ¶
type Unwind struct {
Pos Position
EndPos Position
Expr Expression
Variable string
}
Unwind is an UNWIND clause: UNWIND expr AS variable.
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 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.