///|
/// Classification of a CUE identifier according to its prefix.
///
/// Identifiers in the AST store their full source text as emitted by the lexer
/// (for example `"foo"`, `"#Server"`, `"_secret"`, `"_#Private"`).
#derive(Eq, Debug)
pub(all) enum IdentKind {
  Regular
  Def
  Hidden
  HiddenDef
}

///|
/// A `package ` clause at the top of a CUE file.
#derive(Eq, Debug)
pub(all) struct PackageClause {
  name : String
  span : Span
}

///|
/// A single import specification such as `"strings"` or `str "strings"`.
#derive(Eq, Debug)
pub(all) struct ImportSpec {
  alias_name : String?
  path : String
  span : Span
}

///|
/// An `import` declaration, either single (`import "strings"`) or grouped (`import ( ... )`).
#derive(Eq, Debug)
pub(all) struct ImportDecl {
  grouped : Bool
  specs : Array[ImportSpec]
  span : Span
}

///|
/// The root AST node of a parsed CUE source file.
#derive(Eq, Debug)
pub(all) struct File {
  pre_package_attrs : Array[Attribute]
  package_clause : PackageClause?
  imports : Array[ImportDecl]
  decls : Array[Decl]
  span : Span
}

///|
/// Field presence constraint marker (`?` optional, `!` required, or regular).
#derive(Eq, Debug)
pub(all) enum FieldConstraint {
  Normal
  Optional
  Required
}

///|
/// A segment of an interpolated string literal (`"hello \(name)"`).
#derive(Eq, Debug)
pub(all) enum StringInterpPart {
  Text(String)
  Expr(Expr)
}

///|
/// A segment of an interpolated bytes literal (`'hello \(name)'`).
#derive(Eq, Debug)
pub(all) enum BytesInterpPart {
  BytesChunk(Bytes)
  Expr(Expr)
}

///|
/// A label identifying a field or pattern constraint in a struct declaration.
#derive(Eq, Debug)
pub(all) enum Label {
  Ident(String, IdentKind, Span)
  StringLit(String, Span)
  DynamicExpr(Expr, Span)
  DynamicInterp(Array[StringInterpPart], Span)
  Pattern(String?, Expr, Span)
}

///|
/// A single label entry in a field declaration, including optional alias and `?`/`!` constraint.
#derive(Eq, Debug)
pub(all) struct FieldLabel {
  alias_name : String?
  label : Label
  constraint : FieldConstraint
  span : Span
}

///|
/// A CUE attribute such as `@protobuf(1,name=foo)` or `@if(debug)`.
#derive(Eq, Debug)
pub(all) struct Attribute {
  name : String
  body : String
  span : Span
}

///|
/// A comprehension clause (`for`, `if`, or `let`).
#derive(Eq, Debug)
pub(all) enum Clause {
  For(String?, String, Expr, Span)
  If(Expr, Span)
  Let(String, Expr, Span)
}

///|
/// A declaration inside a CUE file or struct body.
#derive(Eq, Debug)
pub(all) enum Decl {
  Field(Array[FieldLabel], Expr, Array[Attribute], Span)
  Let(String, Expr, Span)
  Embed(Expr, Array[Attribute], Span)
  Ellipsis(Span)
  Comprehension(Array[Clause], Array[Decl], Span)
  Attribute(Attribute)
}

///|
/// An element inside a CUE list literal: an expression or a list comprehension.
#derive(Eq, Debug)
pub(all) enum ListElem {
  Expr(Expr)
  Comprehension(Array[Clause], Expr, Span)
}

///|
/// A selector label used in member access expressions (`a.b` or `a."b-c"`).
#derive(Eq, Debug)
pub(all) enum SelectorLabel {
  Ident(String, IdentKind)
  StringLit(String)
}

///|
/// Unary operators supported by CUE expressions, including bound and regex constraints.
#derive(Eq, Debug)
pub(all) enum UnaryOp {
  Plus
  Minus
  Not
  Default
  Lt
  Le
  Gt
  Ge
  Neq
  Match
  NotMatch
}

///|
/// Binary operators supported by CUE expressions.
#derive(Eq, Debug)
pub(all) enum BinaryOp {
  Or
  And
  Lor
  Land
  Eq
  Neq
  Lt
  Le
  Gt
  Ge
  Match
  NotMatch
  Add
  Sub
  Mul
  QuoSlash
  Div
  Mod
  Quo
  Rem
}

///|
/// A CUE expression AST node.
#derive(Eq, Debug)
pub(all) enum Expr {
  Null(Span)
  Bool(Bool, Span)
  Int(String, Span)
  Float(String, Span)
  String(String, Span)
  Bytes(Bytes, Span)
  Bottom(Span)
  StringInterp(Array[StringInterpPart], Span)
  BytesInterp(Array[BytesInterpPart], Span)
  Ident(String, IdentKind, Span)
  Unary(UnaryOp, Expr, Span)
  Binary(BinaryOp, Expr, Expr, Span)
  Struct(Array[Decl], Span)
  List(Array[ListElem], Expr?, Bool, Span)
  Selector(Expr, SelectorLabel, Span)
  Index(Expr, Expr, Span)
  Slice(Expr, Expr?, Expr?, Span)
  Call(Expr, Array[Expr], Span)
  Paren(Expr, Span)
  Alias(String, Expr, Span)
}

///|
/// Returns the source span of a label node.
pub fn Label::span(self : Label) -> Span {
  match self {
    Ident(_, _, span)
    | StringLit(_, span)
    | DynamicExpr(_, span)
    | DynamicInterp(_, span)
    | Pattern(_, _, span) => span
  }
}

///|
/// Returns the source span of a comprehension clause.
pub fn Clause::span(self : Clause) -> Span {
  match self {
    For(_, _, _, span) | If(_, span) | Let(_, _, span) => span
  }
}

///|
/// Returns the source span of a declaration node.
pub fn Decl::span(self : Decl) -> Span {
  match self {
    Field(_, _, _, span)
    | Let(_, _, span)
    | Embed(_, _, span)
    | Ellipsis(span)
    | Comprehension(_, _, span) => span
    Attribute(attr) => attr.span
  }
}

///|
/// Returns the source span of an expression node.
pub fn Expr::span(self : Expr) -> Span {
  match self {
    Null(span)
    | Bool(_, span)
    | Int(_, span)
    | Float(_, span)
    | String(_, span)
    | Bytes(_, span)
    | Bottom(span)
    | StringInterp(_, span)
    | BytesInterp(_, span)
    | Ident(_, _, span)
    | Unary(_, _, span)
    | Binary(_, _, _, span)
    | Struct(_, span)
    | List(_, _, _, span)
    | Selector(_, _, span)
    | Index(_, _, span)
    | Slice(_, _, _, span)
    | Call(_, _, span)
    | Paren(_, span)
    | Alias(_, _, span) => span
  }
}

///|
/// Syntactic diagnostic categories produced by the parser.
#derive(Eq, Debug)
pub(all) enum ParseErrorKind {
  UnexpectedToken(String, String)
  UnexpectedEof(String)
  MaxDepthExceeded(Int32)
  InvalidLabel(String)
  InvalidSlice
  InvalidImport(String)
  InvalidPackage(String)
  InvalidExpr(String)
}

///|
/// A parser diagnostic with its exact source span.
#derive(Eq, Debug)
pub(all) struct ParseError {
  kind : ParseErrorKind
  span : Span
}

///|
/// Unified lexical and syntactic diagnostic type for the `syntax` package.
#derive(Eq, Debug)
pub(all) enum SyntaxError {
  Lex(LexError)
  Parse(ParseError)
}

///|
/// Returns the source span associated with a `SyntaxError`.
pub fn SyntaxError::span(self : SyntaxError) -> Span {
  match self {
    Lex(err) => err.span
    Parse(err) => err.span
  }
}

///|
fn format_lex_error_kind(kind : LexErrorKind) -> String {
  match kind {
    UnexpectedChar(ch) => "unexpected character '\{ch}'"
    UnterminatedString => "unterminated string literal"
    UnterminatedBytes => "unterminated bytes literal"
    UnterminatedAttribute => "unterminated attribute"
    InvalidEscape(ch) => "invalid escape sequence '\\\{ch}'"
    InvalidEscapeSequence(detail) => "invalid escape sequence: \{detail}"
    InvalidMultilineString(detail) => "invalid multiline string: \{detail}"
    InvalidNumber(raw) => "invalid number literal '\{raw}'"
  }
}

///|
fn format_parse_error_kind(kind : ParseErrorKind) -> String {
  match kind {
    UnexpectedToken(expected, found) => "expected \{expected}, found \{found}"
    UnexpectedEof(expected) => "unexpected end of input, expected \{expected}"
    MaxDepthExceeded(limit) => "maximum nesting depth (\{limit}) exceeded"
    InvalidLabel(detail) => "invalid label: \{detail}"
    InvalidSlice => "invalid slice expression"
    InvalidImport(detail) => "invalid import: \{detail}"
    InvalidPackage(detail) => "invalid package clause: \{detail}"
    InvalidExpr(detail) => "invalid expression: \{detail}"
  }
}

///|
/// Formats a `SyntaxError` as a human-readable diagnostic prefixed with `line:column`.
pub fn SyntaxError::message(self : SyntaxError) -> String {
  let pos = self.span().start
  let detail = match self {
    Lex(err) => format_lex_error_kind(err.kind)
    Parse(err) => format_parse_error_kind(err.kind)
  }
  "\{pos.line}:\{pos.column}: \{detail}"
}