///|
/// Every concrete syntax tree node kind in strict Rego v1.
#derive(Eq, Compare, Hash, Debug)
pub(all) enum SyntaxKind {
  // Roots
  Module
  Query
  // Declarations
  PackageDecl
  ImportDecl
  ImportAlias
  // Rules
  Rule
  DefaultRule
  RuleHead
  RuleHeadRef
  RuleArgs
  RuleContainsKey
  RuleValue
  RuleBody
  ElseBranch
  // Expressions and modifiers
  Expr
  NotExpr
  SomeDecl
  SomeIn
  EveryExpr
  AssignExpr
  UnifyExpr
  InExpr
  BinaryExpr
  UnaryExpr
  WithModifier
  // Terms and references
  Ref
  RefDot
  RefBracket
  CallExpr
  ArgList
  ParenTerm
  Literal
  Var
  TemplateString
  TemplatePartText
  TemplatePartExpr
  ArrayLiteral
  ObjectLiteral
  ObjectEntry
  SetLiteral
  EmptySet
  ArrayComprehension
  ObjectComprehension
  SetComprehension
  // Error recovery wrapper
  Error
}

///|
/// A child element of a green CST node: either a leaf token or an interior node.
#derive(Eq, Hash, Debug)
pub(all) enum SyntaxElement {
  Token(SyntaxToken)
  Node(SyntaxNode)
}

///|
pub fn SyntaxElement::span(self : SyntaxElement) -> SourceSpan {
  match self {
    Token(tok) => tok.span()
    Node(node) => node.span()
  }
}

///|
/// An immutable green CST node preserving exact token order, trivia and spans.
#derive(Eq, Hash, Debug)
struct SyntaxNode {
  kind : SyntaxKind
  children : ReadOnlyArray[SyntaxElement]
  span : SourceSpan
}

///|
fn SyntaxNode::make(
  kind : SyntaxKind,
  children : Array[SyntaxElement],
  fallback_span : SourceSpan,
) -> SyntaxNode {
  let span = if children.is_empty() {
    fallback_span
  } else {
    let mut s = children[0].span()
    for i in 1.. SyntaxKind {
  self.kind
}

///|
/// Returns all direct children (nodes and tokens, including trivia).
pub fn SyntaxNode::children(self : SyntaxNode) -> ReadOnlyArray[SyntaxElement] {
  self.children
}

///|
/// Returns the UTF-16 source span covering this node.
pub fn SyntaxNode::span(self : SyntaxNode) -> SourceSpan {
  self.span
}

///|
fn SyntaxNode::write_source(self : SyntaxNode, buf : StringBuilder) -> Unit {
  for child in self.children {
    match child {
      Token(tok) => buf.write_string(tok.text())
      Node(node) => node.write_source(buf)
    }
  }
}

///|
/// Reconstructs the exact original source slice covered by this CST node.
pub fn SyntaxNode::to_source(self : SyntaxNode) -> String {
  let buf = StringBuilder()
  self.write_source(buf)
  buf.to_string()
}

///|
/// Returns the direct child `SyntaxNode`s in source order.
pub fn SyntaxNode::child_nodes(self : SyntaxNode) -> ReadOnlyArray[SyntaxNode] {
  let out = []
  for child in self.children {
    if child is Node(node) {
      out.push(node)
    }
  }
  ReadOnlyArray::from_array(out)
}

///|
/// Returns the direct child `SyntaxToken`s in source order.
pub fn SyntaxNode::child_tokens(
  self : SyntaxNode,
) -> ReadOnlyArray[SyntaxToken] {
  let out = []
  for child in self.children {
    if child is Token(tok) {
      out.push(tok)
    }
  }
  ReadOnlyArray::from_array(out)
}

///|
/// Returns direct children excluding trivia tokens and `Eof`.
pub fn SyntaxNode::non_trivia_children(
  self : SyntaxNode,
) -> ReadOnlyArray[SyntaxElement] {
  let out = []
  for child in self.children {
    match child {
      Token(tok) =>
        if !tok.kind().is_trivia() && tok.kind() != Eof {
          out.push(child)
        }
      Node(_) => out.push(child)
    }
  }
  ReadOnlyArray::from_array(out)
}

///|
/// The category of a syntax diagnostic recorded during lexing or parsing.
#derive(Eq, Hash, Debug)
pub(all) enum SyntaxDiagnosticKind {
  Lexical(LexErrorKind)
  UnexpectedToken
  ExpectedToken
  MissingIfKeyword
  MissingContainsKeyword
  ReservedKeywordAsVar
  DuplicatePackage
  MissingPackage
  InvalidRuleHead
  InvalidExpression
  UnclosedDelimiter
  UnexpectedPackageInQuery
}

///|
/// An immutable syntax diagnostic with kind, UTF-16 span and message.
#derive(Eq, Hash, Debug)
struct SyntaxDiagnostic {
  kind : SyntaxDiagnosticKind
  span : SourceSpan
  /// Human-readable explanation (free text).
  message : String
}

///|
/// Creates an immutable syntax diagnostic.
pub fn SyntaxDiagnostic::SyntaxDiagnostic(
  kind~ : SyntaxDiagnosticKind,
  span~ : SourceSpan,
  message~ : String,
) -> SyntaxDiagnostic {
  { kind, span, message, }
}

///|
/// Returns the category of this diagnostic.
pub fn SyntaxDiagnostic::kind(self : SyntaxDiagnostic) -> SyntaxDiagnosticKind {
  self.kind
}

///|
/// Returns the UTF-16 source span of this diagnostic.
pub fn SyntaxDiagnostic::span(self : SyntaxDiagnostic) -> SourceSpan {
  self.span
}

///|
/// Returns the human-readable diagnostic message.
pub fn SyntaxDiagnostic::message(self : SyntaxDiagnostic) -> String {
  self.message
}

///|
pub impl Show for SyntaxDiagnostic with fn output(self, logger) {
  logger.write_string("\{self.span}: \{self.message}")
}

///|
/// The lossless result of parsing a Rego v1 module or standalone query.
#derive(Eq, Debug)
struct ParseResult {
  root : SyntaxNode
  diagnostics : ReadOnlyArray[SyntaxDiagnostic]
}

///|
/// Creates an immutable parse result from a CST root and its diagnostics.
pub fn ParseResult::ParseResult(
  root~ : SyntaxNode,
  diagnostics~ : ArrayView[SyntaxDiagnostic],
) -> ParseResult {
  { root, diagnostics: ReadOnlyArray::from_array(diagnostics.to_owned()), }
}

///|
/// Returns the root green CST node.
pub fn ParseResult::root(self : ParseResult) -> SyntaxNode {
  self.root
}

///|
/// Returns all lexical and syntax diagnostics in source order.
pub fn ParseResult::diagnostics(
  self : ParseResult,
) -> ReadOnlyArray[SyntaxDiagnostic] {
  self.diagnostics
}

///|
/// Reports whether parsing produced any diagnostic.
pub fn ParseResult::has_errors(self : ParseResult) -> Bool {
  !self.diagnostics.is_empty()
}

///|
/// Reconstructs the exact original source text from the CST root.
pub fn ParseResult::to_source(self : ParseResult) -> String {
  self.root.to_source()
}

///|
/// Internal opaque checkpoint index inside a `CstBuilder`.
priv struct Checkpoint {
  index : Int32
}

///|
/// Internal parser event stream supporting O(N) Pratt left-wrapping via
/// `forward_parent` links (Rowan / rust-analyzer technique).
priv enum ParseEvent {
  StartNode(SyntaxKind, Int32)
  AddToken(SyntaxToken)
  FinishNode
  Tombstone
}

///|
/// Internal event-driven builder that constructs an immutable green CST in one
/// linear pass, supporting O(N) Pratt left-wrapping via checkpoints.
priv struct CstBuilder {
  events : Array[ParseEvent]
}

///|
fn CstBuilder::CstBuilder() -> CstBuilder {
  { events: [], }
}

///|
fn CstBuilder::checkpoint(self : CstBuilder) -> Checkpoint {
  { index: self.events.length(), }
}

///|
fn CstBuilder::start_node(self : CstBuilder, kind : SyntaxKind) -> Int32 {
  let idx = self.events.length()
  self.events.push(StartNode(kind, 0))
  idx
}

///|
fn CstBuilder::start_node_at(
  self : CstBuilder,
  checkpoint : Checkpoint,
  kind : SyntaxKind,
) -> Unit {
  let parent_idx = self.events.length()
  self.events.push(StartNode(kind, 0))
  let mut cur = checkpoint.index
  while cur < parent_idx {
    match self.events[cur] {
      StartNode(k, fp) =>
        if fp == 0 {
          self.events[cur] = StartNode(k, parent_idx - cur)
          return
        } else {
          cur = cur + fp
        }
      _ => return
    }
  }
}

///|
fn CstBuilder::token(self : CstBuilder, tok : SyntaxToken) -> Unit {
  self.events.push(AddToken(tok))
}

///|
fn CstBuilder::finish_node(self : CstBuilder) -> Unit {
  self.events.push(FinishNode)
}

///|
/// Materializes the recorded events into an immutable green `SyntaxNode` root.
fn CstBuilder::build(
  self : CstBuilder,
  fallback_span : SourceSpan,
) -> SyntaxNode {
  let events = self.events
  let stack : Array[(SyntaxKind, Array[SyntaxElement])] = []
  let forward_kinds : Array[SyntaxKind] = []
  let mut last_span = fallback_span
  for i in 0.. ()
      StartNode(kind, fp) => {
        forward_kinds.clear()
        forward_kinds.push(kind)
        events[i] = Tombstone
        let mut cur = i
        let mut delta = fp
        while delta > 0 {
          cur = cur + delta
          match events[cur] {
            StartNode(pk, next_fp) => {
              forward_kinds.push(pk)
              events[cur] = Tombstone
              delta = next_fp
            }
            _ => break
          }
        }
        let mut j = forward_kinds.length() - 1
        while j >= 0 {
          stack.push((forward_kinds[j], []))
          j -= 1
        }
      }
      AddToken(tok) => {
        last_span = tok.span()
        if !stack.is_empty() {
          stack[stack.length() - 1].1.push(Token(tok))
        }
      }
      FinishNode =>
        if stack.length() > 1 {
          guard stack.pop() is Some((kind, children)) else { continue }
          let node = SyntaxNode::make(kind, children, last_span)
          last_span = node.span()
          stack[stack.length() - 1].1.push(Node(node))
        }
    }
  }
  while stack.length() > 1 {
    guard stack.pop() is Some((kind, children)) else { break }
    let node = SyntaxNode::make(kind, children, last_span)
    last_span = node.span()
    stack[stack.length() - 1].1.push(Node(node))
  }
  match stack.pop() {
    Some((kind, children)) => SyntaxNode::make(kind, children, fallback_span)
    None => SyntaxNode::make(Error, [], fallback_span)
  }
}