///|
/// Raised when an AST domain value breaks its construction invariants.
#derive(Eq, Debug)
pub(all) suberror AstError {
  /// Identifier is empty or starts/contains invalid characters.
  InvalidIdent(text~ : String)
  /// Identifier is a reserved Rego v1 keyword (`if`, `in`, `every`, etc.).
  ReservedKeyword(text~ : String)
  /// Number literal is empty or malformed (for example leading zero `01`).
  InvalidNumberLiteral(text~ : String)
  /// Package path has zero segments.
  EmptyPackagePath
}

///|
/// Raised when lowering a CST to an immutable Rego v1 AST fails.
#derive(Eq, Debug)
pub(all) suberror LowerError {
  /// The CST contained one or more lexical or syntax diagnostics.
  SyntaxErrors(ReadOnlyArray[@syntax.SyntaxDiagnostic])
  /// A `# METADATA` comment block failed YAML or schema validation.
  AnnotationFailure(AnnotationError)
  /// The CST node did not match the expected structure.
  InvalidTree(span~ : @syntax.SourceSpan, message~ : String)
}

///|
pub impl Show for LowerError with fn output(self, logger) {
  match self {
    SyntaxErrors(diags) =>
      if diags.is_empty() {
        logger.write_string("syntax errors")
      } else {
        logger.write_string("syntax error: \{diags[0]}")
      }
    AnnotationFailure(err) =>
      match err {
        InvalidYaml(span~, message~) =>
          logger.write_string("invalid METADATA YAML at \{span}: \{message}")
        NotAMapping(span~) =>
          logger.write_string("METADATA at \{span} is not a YAML mapping")
        InvalidScope(span~, value~) =>
          logger.write_string("invalid METADATA scope `\{value}` at \{span}")
        InvalidFieldShape(span~, field~, message~) =>
          logger.write_string(
            "invalid METADATA field `\{field}` at \{span}: \{message}",
          )
      }
    InvalidTree(span~, message~) =>
      logger.write_string("invalid CST at \{span}: \{message}")
  }
}

///|
fn is_reserved_v1_var(text : String) -> Bool {
  match text {
    "package"
    | "import"
    | "as"
    | "default"
    | "else"
    | "not"
    | "some"
    | "with"
    | "null"
    | "true"
    | "false"
    | "every"
    | "if"
    | "in" => true
    _ => false
  }
}

///|
fn is_valid_ident_chars(text : String) -> Bool {
  if text.is_empty() {
    return false
  }
  let c0 = text.code_unit_at(0).to_int()
  let start_ok = (c0 >= 0x41 && c0 <= 0x5A) ||
    (c0 >= 0x61 && c0 <= 0x7A) ||
    c0 == 0x5F
  if !start_ok {
    return false
  }
  for i in 1..= 0x41 && c <= 0x5A) ||
      (c >= 0x61 && c <= 0x7A) ||
      (c >= 0x30 && c <= 0x39) ||
      c == 0x5F
    if !ok {
      return false
    }
  }
  true
}

///|
/// A validated Rego v1 variable/rule identifier. In OPA v1.23.0, `contains`,
/// `and`, `or` and `_` are valid identifiers, while `if`, `in`, `every` and
/// core keywords are rejected as standalone variables.
#derive(Eq, Compare, Hash, Debug)
struct Ident {
  text : String
}

///|
pub fn Ident::Ident(text : String) -> Ident raise AstError {
  if !is_valid_ident_chars(text) {
    raise InvalidIdent(text~)
  }
  if is_reserved_v1_var(text) {
    raise ReservedKeyword(text~)
  }
  { text, }
}

///|
/// Internal constructor for keyword-headed references (`if.foo`, `not.bar`)
/// where OPA v1.23.0 permits a keyword as the root identifier of a `Ref`.
fn Ident::ref_head_unchecked(text : String) -> Ident {
  { text, }
}

///|
pub fn Ident::to_string(self : Ident) -> String {
  self.text
}

///|
pub impl Show for Ident with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
/// Validated raw text of a Rego numeric literal, preserved verbatim so Phase 2
/// can parse exact arbitrary-precision decimals without IEEE-754 loss.
#derive(Eq, Hash, Debug)
struct NumberLiteral {
  raw : String
}

///|
fn is_valid_number_text(text : String) -> Bool {
  let len = text.length()
  if len == 0 {
    return false
  }
  let mut i = 0
  let c0 = text.code_unit_at(0).to_int()
  if c0 == 0x2E {
    i = 1
    let frac_start = i
    while i < len {
      let c = text.code_unit_at(i).to_int()
      if c >= 0x30 && c <= 0x39 {
        i += 1
      } else {
        break
      }
    }
    if i == frac_start {
      return false
    }
  } else {
    if c0 < 0x30 || c0 > 0x39 {
      return false
    }
    if c0 == 0x30 {
      i = 1
      if i < len {
        let c1 = text.code_unit_at(1).to_int()
        if c1 >= 0x30 && c1 <= 0x39 {
          return false // leading zero
        }
      }
    } else {
      while i < len {
        let c = text.code_unit_at(i).to_int()
        if c >= 0x30 && c <= 0x39 {
          i += 1
        } else {
          break
        }
      }
    }
    if i < len && text.code_unit_at(i).to_int() == 0x2E {
      i += 1
      let frac_start = i
      while i < len {
        let c = text.code_unit_at(i).to_int()
        if c >= 0x30 && c <= 0x39 {
          i += 1
        } else {
          break
        }
      }
      if i == frac_start {
        return false
      }
    }
  }
  if i < len {
    let e = text.code_unit_at(i).to_int()
    if e == 0x65 || e == 0x45 {
      i += 1
      if i < len {
        let s = text.code_unit_at(i).to_int()
        if s == 0x2B || s == 0x2D {
          i += 1
        }
      }
      let exp_start = i
      while i < len {
        let c = text.code_unit_at(i).to_int()
        if c >= 0x30 && c <= 0x39 {
          i += 1
        } else {
          break
        }
      }
      if i == exp_start {
        return false
      }
    }
  }
  i == len
}

///|
pub fn NumberLiteral::NumberLiteral(
  raw : String,
) -> NumberLiteral raise AstError {
  if !is_valid_number_text(raw) {
    raise InvalidNumberLiteral(text=raw)
  }
  { raw, }
}

///|
pub fn NumberLiteral::raw(self : NumberLiteral) -> String {
  self.raw
}

///|
pub impl Show for NumberLiteral with fn output(self, logger) {
  logger.write_string(self.raw)
}

///|
/// Assignment or unification operator in rule heads.
#derive(Eq, Hash, Debug)
pub(all) enum AssignOp {
  Assign
  Unify
}

///|
/// Binary infix operator in Rego v1 expressions (excluding `:=`, `=` and `in`).
#derive(Eq, Hash, Debug)
pub(all) enum BinaryOp {
  Equal
  Neq
  Lt
  Gt
  Lte
  Gte
  Or
  And
  Add
  Sub
  Mul
  Quo
  Rem
}

///|
/// A validated dot-chained reference key (`a.key`, `a.if`, `a.default`).
/// Accepts any valid Rego identifier character sequence, including keywords.
#derive(Eq, Compare, Hash, Debug)
struct DotKey {
  text : String
}

///|
/// Constructs a validated dot-chained reference key.
pub fn DotKey::DotKey(text : String) -> DotKey raise AstError {
  if !is_valid_ident_chars(text) {
    raise InvalidIdent(text~)
  }
  { text, }
}

///|
/// Returns the raw text of this dot key.
pub fn DotKey::to_string(self : DotKey) -> String {
  self.text
}

///|
pub impl Show for DotKey with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
/// A paired assignment or unification operator and value term, preventing
/// mismatched `(Some(op), None)` or `(None, Some(term))` states.
#derive(Eq, Debug)
struct AssignedValue {
  op : AssignOp
  value : Term
}

///|
/// Constructs an assigned value pairing an operator with its term.
pub fn AssignedValue::AssignedValue(
  op~ : AssignOp,
  value~ : Term,
) -> AssignedValue {
  { op, value, }
}

///|
/// Returns the assignment or unification operator.
pub fn AssignedValue::op(self : AssignedValue) -> AssignOp {
  self.op
}

///|
/// Returns the assigned value term.
pub fn AssignedValue::value(self : AssignedValue) -> Term {
  self.value
}

///|
/// One segment of a Rego reference (`a.b` or `a[expr]`).
#derive(Eq, Debug)
pub(all) enum RefSegment {
  Dot(DotKey)
  Bracket(Term)
}

///|
/// A Rego reference chain: base term followed by zero or more segments.
#derive(Eq, Debug)
struct Ref {
  base : Term
  segments : ReadOnlyArray[RefSegment]
  span : @syntax.SourceSpan
}

///|
pub fn Ref::Ref(
  base~ : Term,
  segments~ : ArrayView[RefSegment],
  span~ : @syntax.SourceSpan,
) -> Ref {
  { base, segments: ReadOnlyArray::from_array(segments.to_owned()), span, }
}

///|
pub fn Ref::base(self : Ref) -> Term {
  self.base
}

///|
pub fn Ref::segments(self : Ref) -> ReadOnlyArray[RefSegment] {
  self.segments
}

///|
pub fn Ref::span(self : Ref) -> @syntax.SourceSpan {
  self.span
}

///|
/// A validated non-empty package path (`package a.b["c-d"]`).
#derive(Eq, Debug)
struct PackagePath {
  segments : ReadOnlyArray[RefSegment]
  span : @syntax.SourceSpan
}

///|
pub fn PackagePath::PackagePath(
  segments~ : ArrayView[RefSegment],
  span~ : @syntax.SourceSpan,
) -> PackagePath raise AstError {
  if segments.is_empty() {
    raise EmptyPackagePath
  }
  { segments: ReadOnlyArray::from_array(segments.to_owned()), span, }
}

///|
pub fn PackagePath::segments(self : PackagePath) -> ReadOnlyArray[RefSegment] {
  self.segments
}

///|
pub fn PackagePath::span(self : PackagePath) -> @syntax.SourceSpan {
  self.span
}

///|
/// Formats dot segments joined by `.` and bracket segments with `[...]`.
pub fn PackagePath::to_string(self : PackagePath) -> String {
  let buf = StringBuilder()
  for i in 0.. {
        if i > 0 {
          buf.write_char('.')
        }
        buf.write_string(name.to_string())
      }
      Bracket(term) =>
        match term.kind() {
          String(s) => {
            buf.write_string("[\"")
            buf.write_string(s)
            buf.write_string("\"]")
          }
          _ => buf.write_string("[...]")
        }
    }
  }
  buf.to_string()
}

///|
/// One segment of a Rego v1.9+ template string (`$"..."` or `` $`...` ``).
#derive(Eq, Debug)
pub(all) enum TemplatePart {
  Literal(String)
  Expr(Expr)
}

///|
/// Every Rego v1 term kind.
#derive(Eq, Debug)
pub(all) enum TermKind {
  Null
  Bool(Bool)
  Number(NumberLiteral)
  String(String)
  TemplateString(raw~ : Bool, parts~ : ReadOnlyArray[TemplatePart])
  Var(Ident)
  Ref(Ref)
  Call(callee~ : Term, args~ : ReadOnlyArray[Term])
  UnaryNeg(Term)
  Binary(BinaryOp, Term, Term)
  In(key~ : Term?, value~ : Term, domain~ : Term)
  Array(ReadOnlyArray[Term])
  Set(ReadOnlyArray[Term])
  Object(ReadOnlyArray[(Term, Term)])
  ArrayComprehension(term~ : Term, body~ : RuleBody)
  SetComprehension(term~ : Term, body~ : RuleBody)
  ObjectComprehension(key~ : Term, value~ : Term, body~ : RuleBody)
}

///|
/// An immutable Rego v1 term paired with its UTF-16 source span.
#derive(Eq, Debug)
struct Term {
  kind : TermKind
  span : @syntax.SourceSpan
}

///|
pub fn Term::Term(kind~ : TermKind, span~ : @syntax.SourceSpan) -> Term {
  { kind, span, }
}

///|
pub fn Term::kind(self : Term) -> TermKind {
  self.kind
}

///|
pub fn Term::span(self : Term) -> @syntax.SourceSpan {
  self.span
}

///|
/// A `with  as ` modifier attached to an expression.
#derive(Eq, Debug)
struct WithModifier {
  target : Ref
  value : Term
  span : @syntax.SourceSpan
}

///|
pub fn WithModifier::WithModifier(
  target~ : Ref,
  value~ : Term,
  span~ : @syntax.SourceSpan,
) -> WithModifier {
  { target, value, span, }
}

///|
pub fn WithModifier::target(self : WithModifier) -> Ref {
  self.target
}

///|
pub fn WithModifier::value(self : WithModifier) -> Term {
  self.value
}

///|
pub fn WithModifier::span(self : WithModifier) -> @syntax.SourceSpan {
  self.span
}

///|
/// Every Rego v1 expression form.
#derive(Eq, Debug)
pub(all) enum ExprKind {
  Term(Term)
  Assign(Term, Term)
  Unify(Term, Term)
  Not(ExprKind)
  SomeDecl(first~ : Ident, rest~ : ReadOnlyArray[Ident])
  SomeIn(key~ : Term?, value~ : Term, domain~ : Term)
  Every(key~ : Ident?, value~ : Ident, domain~ : Term, body~ : RuleBody)
}

///|
/// One Rego v1 expression with optional `with` modifiers and source span.
#derive(Eq, Debug)
struct Expr {
  kind : ExprKind
  with_modifiers : ReadOnlyArray[WithModifier]
  span : @syntax.SourceSpan
}

///|
pub fn Expr::Expr(
  kind~ : ExprKind,
  with_modifiers~ : ArrayView[WithModifier],
  span~ : @syntax.SourceSpan,
) -> Expr {
  {
    kind,
    with_modifiers: ReadOnlyArray::from_array(with_modifiers.to_owned()),
    span,
  }
}

///|
pub fn Expr::kind(self : Expr) -> ExprKind {
  self.kind
}

///|
pub fn Expr::with_modifiers(self : Expr) -> ReadOnlyArray[WithModifier] {
  self.with_modifiers
}

///|
pub fn Expr::span(self : Expr) -> @syntax.SourceSpan {
  self.span
}

///|
/// An ordered conjunction of expressions forming a rule, `every`, or
/// comprehension body.
#derive(Eq, Debug)
struct RuleBody {
  exprs : ReadOnlyArray[Expr]
  span : @syntax.SourceSpan
}

///|
pub fn RuleBody::RuleBody(
  exprs~ : ArrayView[Expr],
  span~ : @syntax.SourceSpan,
) -> RuleBody {
  { exprs: ReadOnlyArray::from_array(exprs.to_owned()), span, }
}

///|
pub fn RuleBody::exprs(self : RuleBody) -> ReadOnlyArray[Expr] {
  self.exprs
}

///|
pub fn RuleBody::span(self : RuleBody) -> @syntax.SourceSpan {
  self.span
}

///|
/// One `else` branch attached to a rule.
#derive(Eq, Debug)
struct ElseBranch {
  assigned : AssignedValue?
  body : RuleBody?
  span : @syntax.SourceSpan
}

///|
/// Constructs an `else` branch.
pub fn ElseBranch::ElseBranch(
  assigned~ : AssignedValue?,
  body~ : RuleBody?,
  span~ : @syntax.SourceSpan,
) -> ElseBranch {
  { assigned, body, span, }
}

///|
/// Returns the optional assigned value of this `else` branch.
pub fn ElseBranch::assigned(self : ElseBranch) -> AssignedValue? {
  self.assigned
}

///|
/// Returns the optional body of this `else` branch.
pub fn ElseBranch::body(self : ElseBranch) -> RuleBody? {
  self.body
}

///|
/// Returns the UTF-16 span of this `else` branch.
pub fn ElseBranch::span(self : ElseBranch) -> @syntax.SourceSpan {
  self.span
}

///|
/// The algebraic classification of a strict Rego v1 rule head.
#derive(Eq, Debug)
pub(all) enum RuleHead {
  Complete(ref_head~ : Ref, assigned~ : AssignedValue?)
  PartialSet(ref_head~ : Ref, key~ : Term)
  PartialObject(ref_head~ : Ref, key~ : Term, assigned~ : AssignedValue)
  Function(
    ref_head~ : Ref,
    args~ : ReadOnlyArray[Term],
    assigned~ : AssignedValue?,
  )
  Default(
    ref_head~ : Ref,
    args~ : ReadOnlyArray[Term],
    assigned~ : AssignedValue,
  )
}

///|
/// One Rego v1 rule (complete, partial set, partial object, function or default).
#derive(Eq, Debug)
struct Rule {
  head : RuleHead
  body : RuleBody?
  else_branches : ReadOnlyArray[ElseBranch]
  annotations : ReadOnlyArray[Annotation]
  span : @syntax.SourceSpan
}

///|
pub fn Rule::Rule(
  head~ : RuleHead,
  body~ : RuleBody?,
  else_branches~ : ArrayView[ElseBranch],
  annotations~ : ArrayView[Annotation],
  span~ : @syntax.SourceSpan,
) -> Rule {
  {
    head,
    body,
    else_branches: ReadOnlyArray::from_array(else_branches.to_owned()),
    annotations: ReadOnlyArray::from_array(annotations.to_owned()),
    span,
  }
}

///|
pub fn Rule::head(self : Rule) -> RuleHead {
  self.head
}

///|
pub fn Rule::body(self : Rule) -> RuleBody? {
  self.body
}

///|
pub fn Rule::else_branches(self : Rule) -> ReadOnlyArray[ElseBranch] {
  self.else_branches
}

///|
pub fn Rule::annotations(self : Rule) -> ReadOnlyArray[Annotation] {
  self.annotations
}

///|
pub fn Rule::span(self : Rule) -> @syntax.SourceSpan {
  self.span
}

///|
/// One `import  [as ]` declaration.
#derive(Eq, Debug)
struct Import {
  path : Ref
  alias_name : Ident?
  span : @syntax.SourceSpan
}

///|
pub fn Import::Import(
  path~ : Ref,
  alias_name~ : Ident?,
  span~ : @syntax.SourceSpan,
) -> Import {
  { path, alias_name, span, }
}

///|
pub fn Import::path(self : Import) -> Ref {
  self.path
}

///|
pub fn Import::alias_name(self : Import) -> Ident? {
  self.alias_name
}

///|
pub fn Import::span(self : Import) -> @syntax.SourceSpan {
  self.span
}

///|
/// A parsed and lowered Rego v1 module.
#derive(Eq, Debug)
struct Module {
  package_path : PackagePath
  package_annotations : ReadOnlyArray[Annotation]
  imports : ReadOnlyArray[Import]
  rules : ReadOnlyArray[Rule]
  span : @syntax.SourceSpan
}

///|
pub fn Module::Module(
  package_path~ : PackagePath,
  package_annotations~ : ArrayView[Annotation],
  imports~ : ArrayView[Import],
  rules~ : ArrayView[Rule],
  span~ : @syntax.SourceSpan,
) -> Module {
  {
    package_path,
    package_annotations: ReadOnlyArray::from_array(
      package_annotations.to_owned(),
    ),
    imports: ReadOnlyArray::from_array(imports.to_owned()),
    rules: ReadOnlyArray::from_array(rules.to_owned()),
    span,
  }
}

///|
pub fn Module::package_path(self : Module) -> PackagePath {
  self.package_path
}

///|
pub fn Module::package_annotations(self : Module) -> ReadOnlyArray[Annotation] {
  self.package_annotations
}

///|
pub fn Module::imports(self : Module) -> ReadOnlyArray[Import] {
  self.imports
}

///|
pub fn Module::rules(self : Module) -> ReadOnlyArray[Rule] {
  self.rules
}

///|
pub fn Module::span(self : Module) -> @syntax.SourceSpan {
  self.span
}

///|
/// A parsed and lowered standalone Rego v1 query.
#derive(Eq, Debug)
struct Query {
  exprs : ReadOnlyArray[Expr]
  span : @syntax.SourceSpan
}

///|
pub fn Query::Query(
  exprs~ : ArrayView[Expr],
  span~ : @syntax.SourceSpan,
) -> Query {
  { exprs: ReadOnlyArray::from_array(exprs.to_owned()), span, }
}

///|
pub fn Query::exprs(self : Query) -> ReadOnlyArray[Expr] {
  self.exprs
}

///|
pub fn Query::span(self : Query) -> @syntax.SourceSpan {
  self.span
}