hcl

    HCL parser, formatter, and serialization library for MoonBit

    hcl
    parser
    formatter
    terraform
    configuration
    Download zip
    Author
    Version
    0.1.2
    License
    MIT
    Last updated
    7 months ago
    Downloads
    73

    #HCL for MoonBit

    mooncake

    HCL (HashiCorp Configuration Language) parser, formatter, and serialization library for MoonBit.

    #Features

    #Completed

    • Parse HCL syntax - Parse HCL strings into AST (Body, Block, Attr)
    • Serialize to HCL - Convert MoonBit types back to HCL strings
    • Deserialize to MoonBit types - Use ToHCL/FromHCL traits for type-safe conversion
    • Format HCL - Proper indentation with configurable Formatter
    • Preserve comments and whitespace - Decor system for parse-modify-serialize cycles
    • Expression evaluation - Evaluate HCL expressions (+, -, *, /, comparisons, etc.)
    • 45 built-in functions - abs, ceil, floor, keys, values, length, chomp, upper, lower, replace, split, format, tobool, tonumber, tolist, tomap, and more
    • For expressions - List comprehension [for x in list: expr] and object comprehension {for k, v in obj: k => v}
    • Conditional expressions - cond ? true_val : false_val
    • Heredoc support - <<EOF, <<-EOF with custom delimiters
    • Template expressions - String interpolation ${expr} and template directives %{if}, %{for}
    • Schema validation - Type checking, required fields, custom validators
    • JSON conversion - hcl_to_json(), body_to_json_pretty()
    • CLI tool - moon run cmd/main provides hcl2json with --pretty, --simplify, --validate, --format
    • Visit AST - Immutable (Visit) and mutable (VisitMut) traversals
    • Hash comment support - Both # and // line comments

    #Official HCL Spec Tests

    This library includes tests based on the official HCL spec test suite.

    #Running Spec Tests

    # Run all official spec fixture tests moon test -F "spec fixture *" # Run specific category moon test -F "spec fixture comments *" moon test -F "spec fixture expressions *" moon test -F "spec fixture structure *"

    #Test Categories

    CategoryTestsDescription
    comments3Hash (#), slash (//), and multiline (/* */) comment parsing
    structure/attributes3Attribute parsing including valid/invalid single-line syntax
    structure/blocks5Block parsing including single-line, empty, and invalid syntax
    expressions3Operators, heredoc, and primitive literals

    #Test Implementation Notes

    The official spec tests use .hcl, .hcldec, and .t files:
    • .hcl - Input HCL code
    • .hcldec - Expected structure decoded by hcldec tool
    • .t - Test expectations including variable contexts

    Since MoonBit tests run inline without the hcldec tool, some limitations apply:

    FeatureStatusNotes
    Hash comments #✅ SupportedAdded to lexer
    Slash comments //✅ SupportedStandard
    Multiline comments /* */✅ SupportedStandard
    Operators✅ SupportedFull test coverage
    Heredoc basic✅ SupportedSimplified content
    Heredoc with interpolation⚠️ Limited${var} requires variable context from .hcldec
    Primitive literals✅ SupportedSimplified (avoids bare true/false as attribute names)

    #Why Some Tests Are Simplified

    1. Heredoc interpolation: The official tests define variables in .hcldec (e.g., bar = "Bar"). MoonBit inline tests cannot provide this context, so tests with ${bar} use simplified content.

    2. Bare keywords as attribute names: In HCL, true = true is technically invalid because true is a keyword. Attribute names that are keywords should be quoted: "true" = true. The official test file uses unquoted names which works in Go but is not strictly valid HCL.

    #Quick Start

    import "hcl"

    // Parse HCL
    let input = "name = \"John\"\nport = 8080"
    let body = hcl.parse(input).unwrap()

    // Access attributes
    let name = body.find_attr("name").unwrap().get_value().as_string()
    let port = body.find_attr("port").unwrap().get_value().as_int()

    // Serialize back to HCL
    let hcl_str = hcl.to_hcl_body(body)

    // Convert to JSON
    let json_str = hcl.body_to_json_pretty(body)

    #Installation

    moon add github:lenitain/hcl

    Or add to your moon.pkg:

    { "dependencies": { "hcl": "github:lenitain/hcl" } }

    #Usage Examples

    #Parse and Access Data

    let input = ` // Server configuration server { host = "localhost" port = 8080 } name = "myapp" version = "1.0.0" ` let body = hcl.parse(input).unwrap() // Find block let server = body.find_block("server").unwrap() let server_body = server.get_body() let host = server_body.find_attr("host").unwrap().get_value().as_string() // Find attribute let name = body.find_attr("name").unwrap().get_value().as_string()

    #Serialize to HCL

    ///|
    let value = hcl.hcl_object([
    ("name", hcl.hcl_str("John")),
    ("age", hcl.hcl_int(30)),
    ("active", hcl.hcl_bool(true)),
    ])

    ///|
    let hcl_str = hcl.to_hcl_value(value)
    // name = "John"
    // age = 30
    // active = true

    #Format with Decor Preservation

    ///|
    let input = "// Configure server\nhost = \"localhost\"\nport = 8080"

    ///|
    let body = hcl.parse(input).unwrap()

    // format_body_with_decor preserves comments

    ///|
    let output = hcl.format_body_with_decor(body)

    #Expression Evaluation

    ///|
    let vars = { "x": hcl.hcl_int(10), "y": hcl.hcl_int(3) }

    ///|
    let funcs = hcl.builtin_functions()

    // Evaluate: x + y > 5 ? "yes" : "no"

    ///|
    let expr = hcl.hcl_object([
    ("type", hcl.hcl_str("conditional")),
    (
    "condition",
    hcl.hcl_object([
    ("type", hcl.hcl_str("binary_expr")),
    ("op", hcl.hcl_str(">")),
    (
    "left",
    hcl.hcl_object([
    ("type", hcl.hcl_str("binary_expr")),
    ("op", hcl.hcl_str("+")),
    ("left", hcl.hcl_str("x")),
    ("right", hcl.hcl_str("y")),
    ]),
    ),
    ("right", hcl.hcl_int(5)),
    ]),
    ),
    ("true_expr", hcl.hcl_str("yes")),
    ("false_expr", hcl.hcl_str("no")),
    ])

    ///|
    let result = hcl.eval_expr(expr, vars, funcs)
    // Ok(String("yes", ...))

    #Schema Validation

    let schema = hcl.FieldSchema::new()
    .attr("name", hcl.TypeSchema::String)
    .attr("port", hcl.TypeSchema::Int)
    .required("name")

    let body = hcl.parse("port = 8080").unwrap()
    let result = hcl.from_hcl_with_schema(body, schema)
    // Err(HCLError::missing_required("name"))

    #CLI Usage

    # Parse and convert to JSON moon run cmd/main --file config.hcl # Pretty print JSON moon run cmd/main --file config.hcl --pretty # Simplify expressions moon run cmd/main --file config.hcl --simplify # Validate HCL (exit code 0 or 1) moon run cmd/main --file config.hcl --validate # Format HCL moon run cmd/main --file config.hcl --format

    #HCL Syntax Support

    #Attributes

    name = "John" age = 30 active = true

    #Blocks

    resource "aws_instance" "example" { ami = "ami-123456" instance_type = "t2.micro" }

    #Objects and Arrays

    config = { host = "localhost" port = 8080 } items = ["one", "two", "three"]

    #Expressions

    # Arithmetic count = 1 + 2 * 3 # Conditionals status = count > 10 ? "high" : "low" # For expressions names = [for item in items: item.name]

    #Heredocs

    script = <<EOF #!/bin/bash echo "Hello" EOF

    #API Reference

    #Parse

    • hcl.parse(String) -> HCLResult[Body]

    #Serialize

    • hcl.to_hcl_body(Body) -> String
    • hcl.to_hcl_value(HCLValue) -> String
    • hcl.format_body(Body) -> String
    • hcl.format_body_with_decor(Body) -> String

    #Deserialize

    • hcl.from_hcl_body(String) -> HCLResult[Body]
    • hcl.from_hcl_with_schema(Body, FieldSchema) -> HCLResult[...]

    #JSON

    • hcl.hcl_to_json(String) -> String
    • hcl.body_to_json(Body) -> String
    • hcl.body_to_json_pretty(Body) -> String

    #Evaluation

    • hcl.eval_expr(HCLValue, Map[String, HCLValue], Map[String, Fn]) -> HCLResult[HCLValue]
    • hcl.simplify_body(Body) -> Body
    • hcl.builtin_functions() -> Map[String, (Array[HCLValue]) -> HCLResult[HCLValue]]

    #Schema

    • hcl.TypeSchema - Type checking (String, Int, Bool, Array, Object)
    • hcl.FieldSchema - Field validation with required(), validator()
    • hcl.from_hcl_with_schema(Body, FieldSchema) -> HCLResult[T]

    #Decor

    • hcl.Decor - Whitespace and comment storage
    • hcl.Decorated[T] - Wrapper that carries decor
    • hcl.format_body_with_decor(Body) -> String
    • hcl.format_attr_with_decor(Attr) -> String

    #Visit

    • hcl.Visit trait - Immutable AST traversal
    • hcl.VisitMut trait - Mutable AST traversal

    #License

    Apache-2.0 License

    ExprObject

    type ExprObject = Array[(ObjectKey, Expression)]

    Object type for expressions (preserves insertion order via array of pairs)

    HCLObject

    type HCLObject = Map[String, HCLValue]

    HCL Object type - ordered map of string keys to HCL values.

    Preserves insertion order (like indexmap::IndexMap in hcl-rs).

    HCLResult

    type HCLResult[T] = Result[T, HCLError]

    Validator

    type Validator = (HCLValue, String) -> Array[HCLError]

    Custom validator function type

    FromHCL

    pub trait FromHCL {
    from_hcl(HCLValue) -> Result[Self, HCLError]
    }

    Trait for converting HCLValue to MoonBit types

    ToHCL

    pub trait ToHCL {
    to_hcl(Self) -> HCLValue
    }

    Trait for converting MoonBit types to HCLValue

    Visit

    pub(open) trait Visit {
    visit_body(Self, Body) -> Unit
    visit_body_item(Self, BodyItem) -> Unit
    visit_attr(Self, Attr) -> Unit
    visit_block(Self, Block) -> Unit
    visit_value(Self, HCLValue) -> Unit
    visit_expr(Self, Expression) -> Unit
    visit_object_key(Self, ObjectKey) -> Unit
    visit_traversal(Self, Traversal) -> Unit
    visit_traversal_operator(Self, TraversalOperator) -> Unit
    visit_func_call(Self, FuncCall) -> Unit
    visit_conditional(Self, Conditional) -> Unit
    visit_operation(Self, Operation) -> Unit
    visit_binary_op(Self, BinaryOp) -> Unit
    visit_unary_op(Self, UnaryOp) -> Unit
    visit_for_expr(Self, ForExpr) -> Unit
    visit_template_expr(Self, TemplateExpr) -> Unit
    visit_heredoc(Self, Heredoc) -> Unit
    visit_decorated_expr(Self, Decorated[Expression]) -> Unit
    }

    Visitor trait for immutable traversal of HCL AST Users implement this to customize behavior when visiting AST nodes.

    VisitMut

    pub(open) trait VisitMut {
    visit_body_mut(Self, Body) -> Unit
    visit_body_item_mut(Self, BodyItem) -> Unit
    visit_attr_mut(Self, Attr) -> Unit
    visit_block_mut(Self, Block) -> Unit
    visit_value_mut(Self, HCLValue) -> Unit
    visit_expr_mut(Self, Expression) -> Unit
    visit_object_key_mut(Self, ObjectKey) -> Unit
    visit_traversal_mut(Self, Traversal) -> Unit
    visit_traversal_operator_mut(Self, TraversalOperator) -> Unit
    visit_func_call_mut(Self, FuncCall) -> Unit
    visit_conditional_mut(Self, Conditional) -> Unit
    visit_operation_mut(Self, Operation) -> Unit
    visit_binary_op_mut(Self, BinaryOp) -> Unit
    visit_unary_op_mut(Self, UnaryOp) -> Unit
    visit_for_expr_mut(Self, ForExpr) -> Unit
    visit_template_expr_mut(Self, TemplateExpr) -> Unit
    visit_heredoc_mut(Self, Heredoc) -> Unit
    visit_decorated_expr_mut(Self, Decorated[Expression]) -> Unit
    }

    Visitor trait for mutable traversal of HCL AST

    Attr

    pub struct Attr {
    key : Decorated[String]
    value : Spanned[Expression]
    decor : Decor
    } derive(Eq,
    Debug
    )

    HCL Attribute - key-value pair with decoration

    Attr::get_decor

    fn Attr::get_decor(self : Attr) -> Decor

    Get attribute decoration

    Attr::get_decorated_key

    fn Attr::get_decorated_key(self : Attr) -> Decorated[String]

    Get attribute key with decoration

    Attr::get_key

    fn Attr::get_key(self : Attr) -> String

    Get attribute key

    Attr::get_spanned_value

    fn Attr::get_spanned_value(self : Attr) -> Spanned[Expression]

    Get attribute spanned value

    Attr::get_value

    fn Attr::get_value(self : Attr) -> Expression

    Get attribute value

    Attr::new

    fn Attr::new(key : String, value : Expression) -> Attr

    Create a new attribute with decoration

    Attr::set_span

    fn Attr::set_span(self : Attr, span : Span) -> Attr

    Set span on attribute value

    Attr::with_decor

    fn Attr::with_decor(key : Decorated[String], value : Spanned[Expression], decor : Decor) -> Attr

    Create a new attribute with full decoration

    AttrSchema

    pub struct AttrSchema {
    required : Bool
    type_schema : TypeSchema
    } derive(Eq,
    Debug
    )

    Schema for a body attribute

    AttrSchema::optional

    fn AttrSchema::optional(type_schema : TypeSchema) -> AttrSchema

    Create an optional AttrSchema

    AttrSchema::required

    fn AttrSchema::required(type_schema : TypeSchema) -> AttrSchema

    Create a required AttrSchema

    BinaryOp

    pub(all) struct BinaryOp {
    left : Expression
    op : BinaryOperator
    right : Expression
    } derive(Eq,
    Debug
    )

    Binary operation

    BinaryOperator

    pub(all) enum BinaryOperator {
    Plus
    Minus
    Mul
    Div
    Mod
    Eq
    Neq
    Lt
    Gt
    Lte
    Gte
    And
    Or
    } derive(Eq,
    Debug
    )

    Binary operator

    Block

    pub struct Block {
    type_name : Decorated[String]
    labels : Array[Decorated[String]]
    body : Body
    decor : Decor
    span : Span?
    } derive(Eq,
    Debug
    )

    HCL Block - named container with optional labels and decoration

    Block::builder

    fn Block::builder(type_name : String) -> BlockBuilder

    Create a new BlockBuilder

    Block::find_attr

    fn Block::find_attr(self : Block, key : String) -> Attr?

    Find an attribute in block body

    Block::get_body

    fn Block::get_body(self : Block) -> Body

    Get block body

    Block::get_decor

    fn Block::get_decor(self : Block) -> Decor

    Get block decoration

    Block::get_decorated_labels

    fn Block::get_decorated_labels(self : Block) -> Array[Decorated[String]]

    Get block labels with decoration

    Block::get_decorated_type_name

    fn Block::get_decorated_type_name(self : Block) -> Decorated[String]

    Get block type name with decoration

    Block::get_labels

    fn Block::get_labels(self : Block) -> Array[String]

    Get block labels

    Block::get_span

    fn Block::get_span(self : Block) -> Span?

    Get block span

    Block::get_type_name

    fn Block::get_type_name(self : Block) -> String

    Get block type name

    Block::new

    fn Block::new(type_name : String, labels : Array[String], body : Body) -> Block

    Create a new block with decoration

    Block::set_span

    fn Block::set_span(self : Block, span : Span) -> Block

    Set span on block

    Block::simple

    fn Block::simple(type_name : String, body : Body) -> Block

    Create a block without labels

    Block::with_decor

    fn Block::with_decor(type_name : Decorated[String], labels : Array[Decorated[String]], body : Body, decor : Decor) -> Block

    Create a new block with full decoration

    BlockBuilder

    pub struct BlockBuilder {
    type_name : String
    labels : Array[String]
    items : Array[BodyItem]
    }

    Builder for constructing Block incrementally

    BlockBuilder::attr

    fn BlockBuilder::attr(self : BlockBuilder, key : String, value : Expression) -> BlockBuilder

    Add an attribute with Expression

    BlockBuilder::attr_hcl

    fn[T : ToHCL] BlockBuilder::attr_hcl(self : BlockBuilder, key : String, value : T) -> BlockBuilder

    Add an attribute from ToHCL value

    BlockBuilder::attr_if

    fn BlockBuilder::attr_if(self : BlockBuilder, key : String, value : Expression, cond : Bool) -> BlockBuilder

    Add an attribute conditionally

    BlockBuilder::body

    fn BlockBuilder::body(self : BlockBuilder, b : Body) -> BlockBuilder

    Set the body from an existing Body

    BlockBuilder::build

    fn BlockBuilder::build(self : BlockBuilder) -> Block

    Build the Block

    BlockBuilder::label

    fn BlockBuilder::label(self : BlockBuilder, lbl : String) -> BlockBuilder

    Add a label

    BlockSchema

    pub struct BlockSchema {
    required : Bool
    max_items : Int?
    labels : Array[LabelSchema]
    body : BodySchema
    } derive(Eq,
    Debug
    )

    Schema for a body block

    BlockSchema::mark_required

    fn BlockSchema::mark_required(self : BlockSchema) -> BlockSchema

    Mark an existing block schema as required

    BlockSchema::new

    Create a new BlockSchema

    BlockSchema::with_labels

    fn BlockSchema::with_labels(self : BlockSchema, labels : Array[LabelSchema]) -> BlockSchema

    Set labels for block

    BlockSchema::with_max_items

    fn BlockSchema::with_max_items(self : BlockSchema, max : Int) -> BlockSchema

    Set max items for block

    Body

    pub struct Body {
    items : Array[BodyItem]
    decor : Decor
    span : Span?
    } derive(Eq,
    Debug
    )

    HCL Body - top-level container for attributes and blocks with decoration

    Body::add_attr

    fn Body::add_attr(self : Body, key : String, value : Expression) -> Body

    Add an attribute to the body (returns new body)

    Body::add_block

    fn Body::add_block(self : Body, block : Block) -> Body

    Add a block to the body (returns new body)

    Body::builder

    fn Body::builder() -> BodyBuilder

    Create a new BodyBuilder

    Body::find_attr

    fn Body::find_attr(self : Body, key : String) -> Attr?

    Find an attribute by key

    Body::find_block

    fn Body::find_block(self : Body, type_name : String) -> Block?

    Find first block of a given type

    Body::find_blocks

    fn Body::find_blocks(self : Body, type_name : String) -> Array[Block]

    Find all blocks of a given type

    Body::from_items

    fn Body::from_items(items : Array[BodyItem]) -> Body

    Create a Body from items with decoration

    Body::get_decor

    fn Body::get_decor(self : Body) -> Decor

    Get body decoration

    Body::get_items

    fn Body::get_items(self : Body) -> Array[BodyItem]

    Get the items of the body

    Body::get_span

    fn Body::get_span(self : Body) -> Span?

    Get body span

    Body::is_empty

    fn Body::is_empty(self : Body) -> Bool

    Check if body is empty

    Body::len

    fn Body::len(self : Body) -> Int

    Get the number of items in the body

    Body::new

    fn Body::new() -> Body

    Create a new empty Body with decoration

    Body::set_span

    fn Body::set_span(self : Body, span : Span) -> Body

    Set span on body

    Body::with_decor

    fn Body::with_decor(items : Array[BodyItem], decor : Decor) -> Body

    Create a Body with full decoration

    BodyBuilder

    pub struct BodyBuilder {
    items : Array[BodyItem]
    }

    Builder for constructing Body incrementally

    BodyBuilder::attr

    fn BodyBuilder::attr(self : BodyBuilder, key : String, value : Expression) -> BodyBuilder

    Add an attribute with Expression

    BodyBuilder::attr_hcl

    fn[T : ToHCL] BodyBuilder::attr_hcl(self : BodyBuilder, key : String, value : T) -> BodyBuilder

    Add an attribute from ToHCL value

    BodyBuilder::attr_if

    fn BodyBuilder::attr_if(self : BodyBuilder, key : String, value : Expression, cond : Bool) -> BodyBuilder

    Add an attribute conditionally

    BodyBuilder::attr_option

    fn[T : ToHCL] BodyBuilder::attr_option(self : BodyBuilder, key : String, value : T?) -> BodyBuilder

    Add an attribute from Option (skip if None)

    BodyBuilder::block

    fn BodyBuilder::block(self : BodyBuilder, blk : Block) -> BodyBuilder

    Add a block

    BodyBuilder::build

    fn BodyBuilder::build(self : BodyBuilder) -> Body

    Build the Body

    BodyItem

    pub(all) enum BodyItem {
    Attribute(Attr)
    Block(Block)
    } derive(Eq,
    Debug
    )

    Body item can be either an attribute or a block

    BodySchema

    pub struct BodySchema {
    attrs : Map[String, AttrSchema]
    blocks : Map[String, BlockSchema]
    extra_attrs : Bool
    extra_blocks : Bool
    } derive(Eq,
    Debug
    )

    Schema for extracting structured data from HCL Body

    BodySchema::new

    fn BodySchema::new() -> BodySchema

    Create an empty BodySchema

    BodySchema::with_attrs

    fn BodySchema::with_attrs(self : BodySchema, attrs : Map[String, AttrSchema]) -> BodySchema

    Set attribute schemas on a BodySchema

    BodySchema::with_blocks

    fn BodySchema::with_blocks(self : BodySchema, blocks : Map[String, BlockSchema]) -> BodySchema

    Set block schemas on a BodySchema

    Conditional

    pub(all) struct Conditional {
    condition : Expression
    true_expr : Expression
    false_expr : Expression
    } derive(Eq,
    Debug
    )

    Conditional expression (cond ? true_expr : false_expr)

    Decor

    pub struct Decor {
    prefix : String?
    suffix : String?
    } derive(Eq,
    Debug
    )

    Whitespace and comment decorators, stores prefix and suffix

    Decor::clear

    fn Decor::clear(_self : Decor) -> Decor

    Clear decorations

    Decor::empty

    fn Decor::empty() -> Decor

    Create empty Decor

    Decor::get_prefix

    fn Decor::get_prefix(self : Decor) -> String?

    Get prefix

    Decor::get_suffix

    fn Decor::get_suffix(self : Decor) -> String?

    Get suffix

    Decor::new

    fn Decor::new(prefix : String?, suffix : String?) -> Decor

    Create new Decor

    Decor::set_prefix

    fn Decor::set_prefix(self : Decor, prefix : String) -> Decor

    Set prefix

    Decor::set_suffix

    fn Decor::set_suffix(self : Decor, suffix : String) -> Decor

    Set suffix

    Decorated

    pub struct Decorated[T] {
    value : T
    decor : Decor
    } derive(Eq,
    Debug
    )

    Value with decorations

    Decorated::bare

    fn[T] Decorated::bare(value : T) -> Decorated[T]

    Create value with empty decor

    Decorated::expr

    Create a bare decorated expression (no decor)

    Decorated::expr_with_decor

    fn Decorated::expr_with_decor(expr : Expression, decor : Decor) -> Decorated[Expression]

    Create a decorated expression with decor

    Decorated::get_decor

    fn[T] Decorated::get_decor(self : Decorated[T]) -> Decor

    Get decor

    Decorated::get_expr

    fn Decorated::get_expr(self : Decorated[Expression]) -> Expression

    Extract the inner expression

    Decorated::get_value

    fn[T] Decorated::get_value(self : Decorated[T]) -> T

    Get value

    Decorated::new

    fn[T] Decorated::new(value : T, decor : Decor) -> Decorated[T]

    Create decorated value

    Decorated::set_decor

    fn[T] Decorated::set_decor(self : Decorated[T], decor : Decor) -> Decorated[T]

    Set decor

    Expression

    pub(all) enum Expression {
    ExprNull
    ExprBool(Bool)
    ExprInt(Int)
    ExprInt64(Int64)
    ExprFloat(Double)
    ExprString(String)
    ExprArray(Array[Expression])
    ExprObject(Array[(ObjectKey, Expression)])
    ExprTemplate(TemplateExpr)
    ExprVariable(Variable)
    ExprTraversal(Traversal)
    ExprFuncCall(FuncCall)
    ExprParenthesis(Expression)
    ExprConditional(Conditional)
    ExprOperation(Operation)
    ExprFor(ForExpr)
    ExprUnknown
    } derive(Eq,
    Debug
    )

    Represents an HCL expression

    ExtractedBlock

    pub struct ExtractedBlock {
    labels : Array[String]
    body : ExtractedBody
    } derive(Eq,
    Debug
    )

    A single extracted block with its labels and nested body

    ExtractedBlock::get_label

    fn ExtractedBlock::get_label(self : ExtractedBlock, index : Int) -> String?

    Get a label by index from a block

    ExtractedBody

    pub struct ExtractedBody {
    attrs : Map[String, HCLValue]
    blocks : Map[String, Array[ExtractedBlock]]
    extra_blocks : Array[ExtractedBlock]
    } derive(Eq,
    Debug
    )

    Result of extracting structured data from an HCL Body using a BodySchema

    ExtractedBody::get_attr

    fn ExtractedBody::get_attr(self : ExtractedBody, key : String) -> HCLValue?

    Get an attribute value by key

    ExtractedBody::get_block

    fn ExtractedBody::get_block(self : ExtractedBody, type_name : String) -> ExtractedBlock?

    Get the first block of a given type name

    ExtractedBody::get_blocks

    fn ExtractedBody::get_blocks(self : ExtractedBody, type_name : String) -> Array[ExtractedBlock]

    Get all blocks of a given type name

    ExtractedBody::get_extra_blocks

    fn ExtractedBody::get_extra_blocks(self : ExtractedBody) -> Array[ExtractedBlock]

    Get all extra blocks (unknown blocks when extra_blocks=true)

    ExtractedBody::new

    Create an empty ExtractedBody

    FieldSchema

    pub struct FieldSchema {
    schema : TypeSchema
    required : Bool
    description : String
    } derive(Eq,
    Debug
    )

    Schema for an object field

    FieldSchema::optional

    fn FieldSchema::optional(schema : TypeSchema) -> FieldSchema

    Create an optional field schema

    FieldSchema::required

    fn FieldSchema::required(schema : TypeSchema) -> FieldSchema

    Create a required field schema

    FieldSchema::with_description

    fn FieldSchema::with_description(self : FieldSchema, desc : String) -> FieldSchema

    Create a field schema with description

    FieldSchemaEx

    pub struct FieldSchemaEx {
    base : FieldSchema
    validators : Array[(HCLValue, String) -> Array[HCLError]]
    }

    Extended field schema with custom validators

    FieldSchemaEx::add_validator

    fn FieldSchemaEx::add_validator(self : FieldSchemaEx, v : (HCLValue, String) -> Array[HCLError]) -> FieldSchemaEx

    Add validator to field schema

    FieldSchemaEx::new

    Create extended field schema

    ForExpr

    pub(all) enum ForExpr {
    List(ForListExpr)
    Object(ForObjectExpr)
    } derive(Eq,
    Debug
    )

    For expression (list/object comprehension)

    ForListExpr

    pub(all) struct ForListExpr {
    var_name : String
    collection : Expression
    value_expr : Expression
    filter : Expression?
    } derive(Eq,
    Debug
    )

    List comprehension

    ForObjectExpr

    pub(all) struct ForObjectExpr {
    key_var : String
    value_var : String
    collection : Expression
    key_expr : Expression
    value_expr : Expression
    filter : Expression?
    } derive(Eq,
    Debug
    )

    Object comprehension

    FormatConfig

    pub struct FormatConfig {
    indent : String
    dense : Bool
    compact_arrays : Bool
    compact_objects : Bool
    prefer_ident_keys : Bool
    } derive(Eq,
    Debug
    )

    Format configuration for HCL output

    FormatConfig::compact

    fn FormatConfig::compact() -> FormatConfig

    Create compact FormatConfig (inline arrays/objects)

    FormatConfig::default

    fn FormatConfig::default() -> FormatConfig

    Create default FormatConfig (2-space indent, all options false)

    FormatConfig::dense

    fn FormatConfig::dense() -> FormatConfig

    Create dense FormatConfig (no empty lines between blocks)

    Formatter

    pub struct Formatter {
    config : FormatConfig
    }

    Formatter for HCL output with configuration

    Formatter::format_body

    fn Formatter::format_body(self : Formatter, body : Body) -> String

    Format Body using formatter config

    Formatter::format_value

    fn Formatter::format_value(self : Formatter, value : HCLValue) -> String

    Format HCLValue using formatter config

    Formatter::get_config

    fn Formatter::get_config(self : Formatter) -> FormatConfig

    Get the formatter config

    Formatter::new

    fn Formatter::new() -> Formatter

    Create Formatter with default config

    Formatter::set_compact_arrays

    fn Formatter::set_compact_arrays(self : Formatter, compact_arrays : Bool) -> Formatter

    Set compact arrays mode

    Formatter::set_compact_objects

    fn Formatter::set_compact_objects(self : Formatter, compact_objects : Bool) -> Formatter

    Set compact objects mode

    Formatter::set_dense

    fn Formatter::set_dense(self : Formatter, dense : Bool) -> Formatter

    Set dense mode

    Formatter::set_indent

    fn Formatter::set_indent(self : Formatter, indent : String) -> Formatter

    Set indent string

    Formatter::set_prefer_ident_keys

    fn Formatter::set_prefer_ident_keys(self : Formatter, prefer_ident_keys : Bool) -> Formatter

    Set prefer ident keys mode

    Formatter::with_config

    fn Formatter::with_config(config : FormatConfig) -> Formatter

    Create Formatter with given config

    FuncCall

    pub(all) struct FuncCall {
    name : String
    args : Array[Expression]
    } derive(Eq,
    Debug
    )

    Function call

    FuncCall::builder

    fn FuncCall::builder(name : String) -> FuncCallBuilder

    Create a FuncCallBuilder for this function name

    FuncCallBuilder

    pub struct FuncCallBuilder {
    name : String
    args : Array[Expression]
    }

    Builder for constructing FuncCall expressions incrementally

    FuncCallBuilder::arg

    Add an argument expression

    FuncCallBuilder::build

    Build the FuncCall expression

    FuncCallBuilder::new

    fn FuncCallBuilder::new(name : String) -> FuncCallBuilder

    Create a new FuncCallBuilder with a function name

    FuncDef

    pub struct FuncDef {
    name : String
    params : Array[ParamType]
    variadic : ParamType?
    func : (Array[HCLValue]) -> Result[HCLValue, HCLError]
    }

    Function definition with parameter specifications

    FuncDef::builder

    fn FuncDef::builder() -> FuncDefBuilder

    Create a FuncDefBuilder

    FuncDef::call

    fn FuncDef::call(self : FuncDef, args : Array[HCLValue]) -> Result[HCLValue, HCLError]

    Call function with argument validation

    FuncDefBuilder

    pub struct FuncDefBuilder {
    params : Array[ParamType]
    variadic : ParamType?
    } derive(Eq,
    Debug
    )

    Builder for FuncDef

    FuncDefBuilder::build

    fn FuncDefBuilder::build(self : FuncDefBuilder, name : String, func : (Array[HCLValue]) -> Result[HCLValue, HCLError]) -> FuncDef

    Build FuncDef with name and function body

    FuncDefBuilder::new

    Create new FuncDefBuilder

    FuncDefBuilder::param

    Add a positional parameter

    FuncDefBuilder::variadic

    fn FuncDefBuilder::variadic(self : FuncDefBuilder, vtype : ParamType) -> FuncDefBuilder

    Set variadic parameter type

    HCLError

    pub(all) enum HCLError {
    ParseError(String, Int, Int, Int, String)
    TypeError(String, String)
    MissingField(String)
    InvalidValue(String)
    IOError(String)
    DivisionByZero
    UndefinedVariable(String)
    UndefinedFunction(String)
    UndefinedProperty(String)
    ValidationError(String, String)
    EncodingError(String)
    } derive(Eq,
    Debug
    )

    HCL Error types

    HCLError::division_by_zero

    fn HCLError::division_by_zero() -> HCLError

    HCLError::encoding_error

    fn HCLError::encoding_error(msg : String) -> HCLError

    HCLError::invalid_value

    fn HCLError::invalid_value(msg : String) -> HCLError

    HCLError::io_error

    fn HCLError::io_error(msg : String) -> HCLError

    HCLError::message

    fn HCLError::message(self : HCLError) -> String

    HCLError::missing_field

    fn HCLError::missing_field(field : String) -> HCLError

    HCLError::parse_error

    fn HCLError::parse_error(msg : String, line : Int, column : Int, offset : Int) -> HCLError

    HCLError::parse_error_with_context

    fn HCLError::parse_error_with_context(msg : String, line : Int, column : Int, offset : Int, context : String) -> HCLError

    HCLError::type_error

    fn HCLError::type_error(msg : String) -> HCLError

    HCLError::type_mismatch

    fn HCLError::type_mismatch(expected : String, got : String) -> HCLError

    HCLError::undefined_function

    fn HCLError::undefined_function(name : String) -> HCLError

    HCLError::undefined_property

    fn HCLError::undefined_property(name : String) -> HCLError

    HCLError::undefined_variable

    fn HCLError::undefined_variable(name : String) -> HCLError

    HCLError::validation_error

    fn HCLError::validation_error(path : String, msg : String) -> HCLError

    HCLObjectBuilder

    pub struct HCLObjectBuilder {
    obj : Map[String, HCLValue]
    }

    Builder for constructing HCLObject incrementally

    HCLObjectBuilder::build

    fn HCLObjectBuilder::build(self : HCLObjectBuilder) -> Map[String, HCLValue]

    Build the HCLObject

    HCLObjectBuilder::entry

    fn HCLObjectBuilder::entry(self : HCLObjectBuilder, key : String, value : HCLValue) -> HCLObjectBuilder

    Add a key-value pair

    HCLObjectBuilder::entry_hcl

    fn[T : ToHCL] HCLObjectBuilder::entry_hcl(self : HCLObjectBuilder, key : String, value : T) -> HCLObjectBuilder

    Add a key-value pair from ToHCL value

    HCLObjectBuilder::entry_if

    fn HCLObjectBuilder::entry_if(self : HCLObjectBuilder, key : String, value : HCLValue, cond : Bool) -> HCLObjectBuilder

    Add a key-value pair conditionally

    HCLObjectBuilder::entry_option

    fn[T : ToHCL] HCLObjectBuilder::entry_option(self : HCLObjectBuilder, key : String, value : T?) -> HCLObjectBuilder

    Add a key-value pair from Option (skip if None)

    HCLObjectBuilder::extend

    fn HCLObjectBuilder::extend(self : HCLObjectBuilder, other : Map[String, HCLValue]) -> HCLObjectBuilder

    Add all entries from another HCLObject

    HCLObjectBuilder::new

    Create a new HCLObjectBuilder

    HCLValue

    pub(all) enum HCLValue {
    Null(Decor)
    Bool(Bool, Decor)
    Number(Number, Decor)
    String(String, Decor)
    Array(Array[HCLValue], Decor)
    Object(Map[String, HCLValue], Decor)
    Unknown(Decor)
    } derive(Eq,
    Debug
    )

    HCL value types with decoration

    HCLValue::array

    fn HCLValue::array(arr : Array[HCLValue]) -> HCLValue

    Create array value with empty decor

    HCLValue::as_array

    fn HCLValue::as_array(self : HCLValue) -> Array[HCLValue]?

    Get the array value, or None if not an array

    HCLValue::as_bool

    fn HCLValue::as_bool(self : HCLValue) -> Bool?

    Get the boolean value, or None if not a bool

    HCLValue::as_float

    fn HCLValue::as_float(self : HCLValue) -> Double?

    Get the float value, or None if not a number

    HCLValue::as_int

    fn HCLValue::as_int(self : HCLValue) -> Int?

    Get the int value, or None if not a number representable as Int

    HCLValue::as_int64

    fn HCLValue::as_int64(self : HCLValue) -> Int64?

    Get the int64 value, or None if not a number representable as Int64

    HCLValue::as_number

    fn HCLValue::as_number(self : HCLValue) -> Number?

    Get the Number value, or None if not a number

    HCLValue::as_object

    fn HCLValue::as_object(self : HCLValue) -> Map[String, HCLValue]?

    Get the object value, or None if not an object

    HCLValue::as_string

    fn HCLValue::as_string(self : HCLValue) -> String?

    Get the string value, or None if not a string

    HCLValue::bool

    fn HCLValue::bool(b : Bool) -> HCLValue

    Create bool value with empty decor

    HCLValue::float

    fn HCLValue::float(f : Double) -> HCLValue

    Create float value with empty decor

    HCLValue::get_decor

    fn HCLValue::get_decor(self : HCLValue) -> Decor

    Get decoration from HCLValue

    HCLValue::int

    fn HCLValue::int(i : Int) -> HCLValue

    Create int value with empty decor

    HCLValue::int64

    fn HCLValue::int64(i : Int64) -> HCLValue

    Create int64 value with empty decor

    HCLValue::is_array

    fn HCLValue::is_array(self : HCLValue) -> Bool

    Check if value is an array

    HCLValue::is_bool

    fn HCLValue::is_bool(self : HCLValue) -> Bool

    Check if value is a boolean

    HCLValue::is_null

    fn HCLValue::is_null(self : HCLValue) -> Bool

    Check if value is null

    HCLValue::is_number

    fn HCLValue::is_number(self : HCLValue) -> Bool

    Check if value is a number

    HCLValue::is_object

    fn HCLValue::is_object(self : HCLValue) -> Bool

    Check if value is an object

    HCLValue::is_string

    fn HCLValue::is_string(self : HCLValue) -> Bool

    Check if value is a string

    HCLValue::is_unknown

    fn HCLValue::is_unknown(self : HCLValue) -> Bool

    Check if value is unknown (Terraform plan-stage)

    HCLValue::null

    fn HCLValue::null() -> HCLValue

    Create null value with empty decor

    HCLValue::object

    fn HCLValue::object(obj : Map[String, HCLValue]) -> HCLValue

    Create object value with empty decor

    HCLValue::set_decor

    fn HCLValue::set_decor(self : HCLValue, decor : Decor) -> HCLValue

    Set decoration on HCLValue

    HCLValue::string

    fn HCLValue::string(s : String) -> HCLValue

    Create string value with empty decor

    HCLValue::to_json_string

    fn HCLValue::to_json_string(self : HCLValue) -> String

    Convert HCLValue to JSON-compatible string representation

    HCLValue::type_name

    fn HCLValue::type_name(self : HCLValue) -> String

    Get type name as string

    HCLValue::unknown

    fn HCLValue::unknown() -> HCLValue

    Create unknown value with empty decor (Terraform plan-stage)

    Heredoc

    pub(all) struct Heredoc {
    delimiter : String
    content : String
    strip_mode : HeredocStripMode
    } derive(Eq,
    Debug
    )

    Heredoc template

    HeredocStripMode

    pub(all) enum HeredocStripMode {
    NoStrip
    StripMode
    } derive(Eq,
    Debug
    )

    Heredoc strip mode

    Ident

    pub struct Ident {
    inner : String
    } derive(Eq)

    HCL Identifier type with validation

    Represents a validated HCL identifier. Identifiers are used for attribute names, block labels, variable references, etc.

    Validation uses Unicode XID_Start/XID_Continue rules matching the lexer:
    • First character: a-z, A-Z, underscore, Latin extended, CJK, Hangul, etc.
    • Remaining characters: all of the above plus 0-9, hyphen, combining marks

    Ident::as_str

    fn Ident::as_str(self : Ident) -> String

    Get the identifier as a string reference.

    Ident::hash

    fn Ident::hash(self : Ident) -> Int

    Implement hash for Ident (delegates to inner string)

    Ident::into_string

    fn Ident::into_string(self : Ident) -> String

    Consume the Ident and return the inner String.

    Ident::is_empty

    fn Ident::is_empty(self : Ident) -> Bool

    Check if the identifier is empty (should never happen for valid idents).

    Ident::len

    fn Ident::len(self : Ident) -> Int

    Get the length of the identifier.

    Ident::new

    fn Ident::new(s : String) -> Ident

    Create a new Ident after validating.

    Panics if the identifier is empty or contains invalid characters.

    Ident::new_sanitized

    fn Ident::new_sanitized(s : String) -> Ident

    Create a new Ident, sanitizing invalid input.

    Rules:
    • Empty string becomes "_"
    • Invalid characters replaced with "_"
    • If first char is valid as id_continue but not id_start, prefix with "_"

    Ident::new_unchecked

    fn Ident::new_unchecked(s : String) -> Ident

    Create a new Ident without validation.

    Caller must ensure the string is a valid identifier. Invalid identifiers will produce broken HCL output when serialized.

    Ident::output

    fn Ident::output(self : Ident) -> String

    Implement Display for Ident (output the raw string)

    Ident::to_string

    fn Ident::to_string(self : Ident) -> String

    Debug representation

    Ident::try_new

    fn Ident::try_new(s : String) -> Result[Ident, HCLError]

    Create a new Ident after validating, returning error on failure.

    JsonValue

    pub(all) enum JsonValue {
    JsonNull
    JsonBool(Bool)
    JsonNumber(String)
    JsonString(String)
    JsonArray(Array[JsonValue])
    JsonObject(Array[(String, JsonValue)])
    } derive(Eq,
    Debug
    )

    JSON value intermediate type

    LabelSchema

    pub struct LabelSchema {
    required : Bool
    } derive(Eq,
    Debug
    )

    Schema for a block label

    LabelSchema::optional

    fn LabelSchema::optional() -> LabelSchema

    Create an optional LabelSchema

    LabelSchema::required

    fn LabelSchema::required() -> LabelSchema

    Create a required LabelSchema

    Lexer

    pub struct Lexer {
    input : String
    pos : Int
    line : Int
    col : Int
    }

    HCL Lexer - tokenizes HCL input

    Lexer::collect_comment

    fn Lexer::collect_comment(self : Lexer) -> (Lexer, String?)

    Collect comment (line or block) without consuming, returns collected text

    Lexer::collect_whitespace

    fn Lexer::collect_whitespace(self : Lexer) -> (Lexer, String?)

    Collect whitespace (spaces, tabs, CR) without consuming, returns collected text

    Lexer::get_line

    fn Lexer::get_line(self : Lexer, line_number : Int) -> String

    Get a specific line from input (line number starts at 1)

    Lexer::location

    fn Lexer::location(self : Lexer) -> (Int, Int, Int)

    Get current position info

    Lexer::new

    fn Lexer::new(input : String) -> Lexer

    Create a new lexer from string input

    Lexer::next_token

    fn Lexer::next_token(self : Lexer) -> Result[(Token, Lexer), HCLError]

    Get the next token

    Lexer::next_token_with_trivia

    fn Lexer::next_token_with_trivia(self : Lexer) -> Result[(Token, Lexer, String?), HCLError]

    Get the next token with leading trivia (whitespace, newlines, and comments)

    Lexer::tokenize

    fn Lexer::tokenize(self : Lexer) -> Result[Array[Token], HCLError]

    Tokenize entire input

    Lexer::validate_input

    fn Lexer::validate_input(input : String) -> Result[Unit, HCLError]

    Validate input encoding (no BOM allowed)
    pub(all) enum N {
    PosInt(UInt64)
    NegInt(Int64)
    Float(Double)
    }

    HCL Number internal representation.

    WARNING: This is an internal implementation detail. Use the Number type and its public API instead of matching on N directly.

    Number

    pub struct Number {
    n : N
    }

    Number::as_f64

    fn Number::as_f64(self : Number) -> Double

    Get Number value as f64 (always succeeds)

    Number::as_float

    fn Number::as_float(self : Number) -> Double

    Get Number value as Double (alias for as_f64)

    Number::as_i64

    fn Number::as_i64(self : Number) -> Int64?

    If Number is an integer, return as Int64

    Number::as_int

    fn Number::as_int(self : Number) -> Int?

    If Number fits in Int (32-bit), return as Int

    Number::as_int64

    fn Number::as_int64(self : Number) -> Int64?

    If Number is an integer, return as Int64 (alias for as_i64)

    Number::as_u64

    fn Number::as_u64(self : Number) -> UInt64?

    If Number is a positive integer, return as UInt64

    Number::from_double

    fn Number::from_double(d : Double) -> Number

    Create Number from Double

    Number::from_f64

    fn Number::from_f64(f : Double) -> Number?

    Create a Number from a finite f64. Returns None if f is NaN or infinite.

    Number::from_finite_f64

    fn Number::from_finite_f64(f : Double) -> Number

    Create a Number from f64, assumes finite

    Number::from_int

    fn Number::from_int(i : Int) -> Number

    Create Number from Int

    Number::from_int64

    fn Number::from_int64(i : Int64) -> Number

    Create Number from Int64

    Number::from_uint64

    fn Number::from_uint64(u : UInt64) -> Number

    Create Number from UInt64

    Number::is_f64

    fn Number::is_f64(self : Number) -> Bool

    Check if Number is a float

    Number::is_float

    fn Number::is_float(self : Number) -> Bool

    Check if Number is a float (alias for is_f64)

    Number::is_int

    fn Number::is_int(self : Number) -> Bool

    Check if Number is any integer (PosInt or NegInt)

    Number::is_int64

    fn Number::is_int64(self : Number) -> Bool

    Check if Number is a negative integer (alias for is_neg_int)

    Number::is_neg_int

    fn Number::is_neg_int(self : Number) -> Bool

    Check if Number is a negative integer

    Number::is_pos_int

    fn Number::is_pos_int(self : Number) -> Bool

    Check if Number is a positive integer

    ObjectKey

    pub(all) enum ObjectKey {
    Identifier(String)
    Expression(Expression)
    } derive(Eq,
    Debug
    )

    Object key type - can be identifier or expression

    ObjectKey::to_string

    fn ObjectKey::to_string(self : ObjectKey) -> String

    Convert ObjectKey to string representation

    Operation

    pub(all) enum Operation {
    Binary(BinaryOp)
    Unary(UnaryOp)
    } derive(Eq,
    Debug
    )

    Operation (binary or unary)

    ParamType

    pub(all) enum ParamType {
    Any
    ParamBool
    ParamNumber
    ParamString
    ParamArray(ParamType)
    ParamObject(ParamType)
    Nullable(ParamType)
    OneOf(Array[ParamType])
    } derive(Eq,
    Debug
    )

    Parameter type hint for function argument validation

    ParamType::display_name

    fn ParamType::display_name(self : ParamType) -> String

    Get display name for ParamType (for error messages)

    ParamType::is_satisfied_by

    fn ParamType::is_satisfied_by(self : ParamType, value : HCLValue) -> Bool

    Check if a value satisfies this parameter type

    Parser

    pub struct Parser {
    lexer : Lexer
    current : Token
    peek : Token
    next_prefix : String?
    }

    HCL Parser - parses HCL input into structured data

    Parser::from_lexer

    fn Parser::from_lexer(lexer : Lexer) -> Result[Parser, HCLError]

    Create a new parser from lexer

    Parser::new

    fn Parser::new(input : String) -> Result[Parser, HCLError]

    Create a new parser from string input

    Parser::parse_body

    fn Parser::parse_body(self : Parser) -> Result[Body, HCLError]

    Parse HCL input into a Body

    Span

    pub struct Span {
    start_line : Int
    start_col : Int
    start_offset : Int
    end_line : Int
    end_col : Int
    end_offset : Int
    } derive(Eq,
    Debug
    )

    Source span - tracks position in source text

    Span::empty

    fn Span::empty() -> Span

    Create an empty (zero) Span

    Span::merge

    fn Span::merge(a : Span, b : Span) -> Span

    Merge two spans: start from a, end from b

    Span::new

    fn Span::new(start_line : Int, start_col : Int, start_offset : Int, end_line : Int, end_col : Int, end_offset : Int) -> Span

    Create a new Span

    Spanned

    pub struct Spanned[T] {
    value : T
    span : Span?
    } derive(Eq,
    Debug
    )

    Value with optional source span

    Spanned::bare

    fn[T] Spanned::bare(value : T) -> Spanned[T]

    Create a Spanned value without span

    Spanned::get_span

    fn[T] Spanned::get_span(self : Spanned[T]) -> Span?

    Get the span

    Spanned::new

    fn[T] Spanned::new(value : T, span : Span) -> Spanned[T]

    Create a Spanned value with span

    Spanned::unwrap

    fn[T] Spanned::unwrap(self : Spanned[T]) -> T

    Get the inner value

    Template

    pub struct Template {
    parts : Array[TemplatePart]
    }

    Template representation

    Template::evaluate

    fn Template::evaluate(self : Template, variables : Map[String, HCLValue], functions : Map[String, FuncDef]) -> Result[String, HCLError]

    Evaluate template with given context

    Template::from_heredoc

    fn Template::from_heredoc(input : String, _delimiter : String, strip : Bool) -> Result[Template, HCLError]

    Parse heredoc content

    Template::from_string

    fn Template::from_string(input : String) -> Result[Template, HCLError]

    Parse string with template expressions

    Template::new

    fn Template::new() -> Template

    Create new template

    TemplateExpr

    pub(all) enum TemplateExpr {
    Heredoc(Heredoc)
    InterpolatedString(String)
    } derive(Eq,
    Debug
    )

    Template expression (heredoc or interpolated string)

    TemplatePart

    pub(all) enum TemplatePart {
    Text(String)
    Interpolation(Expression)
    ConditionalStart(Expression)
    ConditionalElseIf(Expression)
    ConditionalElse
    ConditionalEnd
    ForStart(String, Expression)
    ForEnd
    InterpolationStrip(Expression, Bool, Bool)
    ConditionalStartStrip(Expression, Bool, Bool)
    ConditionalElseIfStrip(Expression, Bool, Bool)
    ConditionalElseStrip(Bool, Bool)
    ConditionalEndStrip(Bool, Bool)
    ForStartStrip(String, Expression, Bool, Bool)
    ForEndStrip(Bool, Bool)
    } derive(Eq,
    Debug
    )

    Template part types

    Token

    pub(all) enum Token {
    Ident(String)
    StringLit(String)
    NumberLit(String)
    BoolLit(Bool)
    NullLit
    LBrace
    RBrace
    LBracket
    RBracket
    LParen
    RParen
    Equals
    Comma
    Dot
    Plus
    Minus
    Star
    Slash
    Percent
    Bang
    Lt
    Gt
    LtEq
    GtEq
    EqEq
    BangEq
    AndAnd
    OrOr
    Question
    Colon
    FatArrow
    Heredoc(Bool)
    HeredocLit(String, String, Bool)
    Newline
    EOF
    For
    In
    If
    } derive(Eq,
    Debug
    )

    HCL Token types

    Token::is_delimiter

    fn Token::is_delimiter(self : Token) -> Bool

    Token::is_literal

    fn Token::is_literal(self : Token) -> Bool

    Token::is_operator

    fn Token::is_operator(self : Token) -> Bool

    Token::precedence

    fn Token::precedence(self : Token) -> Int

    Traversal

    pub(all) struct Traversal {
    base : Expression
    operators : Array[TraversalOperator]
    } derive(Eq,
    Debug
    )

    Traversal (property/element access)

    Traversal::builder

    fn Traversal::builder(base : Expression) -> TraversalBuilder

    Create a TraversalBuilder starting from this Traversal

    TraversalBuilder

    pub struct TraversalBuilder {
    base : Expression
    operators : Array[TraversalOperator]
    }

    Builder for constructing Traversal expressions incrementally

    TraversalBuilder::attr

    fn TraversalBuilder::attr(self : TraversalBuilder, name : String) -> TraversalBuilder

    Add an attribute access operator (.attr)

    TraversalBuilder::build

    Build the Traversal expression

    TraversalBuilder::index

    Add an index access operator ([expr])

    TraversalBuilder::new

    Create a new TraversalBuilder from a base expression

    TraversalBuilder::splat

    Add a splat access operator (.*)

    TraversalOperator

    pub(all) enum TraversalOperator {
    Attr(String)
    Index(Expression)
    Splat
    } derive(Eq,
    Debug
    )

    Traversal operator

    TypeName

    pub(all) enum TypeName {
    TNull
    TBool
    TNumber
    TString
    TArray
    TObject
    TUnknown
    } derive(Eq,
    Debug
    )

    HCL type categories for unification

    TypeSchema

    pub(all) enum TypeSchema {
    Any
    NullSchema
    BoolSchema
    IntSchema
    Int64Schema
    FloatSchema
    NumberSchema
    StringSchema
    ArraySchema(TypeSchema)
    ObjectSchema(Map[String, FieldSchema])
    } derive(Eq,
    Debug
    )

    Schema for validating HCL values

    TypeSchema::any

    fn TypeSchema::any() -> TypeSchema

    Schema for any value

    TypeSchema::array

    fn TypeSchema::array(element : TypeSchema) -> TypeSchema

    Schema for array

    TypeSchema::bool

    fn TypeSchema::bool() -> TypeSchema

    Schema for boolean

    TypeSchema::float

    fn TypeSchema::float() -> TypeSchema

    Schema for float

    TypeSchema::int

    fn TypeSchema::int() -> TypeSchema

    Schema for integer

    TypeSchema::int64

    fn TypeSchema::int64() -> TypeSchema

    Schema for 64-bit integer

    TypeSchema::null

    fn TypeSchema::null() -> TypeSchema

    Schema for null

    TypeSchema::number

    fn TypeSchema::number() -> TypeSchema

    Schema for number (int or float)

    TypeSchema::object

    fn TypeSchema::object(fields : Map[String, FieldSchema]) -> TypeSchema

    Schema for object

    TypeSchema::string

    fn TypeSchema::string() -> TypeSchema

    Schema for string

    UnaryOp

    pub(all) struct UnaryOp {
    op : UnaryOperator
    operand : Expression
    } derive(Eq,
    Debug
    )

    Unary operation

    UnaryOperator

    pub(all) enum UnaryOperator {
    Negate
    Not
    } derive(Eq,
    Debug
    )

    Unary operator

    Variable

    pub(all) struct Variable {
    name : String
    } derive(Eq,
    Debug
    )

    Variable reference

    body_to_json

    fn body_to_json(body : Body) -> String

    Convert Body to JSON string (HCL JSON spec-compliant)

    body_to_json_pretty

    fn body_to_json_pretty(body : Body) -> String

    Convert Body to JSON string with pretty printing

    builtin_functions

    fn builtin_functions() -> Map[String, FuncDef]

    Get all built-in functions

    collect_functions

    fn collect_functions(body : Body) -> Array[String]

    Collect all unique function names called in the body (from ExprFuncCall nodes)

    collect_functions_from_expr

    fn collect_functions_from_expr(expr : Expression) -> Array[String]

    Collect all unique function names from a single expression

    collect_traversals

    fn collect_traversals(body : Body) -> Array[String]

    Collect all unique traversal root variable names (from ExprTraversal where base is ExprVariable)

    collect_traversals_from_expr

    fn collect_traversals_from_expr(expr : Expression) -> Array[String]

    Collect all unique traversal root variable names from a single expression

    collect_variables

    fn collect_variables(body : Body) -> Array[String]

    Collect all unique variable names referenced in the body (from ExprVariable nodes)

    collect_variables_from_expr

    fn collect_variables_from_expr(expr : Expression) -> Array[String]

    Collect all unique variable names from a single expression

    convert_value

    fn convert_value(v : HCLValue, target : TypeName) -> Result[HCLValue, HCLError]

    Convert a value to the target type per HCL conversion rules

    decorated_expr_to_string

    fn decorated_expr_to_string(de : Decorated[Expression]) -> String

    Convert Decorated[Expression] to string

    escape_hcl_string

    fn escape_hcl_string(s : String) -> String

    Escape a string for HCL

    eval_binary

    fn eval_binary(left : HCLValue, op : String, right : HCLValue) -> Result[HCLValue, HCLError]

    Evaluate binary operation on two HCLValues

    eval_conditional

    fn eval_conditional(condition : HCLValue, true_expr : HCLValue, false_expr : HCLValue) -> Result[HCLValue, HCLError]

    Evaluate conditional expression (cond ? true : false)

    eval_expr

    fn eval_expr(expr : Expression, variables : Map[String, HCLValue], functions : Map[String, FuncDef]) -> Result[HCLValue, HCLError]

    Evaluate expression (handles all expression types)

    eval_expr_simple

    fn eval_expr_simple(expr : Expression) -> Result[HCLValue, HCLError]

    Evaluate expression with default empty context

    eval_unary

    fn eval_unary(op : String, operand : HCLValue) -> Result[HCLValue, HCLError]

    Evaluate unary operation on HCLValue

    evaluate_template

    fn evaluate_template(input : String, variables : Map[String, HCLValue], functions : Map[String, FuncDef]) -> Result[String, HCLError]

    Evaluate template string directly

    expr_array

    fn expr_array(items : Array[Expression]) -> Expression

    Create Expression array

    expr_bool

    fn expr_bool(v : Bool) -> Expression

    Create Expression from Bool

    expr_func_call

    fn expr_func_call(fc : FuncCall) -> Expression

    Create Expression from FuncCall

    expr_int

    fn expr_int(v : Int) -> Expression

    Create Expression from Int

    expr_null

    fn expr_null() -> Expression

    Null Expression

    expr_str

    fn expr_str(v : String) -> Expression

    Create Expression from String

    expr_to_hcl_value

    fn expr_to_hcl_value(expr : Expression) -> HCLValue

    Convert Expression to HCLValue (bridge for serializers)

    expr_to_string

    fn expr_to_string(expr : Expression) -> String

    Convert Expression to string representation

    expr_unknown

    fn expr_unknown() -> Expression

    Unknown Expression (Terraform plan-stage)

    extract_body

    fn extract_body(body : Body, schema : BodySchema) -> Result[ExtractedBody, Array[HCLError]]

    Extract structured data from an HCL Body using a BodySchema

    format_attr_with_decor

    fn format_attr_with_decor(attr : Attr) -> String

    Format Attr with decor

    format_body

    fn format_body(body : Body) -> String

    Format HCL Body to string

    format_body_with_decor

    fn format_body_with_decor(body : Body) -> String

    Format Body with decor

    format_value_content

    fn format_value_content(value : HCLValue) -> String

    Format HCLValue content without decor

    format_value_with_decor

    fn format_value_with_decor(value : HCLValue) -> String

    Format HCLValue with decor

    from_hcl_body

    fn from_hcl_body(input : String) -> Result[Body, HCLError]

    Deserialize from HCL string to Body

    from_hcl_bool

    fn from_hcl_bool(input : String) -> Result[Bool, HCLError]

    Deserialize from HCL string to Bool

    from_hcl_int

    fn from_hcl_int(input : String) -> Result[Int, HCLError]

    Deserialize from HCL string to Int

    from_hcl_str

    fn[T : FromHCL] from_hcl_str(input : String) -> Result[T, HCLError]

    Parse HCL string to any FromHCL type

    from_hcl_string

    fn from_hcl_string(input : String) -> Result[String, HCLError]

    Deserialize from HCL string to String

    from_hcl_value

    fn from_hcl_value(input : String) -> Result[HCLValue, HCLError]

    Deserialize from HCL string to HCLValue

    from_hcl_with_body_schema

    fn from_hcl_with_body_schema(input : String, schema : BodySchema) -> Result[ExtractedBody, Array[HCLError]]

    Deserialize from HCL string using a BodySchema, returning ExtractedBody

    from_hcl_with_schema

    fn from_hcl_with_schema(input : String, schema : TypeSchema) -> Result[HCLValue, HCLError]

    Deserialize HCL with schema validation

    from_hcl_with_schema_full

    fn from_hcl_with_schema_full(input : String, schema : TypeSchema) -> Result[HCLValue, Array[HCLError]]

    Deserialize HCL with schema, return all errors

    hcl_array

    fn hcl_array(items : Array[HCLValue]) -> HCLValue

    Create Array HCLValue

    hcl_bool

    fn hcl_bool(v : Bool) -> HCLValue

    Create Bool HCLValue

    hcl_float

    fn hcl_float(v : Double) -> HCLValue

    Create Float HCLValue

    hcl_int

    fn hcl_int(v : Int) -> HCLValue

    Create Int HCLValue

    hcl_int64

    fn hcl_int64(v : Int64) -> HCLValue

    Create Int64 HCLValue

    hcl_null

    fn hcl_null() -> HCLValue

    Create Null HCLValue

    hcl_object

    fn hcl_object(entries : Map[String, HCLValue]) -> HCLValue

    Create Object HCLValue

    hcl_object_entries

    fn hcl_object_entries(obj : Map[String, HCLValue]) -> Array[(String, HCLValue)]

    Get key-value pairs in insertion order

    hcl_object_extend

    fn hcl_object_extend(obj : Map[String, HCLValue], other : Map[String, HCLValue]) -> Unit

    Extend obj with entries from another object (mutates obj)

    hcl_object_from_pairs

    fn hcl_object_from_pairs(pairs : Array[(String, HCLValue)]) -> Map[String, HCLValue]

    Create HCLObject from array of key-value pairs

    hcl_object_keys

    fn hcl_object_keys(obj : Map[String, HCLValue]) -> Array[String]

    Get keys in insertion order

    hcl_object_merge

    fn hcl_object_merge(lhs : Map[String, HCLValue], rhs : Map[String, HCLValue]) -> Map[String, HCLValue]

    Merge two objects. Keys from rhs override keys from lhs.

    hcl_object_values

    fn hcl_object_values(obj : Map[String, HCLValue]) -> Array[HCLValue]

    Get values in insertion order

    hcl_str

    fn hcl_str(v : String) -> HCLValue

    Create String HCLValue

    hcl_to_json

    fn hcl_to_json(input : String) -> Result[String, HCLError]

    Convert HCL string to JSON string

    hcl_to_json_pretty

    fn hcl_to_json_pretty(input : String) -> Result[String, HCLError]

    Convert HCL string to JSON string with pretty printing

    hcl_value_to_expression

    fn hcl_value_to_expression(value : HCLValue) -> Expression

    Convert HCLValue to Expression

    int_in_range

    fn int_in_range(min : Int, max : Int) -> ((HCLValue, String) -> Array[HCLError])

    Validator: int in range

    is_id_continue

    fn is_id_continue(ch : Char) -> Bool

    Determines if ch is a valid HCL identifier continue character.

    Valid continue: a-z, A-Z, 0-9, underscore, hyphen, and Unicode XID_Continue characters (combining marks)

    is_id_start

    fn is_id_start(ch : Char) -> Bool

    Determines if ch is a valid HCL identifier start character.

    Valid start: a-z, A-Z, underscore, and Unicode XID_Start characters (Latin extended, CJK, Hangul, Cyrillic, Greek, Arabic, etc.)

    is_ident

    fn is_ident(s : String) -> Bool

    Determines if s is a valid HCL identifier.

    A valid identifier must:
    • Not be empty
    • First char passes is_id_start
    • All remaining chars pass is_id_continue

    is_valid

    fn is_valid(value : HCLValue, schema : TypeSchema) -> Bool

    Check if value is valid

    json_to_body

    fn json_to_body(input : String) -> Result[Body, HCLError]

    Convert JSON string to HCL Body

    json_to_hcl_string

    fn json_to_hcl_string(input : String) -> Result[String, HCLError]

    Convert JSON string to HCL formatted string

    new_hcl_object

    fn new_hcl_object() -> Map[String, HCLValue]

    Create an empty HCLObject

    parse

    fn parse(input : String) -> Result[Body, HCLError]

    Parse HCL string into Body

    parse_template

    fn parse_template(input : String) -> Result[Template, HCLError]

    Parse template from string (simple version)

    simplify_body

    fn simplify_body(body : Body) -> Body

    Simplify all values in a Body by evaluating constant expressions

    string_not_empty

    fn string_not_empty() -> ((HCLValue, String) -> Array[HCLError])

    Validator: string not empty

    string_starts_with

    fn string_starts_with(prefix : String) -> ((HCLValue, String) -> Array[HCLError])

    Validator: string matches pattern (simple prefix/suffix check)

    substring

    fn substring(s : String, start : Int, end : Int) -> String

    Extract substring from string

    to_hcl_body

    fn to_hcl_body(body : Body) -> String

    Serialize Body to HCL string

    to_hcl_bool

    fn to_hcl_bool(value : Bool) -> String

    Serialize Bool to HCL string

    to_hcl_int

    fn to_hcl_int(value : Int) -> String

    Serialize Int to HCL string

    to_hcl_str

    fn[T : ToHCL] to_hcl_str(value : T) -> String

    Convert any ToHCL type to HCL string

    to_hcl_string

    fn to_hcl_string(value : String) -> String

    Serialize String to HCL string

    to_hcl_value

    fn to_hcl_value(value : HCLValue) -> String

    Serialize HCLValue to HCL string

    type_of

    fn type_of(v : HCLValue) -> TypeName

    Get the TypeName for a given HCLValue

    unify_types

    fn unify_types(a : TypeName, b : TypeName) -> Result[TypeName, HCLError]

    Find the common type for two types per HCL spec rules

    validate

    fn validate(value : HCLValue, schema : TypeSchema) -> Array[HCLError]

    Validate a value against a schema

    validate_ex

    fn validate_ex(value : HCLValue, schema : Map[String, FieldSchemaEx]) -> Array[HCLError]

    Validate with custom validators

    validate_one

    fn validate_one(value : HCLValue, schema : TypeSchema) -> Result[Unit, HCLError]

    Validate and return first error, or Ok

    visit_attr_default

    fn[V : Visit] visit_attr_default(v : V, attr : Attr) -> Unit

    Default attr visitor - visits spanned value

    visit_attr_mut_default

    fn[V : VisitMut] visit_attr_mut_default(v : V, attr : Attr) -> Unit

    Default attr visitor mutably - visits spanned value

    visit_binary_op_default

    fn[V : Visit] visit_binary_op_default(v : V, binop : BinaryOp) -> Unit

    Default binary op visitor

    visit_binary_op_mut_default

    fn[V : VisitMut] visit_binary_op_mut_default(v : V, binop : BinaryOp) -> Unit

    Default binary op visitor mutably

    visit_block_default

    fn[V : Visit] visit_block_default(v : V, block : Block) -> Unit

    Default block visitor - visits body

    visit_block_mut_default

    fn[V : VisitMut] visit_block_mut_default(v : V, block : Block) -> Unit

    Default block visitor mutably

    visit_body_default

    fn[V : Visit] visit_body_default(v : V, body : Body) -> Unit

    Default body visitor - iterates over all items

    visit_body_item_default

    fn[V : Visit] visit_body_item_default(v : V, item : BodyItem) -> Unit

    Default body item visitor - dispatches to attr or block

    visit_body_item_mut_default

    fn[V : VisitMut] visit_body_item_mut_default(v : V, item : BodyItem) -> Unit

    Default body item visitor mutably

    visit_body_mut_default

    fn[V : VisitMut] visit_body_mut_default(v : V, body : Body) -> Unit

    Default body visitor mutably

    visit_conditional_default

    fn[V : Visit] visit_conditional_default(v : V, cond : Conditional) -> Unit

    Default conditional visitor

    visit_conditional_mut_default

    fn[V : VisitMut] visit_conditional_mut_default(v : V, cond : Conditional) -> Unit

    Default conditional visitor mutably

    visit_decorated_expr_default

    fn[V : Visit] visit_decorated_expr_default(v : V, de : Decorated[Expression]) -> Unit

    Default decorated expression visitor

    visit_decorated_expr_mut_default

    fn[V : VisitMut] visit_decorated_expr_mut_default(v : V, de : Decorated[Expression]) -> Unit

    Default decorated expression visitor mutably

    visit_expr_default

    fn[V : Visit] visit_expr_default(v : V, expr : Expression) -> Unit

    Default expression visitor - dispatches based on variant

    visit_expr_mut_default

    fn[V : VisitMut] visit_expr_mut_default(v : V, expr : Expression) -> Unit

    Default expression visitor mutably

    visit_for_expr_default

    fn[V : Visit] visit_for_expr_default(v : V, for_expr : ForExpr) -> Unit

    Default for expression visitor

    visit_for_expr_mut_default

    fn[V : VisitMut] visit_for_expr_mut_default(v : V, for_expr : ForExpr) -> Unit

    Default for expression visitor mutably

    visit_func_call_default

    fn[V : Visit] visit_func_call_default(v : V, call : FuncCall) -> Unit

    Default function call visitor

    visit_func_call_mut_default

    fn[V : VisitMut] visit_func_call_mut_default(v : V, call : FuncCall) -> Unit

    Default function call visitor mutably

    visit_heredoc_default

    fn[V] visit_heredoc_default(_v : V, _heredoc : Heredoc) -> Unit

    Default heredoc visitor (no-op)

    visit_heredoc_mut_default

    fn[V] visit_heredoc_mut_default(_v : V, _heredoc : Heredoc) -> Unit

    Default heredoc visitor mutably (no-op)

    visit_object_key_default

    fn[V : Visit] visit_object_key_default(v : V, key : ObjectKey) -> Unit

    Default object key visitor

    visit_object_key_mut_default

    fn[V : VisitMut] visit_object_key_mut_default(v : V, key : ObjectKey) -> Unit

    Default object key visitor mutably

    visit_operation_default

    fn[V : Visit] visit_operation_default(v : V, op : Operation) -> Unit

    Default operation visitor

    visit_operation_mut_default

    fn[V : VisitMut] visit_operation_mut_default(v : V, op : Operation) -> Unit

    Default operation visitor mutably

    visit_spanned_expr_default

    fn[V : Visit] visit_spanned_expr_default(v : V, spanned : Spanned[Expression]) -> Unit

    Default spanned expression visitor - unwraps and visits expression

    visit_spanned_expr_mut_default

    fn[V : VisitMut] visit_spanned_expr_mut_default(v : V, spanned : Spanned[Expression]) -> Unit

    Default spanned expression visitor mutably - unwraps and visits expression

    visit_template_expr_default

    fn[V : Visit] visit_template_expr_default(v : V, tmpl : TemplateExpr) -> Unit

    Default template expression visitor

    visit_template_expr_mut_default

    fn[V : VisitMut] visit_template_expr_mut_default(v : V, tmpl : TemplateExpr) -> Unit

    Default template expression visitor mutably

    visit_traversal_default

    fn[V : Visit] visit_traversal_default(v : V, trav : Traversal) -> Unit

    Default traversal visitor

    visit_traversal_mut_default

    fn[V : VisitMut] visit_traversal_mut_default(v : V, trav : Traversal) -> Unit

    Default traversal visitor mutably

    visit_traversal_operator_default

    fn[V : Visit] visit_traversal_operator_default(v : V, op : TraversalOperator) -> Unit

    Default traversal operator visitor

    visit_traversal_operator_mut_default

    fn[V : VisitMut] visit_traversal_operator_mut_default(v : V, op : TraversalOperator) -> Unit

    Default traversal operator visitor mutably

    visit_unary_op_default

    fn[V : Visit] visit_unary_op_default(v : V, unop : UnaryOp) -> Unit

    Default unary op visitor

    visit_unary_op_mut_default

    fn[V : VisitMut] visit_unary_op_mut_default(v : V, unop : UnaryOp) -> Unit

    Default unary op visitor mutably

    visit_value_default

    fn[V : Visit] visit_value_default(v : V, value : HCLValue) -> Unit

    Default value visitor - dispatches based on variant

    visit_value_mut_default

    fn[V : VisitMut] visit_value_mut_default(v : V, value : HCLValue) -> Unit

    Default value visitor mutably