hcl

    HCL parser, formatter, and serialization library for MoonBit

    hcl
    parser
    formatter
    terraform
    configuration
    Download zip
    Author
    Version
    0.2.0
    License
    Apache-2.0
    Last updated
    3 months ago
    Downloads
    73

    No dependencies

    #HCL for MoonBit

    mooncake Docs License: Apache-2.0 CI

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

    100% of the official HCL spec suite passes (comments, structure, expressions, heredocs, operators; fixtures inline in spec_test.mbt). 83 built-in functions modeled on Terraform's standard library (crypto functions skipped — MoonBit has no crypto module). Zero external dependencies.

    This README is a literate test file. Every mbt check block below is compiled and run by moon test, so the examples stay in sync with the API.

    #Features

    #Core

    • 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 - ToHCL/FromHCL traits for type-safe conversion
    • Format HCL - Configurable Formatter with proper indentation
    • Preserve comments and whitespace - Decor system for parse-modify-serialize cycles
    • Source position tracking - Span info on Attr, Block, Body nodes

    #Expressions

    • Binary ops - +, -, *, /, %, ==, !=, <, >, <=, >=, &&, ||
    • Unary ops - -, !
    • Conditional - cond ? true_val : false_val (with type unification)
    • For expressions - List comprehension [for x in list: expr], object comprehension {for k, v in obj: k => v}, if filter
    • Splat operator - list.*.attr, list[*].attr
    • Property access - obj.key, obj["key"], arr[0]
    • Function calls - Full function call framework
    • Parenthesized - Grouping and precedence override

    #Templates

    • String interpolation - ${expr}
    • Template directives - %{if}, %{else if}, %{else}, %{endif}, %{for}, %{endfor}
    • Strip markers - ${~ expr ~}, %{~ directive ~} for whitespace control
    • Heredoc - <<EOF, <<-EOF with custom delimiters

    #Built-in Functions (83)

    • Numeric (9) - abs, ceil, floor, log, max, min, parseint, pow, signum
    • Collection (22) - length, keys, values, contains, flatten, merge, reverse, distinct, sort, slice, element, index, concat, coalesce, coalescelist, compact, range, chunklist, lookup, zipmap, transpose, matchkeys
    • Aggregation (4) - sum, alltrue, anytrue, one
    • Set (6) - setunion, setintersection, setsubtract, setsymmetricdifference, setproduct, setissubset
    • String (20) - chomp, indent, join, lower, upper, replace, split, strrev, substr, trim, trimprefix, trimsuffix, trimspace, format, formatlist, startswith, endswith, strcontains, title, templatestring
    • Type conversion (6) - tobool, tonumber, tolist, tomap, toset, tostring
    • Encoding (6) - jsondecode, jsonencode, base64decode, base64encode, csvdecode, urlencode
    • DateTime (3) - formatdate, timeadd, timecmp
    • Network (4) - cidrhost, cidrnetmask, cidrsubnet, cidrsubnets
    • Regex (3) - regex, regexall, regex_replace

    #Types & Validation

    • Schema validation - TypeSchema type checking, required fields, custom validators
    • Body schema extraction - BodySchema/BlockSchema/LabelSchema for structured body extraction
    • Type unification - unify_types, convert_value for implicit type coercion (string↔number↔bool)
    • Unknown values - HCLValue::Unknown for Terraform partial-evaluation compatibility
    • Dynamic types - TDynamic variant in TypeName, unifies with any type
    • FuncDef parameter system - ParamType (Any, Bool, Number, String, Array, Object, Nullable, OneOf) with automatic validation

    #Identifiers

    • Unicode support - XID_Start/XID_Continue (CJK, Hangul, Cyrillic, Greek, Arabic, Devanagari, Thai, Latin Extended, etc.)
    • Number literals - Decimal, hex (0x), octal (0o), binary (0b), scientific notation, float

    #JSON

    • HCL→JSON - hcl_to_json(), body_to_json_pretty() (spec-compliant, handles nested blocks/labels)
    • JSON→HCL - json_to_body() parses terraform.tfvars.json into HCL Body

    #Analysis & Transformation

    • Static analysis - collect_variables, collect_functions, collect_traversals on Body or Expression
    • Expression simplification - simplify_body for constant folding at parse time
    • Parse error recovery - parse_with_recovery accumulates multiple errors, returns partial Body
    • FuncRegistry API - FuncRegistry for registering custom functions with built-in merge
    • AST traversal - Immutable (Visit) and mutable (VisitMut) visitor pattern
    • Decor system - Decor, Decorated[T] for comment/whitespace preservation

    #Installation

    Add the dependency to your moon.mod:

    import { "lenitain/hcl@0.2.0" }

    Or with the MoonBit CLI:

    moon add lenitain/hcl

    #Quick Start

    ///|
    test "quick start" {
    let input = "name = \"John\"\nport = 8080"
    let body = parse(input).unwrap()
    assert_eq(body.len(), 2)

    // Access attributes
    let name = body.find_attr("name").unwrap()
    assert_eq(expr_to_hcl_value(name.get_value()).as_string().unwrap(), "John")
    assert_eq(
    expr_to_hcl_value(body.find_attr("port").unwrap().get_value())
    .as_int()
    .unwrap(),
    8080,
    )

    // Serialize back to HCL
    assert_eq(to_hcl_body(body), "name = \"John\"\nport = 8080")

    // Convert to JSON
    assert_eq(body_to_json(body), "{\"name\":\"John\",\"port\":8080}")

    // Evaluate expressions (constant folding)
    let simplified = simplify_body(parse("x = 1 + 2 * 3").unwrap())
    assert_eq(body_to_json(simplified), "{\"x\":7}")
    }

    #Parsing

    parse reads an HCL string into a Body — a list of Attribute and Block items. Body and Block expose accessors like find_attr, find_block and get_labels:

    ///|
    test "parse blocks with labels" {
    let input = "resource \"aws_instance\" \"example\" {\n ami = \"ami-123\"\n instance_type = \"t2.micro\"\n}"
    let body = parse(input).unwrap()
    let block = body.find_block("resource").unwrap()
    assert_eq(block.get_type_name(), "resource")
    assert_eq(block.get_labels(), ["aws_instance", "example"])
    assert_eq(block.get_body().find_attr("ami").unwrap().get_key(), "ami")
    }

    Parse failures are reported as HCLError:

    ///|
    test "parse errors" {
    match parse("age thirty") {
    Err(e) => assert_true(e.to_display_string().contains("--> line 1"))
    Ok(_) => panic()
    }
    }

    #Serialization & Formatting

    Values, bodies and arbitrary ToHCL-implementing types serialize back to HCL text. The Formatter controls indentation, density and key quoting:

    ///|
    test "serialize values" {
    assert_eq(to_hcl_int(42), "42")
    assert_eq(to_hcl_string("hi"), "\"hi\"")
    assert_eq(to_hcl_bool(true), "true")
    assert_eq(to_hcl_value(hcl_int(7)), "7")
    assert_eq(to_hcl_value(hcl_str("x")), "\"x\"")
    }

    ///|
    test "format with formatter" {
    let body = parse("name = \"test\"").unwrap()
    let fmt = Formatter::new().set_dense(true).set_prefer_ident_keys(true)
    assert_eq(fmt.format_body(body), "name = \"test\"")
    }

    #Deserialization

    The FromHCL trait converts HCL text into typed MoonBit values — maps, arrays and nested structures of String / Int / Bool / ... :

    ///|
    test "from_hcl_str into typed values" {
    let strings : HCLResult[Map[String, String]] = from_hcl_str("val = \"hello\"")
    assert_eq(strings.unwrap()["val"], "hello")

    let ints : HCLResult[Map[String, Int]] = from_hcl_str("val = 42")
    assert_eq(ints.unwrap()["val"], 42)

    let bools : HCLResult[Map[String, Bool]] = from_hcl_str("val = true")
    assert_eq(bools.unwrap()["val"], true)
    }

    ///|
    test "to_hcl_str roundtrip" {
    let original = "hello world"
    let hcl = to_hcl_str(original)
    let result : HCLResult[Map[String, String]] = from_hcl_str("val = " + hcl)
    assert_eq(result.unwrap()["val"], original)
    }

    For selective reads/writes on an already-parsed Body (the hcl-rs serde use case, following lenitain/kdl's decode_prop/encode_children pattern), typed helpers decode attributes and blocks, and encode values into attributes/blocks:

    ///|
    test "typed decode/encode helpers" {
    let body = parse("server {\n port = 8080\n host = \"x\"\n}").unwrap()
    let port : Int = decode_attr(
    body.find_block("server").unwrap().get_body(),
    "port",
    ).unwrap()
    assert_eq(port, 8080)

    let cfgs : Array[Map[String, Int]] = decode_blocks(
    parse("server {\n port = 80\n}\nserver {\n port = 443\n}").unwrap(),
    "server",
    ).unwrap()
    assert_eq(cfgs.length(), 2)
    assert_eq(cfgs[1]["port"], 443)

    let blk = encode_block("server", ["web"], { "port": 8080 }).unwrap()
    assert_eq(blk.get_labels(), ["web"])
    }

    #Expression Evaluation

    Evaluate any Expression with eval_expr_simple (no variables) or eval_expr (with variables and functions). simplify_body folds constants at parse time:

    ///|
    test "evaluate expressions" {
    let expr = parse("v = 1 + 2 * 3").unwrap().find_attr("v").unwrap().get_value()
    match eval_expr_simple(expr) {
    Ok(v) => assert_eq(v.as_int().unwrap(), 7)
    Err(_) => panic()
    }
    }

    ///|
    test "evaluate with variables" {
    let expr = parse("v = x + 1").unwrap().find_attr("v").unwrap().get_value()
    let variables : Map[String, HCLValue] = { "x": hcl_int(41) }
    match eval_expr(expr, variables, Map([])) {
    Ok(v) => assert_eq(v.as_int().unwrap(), 42)
    Err(_) => panic()
    }
    }

    #Built-in Functions

    83 built-in functions come from builtin_functions(), modeled on Terraform's standard library (crypto and filesystem functions excluded). Register custom functions with FuncRegistry and evaluate them alongside the built-ins:

    ///|
    test "built-in functions" {
    let funcs = builtin_functions()
    assert_true(funcs.contains("abs"))
    assert_true(funcs.contains("upper"))

    let expr = parse("v = upper(\"hello\")")
    .unwrap()
    .find_attr("v")
    .unwrap()
    .get_value()
    match eval_expr(expr, Map([]), funcs) {
    Ok(v) => assert_eq(v.as_string().unwrap(), "HELLO")
    Err(_) => panic()
    }
    }

    ///|
    test "custom functions with FuncRegistry" {
    let double = FuncDef::builder()
    .param(ParamNumber)
    .build("double", fn(args) {
    match args[0].as_int() {
    Some(n) => Ok(hcl_int(n * 2))
    None => Err(HCLError::type_error("expected a number"))
    }
    })
    let funcs = FuncRegistry::new().register("double", double).build()
    let expr = parse("v = double(21)")
    .unwrap()
    .find_attr("v")
    .unwrap()
    .get_value()
    match eval_expr(expr, Map([]), funcs) {
    Ok(v) => assert_eq(v.as_int().unwrap(), 42)
    Err(_) => panic()
    }
    }

    #Templates

    HCL templates interpolate ${expr} and support %{if} / %{for} directives. evaluate_template is the one-shot entry point:

    ///|
    test "template interpolation" {
    let vars = { "name": HCLValue::String("World", Decor::empty()) }
    match evaluate_template("Hello, ${name}!", vars, Map([])) {
    Ok(result) => assert_eq(result, "Hello, World!")
    Err(_) => panic()
    }
    }

    ///|
    test "template directives" {
    let vars = {
    "items": HCLValue::Array(
    [
    HCLValue::String("a", Decor::empty()),
    HCLValue::String("b", Decor::empty()),
    ],
    Decor::empty(),
    ),
    }
    match
    evaluate_template("%{for item in items}${item} %{endfor}", vars, Map([])) {
    Ok(result) => assert_eq(result, "a b ")
    Err(_) => panic()
    }
    }

    #Schema Validation

    TypeSchema checks values against a typed schema; BodySchema/BlockSchema extract structured data from a parsed Body:

    ///|
    test "type schema validation" {
    let schema = TypeSchema::object({
    "name": FieldSchema::required(TypeSchema::string()),
    "port": FieldSchema::required(TypeSchema::int()),
    })
    let value = hcl_object({ "name": hcl_str("web"), "port": hcl_int(8080) })
    assert_eq(validate(value, schema).length(), 0)
    assert_true(is_valid(value, schema))
    }

    ///|
    test "body schema extraction" {
    let body = parse(
    "server \"web\" {\n port = 8080\n}\nserver \"api\" {\n port = 3000\n}",
    ).unwrap()
    let schema = BodySchema::new().with_blocks({
    "server": BlockSchema::new(
    BodySchema::new().with_attrs({
    "port": AttrSchema::required(TypeSchema::int()),
    }),
    ).with_labels([LabelSchema::required()]),
    })
    match extract_body(body, schema) {
    Ok(extracted) => {
    let servers = extracted.get_blocks("server")
    assert_eq(servers.length(), 2)
    assert_eq(servers[0].get_label(0), Some("web"))
    assert_eq(servers[1].get_label(0), Some("api"))
    }
    Err(_) => panic()
    }
    }

    #JSON Conversion

    HCL and JSON interconvert for tooling compatibility (terraform.tfvars / terraform.tfvars.json):

    ///|
    test "hcl to json" {
    assert_eq(hcl_to_json("a = 1").unwrap(), "{\"a\":1}")
    assert_eq(
    hcl_to_json("region = \"us-east-1\"").unwrap(),
    "{\"region\":\"us-east-1\"}",
    )
    assert_eq(hcl_to_json_pretty("a = 1").unwrap(), "{\n \"a\": 1\n}")
    }

    ///|
    test "json to hcl" {
    let body = json_to_body("{\"name\": \"John\", \"age\": 30}").unwrap()
    assert_eq(body.len(), 2)
    assert_eq(
    expr_to_string(body.find_attr("name").unwrap().get_value()),
    "\"John\"",
    )
    assert_eq(expr_to_string(body.find_attr("age").unwrap().get_value()), "30")
    }

    #Errors

    Parse, evaluation, and validation failures are reported as HCLError. to_display_string() renders an error as a miette-style report — an error: header, a --> line N, col M location, the offending source line and a caret under the error position. parse_with_recovery collects multiple errors, rendered one after the other:

    ///|
    test "error display" {
    match parse("name = \"John\"\nage thirty") {
    Err(e) => {
    let out = e.to_display_string()
    assert_true(out.contains("--> line 2"))
    assert_true(out.contains("age thirty"))
    assert_true(out.contains("^"))
    }
    Ok(_) => panic()
    }
    }

    #HCL Syntax Support

    # Attributes name = "John" count = 1 + 2 * 3 status = count > 10 ? "high" : "low" # Blocks with labels resource "aws_instance" "example" { ami = "ami-123456" instance_type = "t2.micro" } # Objects and Arrays config = { host = "localhost", port = 8080 } items = ["one", "two", "three"] # Heredoc script = <<EOF #!/bin/bash echo "Hello" EOF # For expressions names = [for item in items: item.name] # Splat all_names = items.*.name

    #API Reference

    CategoryFunctions
    Parseparse(String) -> HCLResult[Body], parse_with_recovery(String) -> (Body?, Array[HCLError])
    Serializeto_hcl_body(Body) -> String, to_hcl_value(HCLValue) -> String, format_body(Body) -> String, format_body_with_decor(Body) -> String, encode_attr/encode_opt_attr(String, ...) -> Attr?, encode_block/encode_blocks(String, Array[String], ...) -> HCLResult[Block/Array[Block]]
    Deserializefrom_hcl_body(String) -> HCLResult[Body], from_hcl_with_schema(Body, FieldSchema) -> HCLResult[...], from_hcl_with_body_schema(Body, BodySchema) -> HCLResult[ExtractedBody], decode_attr/decode_opt_attr/decode_block/decode_opt_block/decode_blocks(Body, ...) -> HCLResult[...]
    JSONhcl_to_json(String) -> String, body_to_json(Body) -> String, body_to_json_pretty(Body) -> String, json_to_body(String) -> HCLResult[Body]
    Evaleval_expr(Expression, Map[String, HCLValue], Map[String, FuncDef]) -> HCLResult[HCLValue], eval_expr_with_funcs(Expression, Map[String, HCLValue], Map[String, FuncDef]) -> HCLResult[HCLValue], simplify_body(Body) -> Body, builtin_functions() -> Map[String, FuncDef], merge_funcs(Map[...], Map[...]) -> Map[...]
    SchemaTypeSchema, FieldSchema, BodySchema, Validator, from_hcl_with_schema
    TypesTypeName enum, unify_types(TypeName, TypeName) -> HCLResult[TypeName], convert_value(HCLValue, TypeName) -> HCLResult[HCLValue]
    Static analysiscollect_variables(Body) -> Array[String], collect_functions(Body) -> Array[String], collect_traversals(Body) -> Array[String]
    IdentIdent::new(String) -> HCLResult[Ident] (validates XID_Start/XID_Continue)
    SpanSpan struct, Spanned[T] wrapper with start/end line+column
    FuncDefFuncDefBuilder for defining functions with typed params, variadic, OneOf
    FuncRegistryFuncRegistry::new(), with_builtins(), register(name, def), merge(other), build()
    DecorDecor, Decorated[T], format_body_with_decor, format_attr_with_decor
    VisitVisit trait (immutable), VisitMut trait (mutable)

    #License

    Apache-2.0 License

    ExprObject

    type ExprObject = Array[(ObjectKey, Expression)]

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

    test {
    let pairs : ExprObject = [(ObjectKey::Identifier("a"), expr_int(1))]
    assert_eq(expr_to_string(Expression::ExprObject(pairs)), "{ a = 1 }")
    }

    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).

    test {
    let o : HCLObject = { "a": hcl_int(1) }
    assert_eq(o["a"].as_int().unwrap(), 1)
    }

    HCLResult

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

    test {
    let r : HCLResult[Int] = Ok(42)
    assert_eq(r.unwrap(), 42)
    let e : HCLResult[Int] = Err(HCLError::missing_field("x"))
    assert_true(e is Err(_))
    }

    Validator

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

    Custom validator function type

    test {
    let v : Validator = fn(value, _path) {
    match value.as_string() {
    Some("") => [HCLError::validation_error("", "must not be empty")]
    _ => []
    }
    }
    assert_eq(v(hcl_str(""), "name").length(), 1)
    }

    FromHCL

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

    Trait for converting HCLValue to MoonBit types

    test {
    let r : HCLResult[Map[String, Int]] = from_hcl_str("a = 1")
    assert_eq(r.unwrap()["a"], 1)
    }
    impl FromHCL for Bool
    impl FromHCL for Int
    impl FromHCL for Int64
    impl FromHCL for Double
    impl FromHCL for String
    impl FromHCL for Option[T]
    impl FromHCL for Array[T]
    impl FromHCL for Map[String, T]

    ToHCL

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

    Trait for converting MoonBit types to HCLValue

    test {
    assert_eq(to_hcl_str(42), "42")
    assert_eq(to_hcl_str("hi"), "\"hi\"")
    }
    impl ToHCL for Bool
    impl ToHCL for Int
    impl ToHCL for Int64
    impl ToHCL for Double
    impl ToHCL for String
    impl ToHCL for Option[T]
    impl ToHCL for Array[T]
    impl ToHCL for Map[String, T]

    Visit

    pub(open) trait Visit {
    fn visit_body(Self, Body) -> Unit
    fn visit_body_item(Self, BodyItem) -> Unit
    fn visit_attr(Self, Attr) -> Unit
    fn visit_block(Self, Block) -> Unit
    fn visit_value(Self, HCLValue) -> Unit
    fn visit_expr(Self, Expression) -> Unit
    fn visit_object_key(Self, ObjectKey) -> Unit
    fn visit_traversal(Self, Traversal) -> Unit
    fn visit_traversal_operator(Self, TraversalOperator) -> Unit
    fn visit_func_call(Self, FuncCall) -> Unit
    fn visit_conditional(Self, Conditional) -> Unit
    fn visit_operation(Self, Operation) -> Unit
    fn visit_binary_op(Self, BinaryOp) -> Unit
    fn visit_unary_op(Self, UnaryOp) -> Unit
    fn visit_for_expr(Self, ForExpr) -> Unit
    fn visit_template_expr(Self, TemplateExpr) -> Unit
    fn visit_heredoc(Self, Heredoc) -> Unit
    fn 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 {
    fn visit_body_mut(Self, Body) -> Unit
    fn visit_body_item_mut(Self, BodyItem) -> Unit
    fn visit_attr_mut(Self, Attr) -> Unit
    fn visit_block_mut(Self, Block) -> Unit
    fn visit_value_mut(Self, HCLValue) -> Unit
    fn visit_expr_mut(Self, Expression) -> Unit
    fn visit_object_key_mut(Self, ObjectKey) -> Unit
    fn visit_traversal_mut(Self, Traversal) -> Unit
    fn visit_traversal_operator_mut(Self, TraversalOperator) -> Unit
    fn visit_func_call_mut(Self, FuncCall) -> Unit
    fn visit_conditional_mut(Self, Conditional) -> Unit
    fn visit_operation_mut(Self, Operation) -> Unit
    fn visit_binary_op_mut(Self, BinaryOp) -> Unit
    fn visit_unary_op_mut(Self, UnaryOp) -> Unit
    fn visit_for_expr_mut(Self, ForExpr) -> Unit
    fn visit_template_expr_mut(Self, TemplateExpr) -> Unit
    fn visit_heredoc_mut(Self, Heredoc) -> Unit
    fn 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

    test {
    let a = Attr::new("port", expr_int(80))
    assert_eq(a.get_key(), "port")
    }

    Attr::get_decor

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

    Get attribute decoration

    test {
    assert_eq(Attr::new("x", expr_int(1)).get_decor(), Decor::empty())
    }

    Attr::get_decorated_key

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

    Get attribute key with decoration

    test {
    let a = Attr::new("x", expr_int(1))
    assert_eq(a.get_decorated_key().get_value(), "x")
    }

    Attr::get_key

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

    Get attribute key

    test {
    assert_eq(Attr::new("x", expr_int(1)).get_key(), "x")
    }

    Attr::get_spanned_value

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

    Get attribute spanned value

    test {
    let a = Attr::new("x", expr_int(1))
    assert_eq(expr_to_string(a.get_spanned_value().unwrap()), "1")
    }

    Attr::get_value

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

    Get attribute value

    test {
    let a = Attr::new("x", expr_int(1))
    assert_eq(expr_to_string(a.get_value()), "1")
    }

    Attr::new

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

    Create a new attribute with decoration

    test {
    let a = Attr::new("port", expr_int(80))
    assert_eq(a.get_key(), "port")
    assert_eq(expr_to_string(a.get_value()), "80")
    }

    Attr::set_span

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

    Set span on attribute value

    test {
    let a = Attr::new("x", expr_int(1)).set_span(Span::new(1, 1, 0, 1, 2, 1))
    assert_true(a.get_spanned_value().get_span() is Some(_))
    }

    Attr::with_decor

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

    Create a new attribute with full decoration

    test {
    let a = Attr::with_decor(
    Decorated::bare("x"),
    Spanned::bare(expr_int(1)),
    Decor::empty(),
    )
    assert_eq(a.get_key(), "x")
    }

    AttrSchema

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

    Schema for a body attribute

    test {
    let a = AttrSchema::required(TypeSchema::int())
    let s = BodySchema::new().with_attrs({ "x": a })
    assert_true(extract_body(parse("x = 1").unwrap(), s) is Ok(_))
    }

    AttrSchema::optional

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

    Create an optional AttrSchema

    test {
    let s = BodySchema::new().with_attrs({
    "x": AttrSchema::optional(TypeSchema::int()),
    })
    assert_true(extract_body(Body::new(), s) is Ok(_))
    }

    AttrSchema::required

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

    Create a required AttrSchema

    test {
    let s = BodySchema::new().with_attrs({
    "x": AttrSchema::required(TypeSchema::int()),
    })
    assert_true(extract_body(Body::new(), s) is Err(_))
    }

    BinaryOp

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

    Binary operation

    test {
    let e = parse("v = 1 + 2").unwrap().find_attr("v").unwrap().get_value()
    match e {
    Expression::ExprOperation(Operation::Binary(b)) =>
    assert_eq(b.op, BinaryOperator::Plus)
    _ => panic()
    }
    }

    BinaryOperator

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

    Binary operator

    test {
    let e = parse("v = 1 * 2").unwrap().find_attr("v").unwrap().get_value()
    match e {
    Expression::ExprOperation(Operation::Binary(b)) =>
    assert_eq(b.op, BinaryOperator::Mul)
    _ => panic()
    }
    }

    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

    test {
    let blk = Block::simple("server", Body::new())
    assert_eq(blk.get_type_name(), "server")
    }

    Block::builder

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

    Create a new BlockBuilder

    test {
    let b = Block::builder("resource")
    let blk = b.build()
    assert_eq(blk.get_type_name(), "resource")
    }

    Block::find_attr

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

    Find an attribute in block body

    test {
    let blk = Block::simple("server", Body::new().add_attr("port", expr_int(80)))
    assert_eq(blk.find_attr("port").unwrap().get_key(), "port")
    }

    Block::get_body

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

    Get block body

    test {
    let blk = Block::simple("server", Body::new().add_attr("x", expr_int(1)))
    assert_eq(blk.get_body().len(), 1)
    }

    Block::get_decor

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

    Get block decoration

    test {
    assert_eq(Block::simple("server", Body::new()).get_decor(), Decor::empty())
    }

    Block::get_decorated_labels

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

    Get block labels with decoration

    test {
    let blk = Block::new("server", ["web"], Body::new())
    assert_eq(blk.get_decorated_labels().length(), 1)
    assert_eq(blk.get_decorated_labels()[0].get_value(), "web")
    }

    Block::get_decorated_type_name

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

    Get block type name with decoration

    test {
    let blk = Block::simple("server", Body::new())
    assert_eq(blk.get_decorated_type_name().get_value(), "server")
    }

    Block::get_labels

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

    Get block labels

    test {
    let blk = Block::new("server", ["web", "prod"], Body::new())
    assert_eq(blk.get_labels(), ["web", "prod"])
    }

    Block::get_span

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

    Get block span

    test {
    assert_eq(Block::simple("server", Body::new()).get_span(), None)
    }

    Block::get_type_name

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

    Get block type name

    test {
    assert_eq(Block::simple("server", Body::new()).get_type_name(), "server")
    }

    Block::new

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

    Create a new block with decoration

    test {
    let blk = Block::new("server", ["web"], Body::new())
    assert_eq(blk.get_type_name(), "server")
    assert_eq(blk.get_labels(), ["web"])
    }

    Block::set_span

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

    Set span on block

    test {
    let blk = Block::simple("server", Body::new()).set_span(
    Span::new(1, 1, 0, 1, 2, 1),
    )
    assert_true(blk.get_span() is Some(_))
    }

    Block::simple

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

    Create a block without labels

    test {
    let blk = Block::simple("server", Body::new())
    assert_eq(blk.get_type_name(), "server")
    assert_eq(blk.get_labels().length(), 0)
    }

    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

    test {
    let blk = Block::with_decor(
    Decorated::bare("server"),
    [Decorated::bare("web")],
    Body::new(),
    Decor::empty(),
    )
    assert_eq(blk.get_type_name(), "server")
    }

    BlockBuilder

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

    Builder for constructing Block incrementally

    test {
    let blk = Block::builder("server")
    .label("web")
    .attr("port", expr_int(80))
    .build()
    assert_eq(blk.get_type_name(), "server")
    assert_eq(blk.get_labels(), ["web"])
    }

    BlockBuilder::attr

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

    Add an attribute with Expression

    test {
    let blk = Block::builder("server").attr("port", expr_int(80)).build()
    assert_eq(blk.find_attr("port").unwrap().get_key(), "port")
    }

    BlockBuilder::attr_hcl

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

    Add an attribute from ToHCL value

    test {
    let blk = Block::builder("server").attr_hcl("port", 8080).build()
    assert_eq(expr_to_string(blk.find_attr("port").unwrap().get_value()), "8080")
    }

    BlockBuilder::attr_if

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

    Add an attribute conditionally

    test {
    let blk = Block::builder("server")
    .attr_if("a", expr_int(1), true)
    .attr_if("b", expr_int(2), false)
    .build()
    assert_eq(blk.get_body().len(), 1)
    }

    BlockBuilder::body

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

    Set the body from an existing Body

    test {
    let inner = Body::builder().attr("x", expr_int(1)).build()
    let blk = Block::builder("server").body(inner).build()
    assert_eq(blk.get_body().len(), 1)
    }

    BlockBuilder::build

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

    Build the Block

    test {
    let blk = Block::builder("server").label("web").build()
    assert_eq(blk.get_type_name(), "server")
    assert_eq(blk.get_labels().length(), 1)
    }

    BlockBuilder::label

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

    Add a label

    test {
    let blk = Block::builder("server").label("web").label("prod").build()
    assert_eq(blk.get_labels(), ["web", "prod"])
    }

    BlockSchema

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

    Schema for a body block

    test {
    let bs = BlockSchema::new(BodySchema::new())
    let s = BodySchema::new().with_blocks({ "server": bs })
    assert_true(extract_body(parse("server {}\n").unwrap(), s) is Ok(_))
    }

    BlockSchema::mark_required

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

    Mark an existing block schema as required

    test {
    let bs = BlockSchema::new(BodySchema::new()).mark_required()
    let s = BodySchema::new().with_blocks({ "server": bs })
    assert_true(extract_body(Body::new(), s) is Err(_))
    }

    BlockSchema::new

    Create a new BlockSchema

    test {
    let bs = BlockSchema::new(
    BodySchema::new().with_attrs({
    "port": AttrSchema::required(TypeSchema::int()),
    }),
    )
    let s = BodySchema::new().with_blocks({ "server": bs })
    assert_true(
    extract_body(parse("server {\n port = 80\n}\n").unwrap(), s) is Ok(_),
    )
    }

    BlockSchema::with_labels

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

    Set labels for block

    test {
    let bs = BlockSchema::new(BodySchema::new()).with_labels([
    LabelSchema::required(),
    ])
    let s = BodySchema::new().with_blocks({ "server": bs })
    assert_true(extract_body(parse("server \"web\" {}\n").unwrap(), s) is Ok(_))
    }

    BlockSchema::with_max_items

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

    Set max items for block

    test {
    let bs = BlockSchema::new(BodySchema::new()).with_max_items(1)
    let s = BodySchema::new().with_blocks({ "server": bs })
    assert_true(
    extract_body(parse("server {}\nserver {}\n").unwrap(), s) is Err(_),
    )
    }

    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

    test {
    let b = Body::new().add_attr("x", expr_int(1))
    assert_eq(b.len(), 1)
    }

    Body::add_attr

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

    Add an attribute to the body (returns new body)

    test {
    let b = Body::new().add_attr("x", expr_int(1))
    assert_eq(b.find_attr("x").unwrap().get_key(), "x")
    }

    Body::add_block

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

    Add a block to the body (returns new body)

    test {
    let b = Body::new().add_block(Block::simple("server", Body::new()))
    assert_eq(b.find_block("server").unwrap().get_type_name(), "server")
    }

    Body::builder

    fn Body::builder() -> BodyBuilder

    Create a new BodyBuilder

    test {
    let b = Body::builder()
    assert_eq(b.build().len(), 0)
    }

    Body::find_attr

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

    Find an attribute by key

    test {
    let b = Body::new().add_attr("x", expr_int(1))
    assert_eq(expr_to_string(b.find_attr("x").unwrap().get_value()), "1")
    }

    Body::find_block

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

    Find first block of a given type

    test {
    let b = Body::new().add_block(Block::simple("server", Body::new()))
    assert_true(b.find_block("server") is Some(_))
    assert_eq(b.find_block("other"), None)
    }

    Body::find_blocks

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

    Find all blocks of a given type

    test {
    let b = Body::new().add_block(Block::simple("server", Body::new()))
    assert_eq(b.find_blocks("server").length(), 1)
    assert_eq(b.find_blocks("other").length(), 0)
    }

    Body::from_items

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

    Create a Body from items with decoration

    test {
    let b = Body::from_items([BodyItem::Attribute(Attr::new("x", expr_int(1)))])
    assert_eq(b.len(), 1)
    }

    Body::get_decor

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

    Get body decoration

    test {
    let b = Body::new()
    assert_eq(b.get_decor(), Decor::empty())
    }

    Body::get_items

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

    Get the items of the body

    test {
    let b = Body::new().add_attr("x", expr_int(1))
    assert_eq(b.get_items().length(), 1)
    }

    Body::get_span

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

    Get body span

    test {
    assert_eq(Body::new().get_span(), None)
    }

    Body::is_empty

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

    Check if body is empty

    test {
    assert_eq(Body::new().is_empty(), true)
    assert_eq(Body::new().add_attr("x", expr_int(1)).is_empty(), false)
    }

    Body::len

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

    Get the number of items in the body

    test {
    let b = Body::new().add_attr("x", expr_int(1))
    assert_eq(b.len(), 1)
    }

    Body::new

    fn Body::new() -> Body

    Create a new empty Body with decoration

    test {
    let b = Body::new()
    assert_eq(b.len(), 0)
    assert_true(b.is_empty())
    }

    Body::set_span

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

    Set span on body

    test {
    let b = Body::new().set_span(Span::new(1, 1, 0, 1, 2, 1))
    assert_eq(b.get_span().unwrap(), Span::new(1, 1, 0, 1, 2, 1))
    }

    Body::with_decor

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

    Create a Body with full decoration

    test {
    let b = Body::with_decor(
    [BodyItem::Attribute(Attr::new("x", expr_int(1)))],
    Decor::empty(),
    )
    assert_eq(b.len(), 1)
    }

    BodyBuilder

    pub struct BodyBuilder {
    items : Array[BodyItem]
    }

    Builder for constructing Body incrementally

    test {
    let b = Body::builder().attr("x", expr_int(1)).build()
    assert_eq(b.len(), 1)
    }

    BodyBuilder::attr

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

    Add an attribute with Expression

    test {
    let b = Body::builder().attr("x", expr_int(1)).build()
    assert_eq(b.find_attr("x").unwrap().get_key(), "x")
    }

    BodyBuilder::attr_hcl

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

    Add an attribute from ToHCL value

    test {
    let b = Body::builder().attr_hcl("port", 8080).build()
    assert_eq(expr_to_string(b.find_attr("port").unwrap().get_value()), "8080")
    }

    BodyBuilder::attr_if

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

    Add an attribute conditionally

    test {
    let b = Body::builder()
    .attr_if("a", expr_int(1), true)
    .attr_if("b", expr_int(2), false)
    .build()
    assert_eq(b.len(), 1)
    }

    BodyBuilder::attr_option

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

    Add an attribute from Option (skip if None)

    test {
    let some : Int? = Some(5)
    let none : Int? = None
    let b = Body::builder().attr_option("a", some).attr_option("b", none).build()
    assert_eq(b.len(), 1)
    }

    BodyBuilder::block

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

    Add a block

    test {
    let blk = Block::builder("server").build()
    let b = Body::builder().block(blk).build()
    assert_eq(b.find_block("server").unwrap().get_type_name(), "server")
    }

    BodyBuilder::build

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

    Build the Body

    test {
    let b = Body::builder().attr("x", expr_int(1)).build()
    assert_eq(b.len(), 1)
    }

    BodyItem

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

    Body item can be either an attribute or a block

    test {
    let it = BodyItem::Attribute(Attr::new("x", expr_int(1)))
    let b = Body::from_items([it])
    assert_eq(b.len(), 1)
    }

    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

    test {
    let s = BodySchema::new()
    assert_eq(extract_body(Body::new(), s).unwrap().get_attr("x"), None)
    }

    BodySchema::new

    fn BodySchema::new() -> BodySchema

    Create an empty BodySchema

    test {
    let s = BodySchema::new()
    assert_true(extract_body(Body::new(), s) is Ok(_))
    }

    BodySchema::with_attrs

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

    Set attribute schemas on a BodySchema

    test {
    let s = BodySchema::new().with_attrs({
    "name": AttrSchema::required(TypeSchema::string()),
    })
    let r = extract_body(parse("name = \"x\"").unwrap(), s)
    assert_eq(r.unwrap().get_attr("name").unwrap().as_string().unwrap(), "x")
    }

    BodySchema::with_blocks

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

    Set block schemas on a BodySchema

    test {
    let s = BodySchema::new().with_blocks({
    "server": BlockSchema::new(BodySchema::new()),
    })
    let r = extract_body(parse("server {}\n").unwrap(), s)
    assert_eq(r.unwrap().get_blocks("server").length(), 1)
    }

    Conditional

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

    Conditional expression (cond ? true_expr : false_expr)

    test {
    let e = parse("v = c ? 1 : 2").unwrap().find_attr("v").unwrap().get_value()
    match e {
    Expression::ExprConditional(_) => ()
    _ => panic()
    }
    }

    Decor

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

    Whitespace and comment decorators, stores prefix and suffix

    test {
    let d = Decor::new(Some("# "), Some(" #"))
    assert_eq(d.get_prefix(), Some("# "))
    assert_eq(d.get_suffix(), Some(" #"))
    }

    Decor::clear

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

    Clear decorations

    test {
    let d = Decor::new(Some("#"), Some("#")).clear()
    assert_eq(d, Decor::empty())
    }

    Decor::empty

    fn Decor::empty() -> Decor

    Create empty Decor

    test {
    assert_eq(Decor::empty(), Decor::new(None, None))
    }

    Decor::get_prefix

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

    Get prefix

    test {
    assert_eq(Decor::empty().get_prefix(), None)
    assert_eq(Decor::new(Some("x"), None).get_prefix(), Some("x"))
    }

    Decor::get_suffix

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

    Get suffix

    test {
    assert_eq(Decor::empty().get_suffix(), None)
    assert_eq(Decor::new(None, Some("y")).get_suffix(), Some("y"))
    }

    Decor::new

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

    Create new Decor

    test {
    let d = Decor::new(Some(" "), Some(" "))
    assert_eq(d.get_prefix(), Some(" "))
    assert_eq(d.get_suffix(), Some(" "))
    }

    Decor::set_prefix

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

    Set prefix

    test {
    let d = Decor::empty().set_prefix(" ")
    assert_eq(d.get_prefix(), Some(" "))
    assert_eq(d.get_suffix(), None)
    }

    Decor::set_suffix

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

    Set suffix

    test {
    let d = Decor::empty().set_suffix("\n")
    assert_eq(d.get_suffix(), Some("\n"))
    }

    Decorated

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

    Value with decorations

    test {
    let v = Decorated::new(42, Decor::new(Some(" "), Some(" ")))
    assert_eq(v.get_value(), 42)
    }

    Decorated::bare

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

    Create value with empty decor

    test {
    let v = Decorated::bare(7)
    assert_eq(v.get_value(), 7)
    assert_eq(v.get_decor(), Decor::empty())
    }

    Decorated::expr

    Create a bare decorated expression (no decor)

    test {
    let de = Decorated::expr(expr_str("hi"))
    assert_eq(expr_to_string(de.get_expr()), "\"hi\"")
    }

    Decorated::expr_with_decor

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

    Create a decorated expression with decor

    test {
    let de = Decorated::expr_with_decor(
    expr_str("hi"),
    Decor::new(Some(" /* c */ "), None),
    )
    assert_eq(decorated_expr_to_string(de), " /* c */ \"hi\"")
    }

    Decorated::get_decor

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

    Get decor

    test {
    let d = Decor::new(Some("#"), None)
    assert_eq(Decorated::new(1, d).get_decor(), d)
    }

    Decorated::get_expr

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

    Extract the inner expression

    test {
    let de = Decorated::expr(expr_int(7))
    assert_eq(expr_to_string(de.get_expr()), "7")
    }

    Decorated::get_value

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

    Get value

    test {
    assert_eq(Decorated::bare(1).get_value(), 1)
    }

    Decorated::new

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

    Create decorated value

    test {
    let v = Decorated::new("x", Decor::empty())
    assert_eq(v.get_value(), "x")
    assert_eq(v.get_decor(), Decor::empty())
    }

    Decorated::set_decor

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

    Set decor

    test {
    let v = Decorated::bare(1).set_decor(Decor::new(Some(" "), None))
    assert_eq(v.get_decor().get_prefix(), Some(" "))
    }

    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

    test {
    assert_eq(expr_to_string(expr_int(1)), "1")
    assert_eq(expr_to_string(expr_array([expr_int(1), expr_int(2)])), "[1, 2]")
    }

    ExtractedBlock

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

    A single extracted block with its labels and nested body

    test {
    let e = extract_body(
    parse("server \"web\" {}\n").unwrap(),
    BodySchema::new().with_blocks({
    "server": BlockSchema::new(BodySchema::new()).with_labels([
    LabelSchema::required(),
    ]),
    }),
    ).unwrap()
    assert_eq(e.get_blocks("server")[0].get_label(0), Some("web"))
    }

    ExtractedBlock::get_label

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

    Get a label by index from a block

    test {
    let e = extract_body(
    parse("server \"web\" \"prod\" {}\n").unwrap(),
    BodySchema::new().with_blocks({
    "server": BlockSchema::new(BodySchema::new()).with_labels([
    LabelSchema::required(),
    LabelSchema::required(),
    ]),
    }),
    ).unwrap()
    assert_eq(e.get_blocks("server")[0].get_label(0), Some("web"))
    assert_eq(e.get_blocks("server")[0].get_label(1), Some("prod"))
    }

    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

    test {
    let r = extract_body(
    parse("name = \"x\"\n").unwrap(),
    BodySchema::new().with_attrs({
    "name": AttrSchema::required(TypeSchema::string()),
    }),
    ).unwrap()
    assert_eq(r.get_attr("name").unwrap().as_string().unwrap(), "x")
    }

    ExtractedBody::get_attr

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

    Get an attribute value by key

    test {
    let e = extract_body(
    parse("a = 1\n").unwrap(),
    BodySchema::new().with_attrs({
    "a": AttrSchema::required(TypeSchema::int()),
    }),
    ).unwrap()
    assert_eq(e.get_attr("a").unwrap().as_int().unwrap(), 1)
    }

    ExtractedBody::get_block

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

    Get the first block of a given type name

    test {
    let e = extract_body(
    parse("server {}\n").unwrap(),
    BodySchema::new().with_blocks({
    "server": BlockSchema::new(BodySchema::new()),
    }),
    ).unwrap()
    assert_true(e.get_block("server") is Some(_))
    assert_eq(e.get_block("other"), None)
    }

    ExtractedBody::get_blocks

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

    Get all blocks of a given type name

    test {
    let e = extract_body(
    parse("server {}\nserver {}\n").unwrap(),
    BodySchema::new().with_blocks({
    "server": BlockSchema::new(BodySchema::new()),
    }),
    ).unwrap()
    assert_eq(e.get_blocks("server").length(), 2)
    }

    ExtractedBody::get_extra_blocks

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

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

    test {
    let e = extract_body(
    parse("server {}\n").unwrap(),
    BodySchema::new().with_blocks({
    "server": BlockSchema::new(BodySchema::new()),
    }),
    ).unwrap()
    assert_eq(e.get_extra_blocks().length(), 0)
    }

    ExtractedBody::new

    Create an empty ExtractedBody

    test {
    let e = ExtractedBody::new()
    assert_eq(e.get_attr("x"), None)
    assert_eq(e.get_blocks("x").length(), 0)
    }

    FieldSchema

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

    Schema for an object field

    test {
    let f = FieldSchema::required(TypeSchema::int())
    let s = TypeSchema::object({ "age": f })
    assert_true(is_valid(hcl_object({ "age": hcl_int(1) }), s))
    }

    FieldSchema::optional

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

    Create an optional field schema

    test {
    let f = FieldSchema::optional(TypeSchema::int())
    assert_eq(is_valid(hcl_object({}), TypeSchema::object({ "age": f })), true)
    }

    FieldSchema::required

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

    Create a required field schema

    test {
    let f = FieldSchema::required(TypeSchema::int())
    assert_eq(is_valid(hcl_object({}), TypeSchema::object({ "age": f })), false)
    }

    FieldSchema::with_description

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

    Create a field schema with description

    test {
    let f = FieldSchema::optional(TypeSchema::int()).with_description(
    "age in years",
    )
    let s = TypeSchema::object({ "age": f })
    assert_true(is_valid(hcl_object({ "age": hcl_int(1) }), s))
    }

    FieldSchemaEx

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

    Extended field schema with custom validators

    test {
    let fx = FieldSchemaEx::new(FieldSchema::required(TypeSchema::string()))
    assert_eq(
    validate_ex(hcl_object({ "name": hcl_str("x") }), { "name": fx }).length(),
    0,
    )
    }

    FieldSchemaEx::add_validator

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

    Add validator to field schema

    test {
    let fx = FieldSchemaEx::new(FieldSchema::required(TypeSchema::string())).add_validator(
    string_not_empty(),
    )
    assert_eq(
    validate_ex(hcl_object({ "name": hcl_str("") }), { "name": fx }).length(),
    1,
    )
    }

    FieldSchemaEx::new

    Create extended field schema

    test {
    let fx = FieldSchemaEx::new(FieldSchema::required(TypeSchema::int()))
    assert_eq(
    validate_ex(hcl_object({ "age": hcl_int(1) }), { "age": fx }).length(),
    0,
    )
    }

    ForExpr

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

    For expression (list/object comprehension)

    test {
    let e = parse("v = [for x in xs : x]")
    .unwrap()
    .find_attr("v")
    .unwrap()
    .get_value()
    match e {
    Expression::ExprFor(ForExpr::List(_)) => ()
    _ => panic()
    }
    }

    ForListExpr

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

    List comprehension

    test {
    let e = parse("v = [for x in xs : x]")
    .unwrap()
    .find_attr("v")
    .unwrap()
    .get_value()
    match e {
    Expression::ExprFor(ForExpr::List(l)) => assert_eq(l.var_name, "x")
    _ => panic()
    }
    }

    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

    test {
    let e = parse("v = {for k, v in m : k => v}")
    .unwrap()
    .find_attr("v")
    .unwrap()
    .get_value()
    match e {
    Expression::ExprFor(ForExpr::Object(o)) => assert_eq(o.key_var, "k")
    _ => panic()
    }
    }

    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

    test {
    let c = FormatConfig::default()
    assert_eq(c.indent, " ")
    assert_eq(c.dense, false)
    }

    FormatConfig::compact

    fn FormatConfig::compact() -> FormatConfig

    Create compact FormatConfig (inline arrays/objects)

    test {
    let c = FormatConfig::compact()
    assert_eq(c.dense, true)
    assert_eq(c.compact_arrays, true)
    assert_eq(c.prefer_ident_keys, true)
    }

    FormatConfig::default

    fn FormatConfig::default() -> FormatConfig

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

    test {
    let c = FormatConfig::default()
    assert_eq(c.indent, " ")
    assert_eq(c.compact_arrays, false)
    }

    FormatConfig::dense

    fn FormatConfig::dense() -> FormatConfig

    Create dense FormatConfig (no empty lines between blocks)

    test {
    let c = FormatConfig::dense()
    assert_eq(c.dense, true)
    assert_eq(c.compact_arrays, false)
    }

    Formatter

    pub struct Formatter {
    config : FormatConfig
    }

    Formatter for HCL output with configuration

    test {
    let fmt = Formatter::new()
    assert_eq(fmt.format_value(hcl_int(1)), "1")
    }

    Formatter::format_body

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

    Format Body using formatter config

    test {
    let fmt = Formatter::new().set_prefer_ident_keys(true)
    let body = parse("a = 1").unwrap()
    assert_eq(fmt.format_body(body), "a = 1")
    }

    Formatter::format_value

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

    Format HCLValue using formatter config

    test {
    let fmt = Formatter::new().set_compact_arrays(true)
    assert_eq(fmt.format_value(hcl_array([hcl_int(1), hcl_int(2)])), "[1, 2]")
    }

    Formatter::get_config

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

    Get the formatter config

    test {
    let fmt = Formatter::new()
    assert_eq(fmt.get_config().indent, " ")
    }

    Formatter::new

    fn Formatter::new() -> Formatter

    Create Formatter with default config

    test {
    let fmt = Formatter::new()
    assert_eq(fmt.get_config().indent, " ")
    }

    Formatter::set_compact_arrays

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

    Set compact arrays mode

    test {
    let fmt = Formatter::new().set_compact_arrays(true)
    assert_eq(fmt.get_config().compact_arrays, true)
    }

    Formatter::set_compact_objects

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

    Set compact objects mode

    test {
    let fmt = Formatter::new().set_compact_objects(true)
    assert_eq(fmt.get_config().compact_objects, true)
    }

    Formatter::set_dense

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

    Set dense mode

    test {
    let fmt = Formatter::new().set_dense(true)
    assert_eq(fmt.get_config().dense, true)
    }

    Formatter::set_indent

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

    Set indent string

    test {
    let fmt = Formatter::new().set_indent(" ")
    assert_eq(fmt.get_config().indent, " ")
    }

    Formatter::set_prefer_ident_keys

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

    Set prefer ident keys mode

    test {
    let fmt = Formatter::new().set_prefer_ident_keys(true)
    assert_eq(fmt.get_config().prefer_ident_keys, true)
    }

    Formatter::with_config

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

    Create Formatter with given config

    test {
    let fmt = Formatter::with_config(FormatConfig::compact())
    assert_eq(fmt.get_config().dense, true)
    }

    FuncCall

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

    Function call

    test {
    let fc = FuncCallBuilder::new("upper").arg(expr_str("x")).build()
    assert_eq(expr_to_string(Expression::ExprFuncCall(fc)), "upper(\"x\")")
    }

    FuncCall::builder

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

    Create a FuncCallBuilder for this function name

    test {
    let fc = FuncCall::builder("len").arg(expr_str("x")).build()
    assert_eq(expr_to_string(Expression::ExprFuncCall(fc)), "len(\"x\")")
    }

    FuncCallBuilder

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

    Builder for constructing FuncCall expressions incrementally

    test {
    let fc = FuncCallBuilder::new("max").arg(expr_int(1)).build()
    assert_eq(expr_to_string(Expression::ExprFuncCall(fc)), "max(1)")
    }

    FuncCallBuilder::arg

    Add an argument expression

    test {
    let fc = FuncCallBuilder::new("max").arg(expr_int(1)).arg(expr_int(2)).build()
    assert_eq(expr_to_string(Expression::ExprFuncCall(fc)), "max(1, 2)")
    }

    FuncCallBuilder::build

    Build the FuncCall expression

    test {
    let fc = FuncCallBuilder::new("min").arg(expr_int(1)).build()
    assert_eq(fc.name, "min")
    }

    FuncCallBuilder::new

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

    Create a new FuncCallBuilder with a function name

    test {
    let b = FuncCallBuilder::new("max")
    assert_eq(expr_to_string(Expression::ExprFuncCall(b.build())), "max()")
    }

    FuncDef

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

    Function definition with parameter specifications

    test {
    let fd = FuncDef::builder()
    .param(ParamType::ParamString)
    .build("echo", fn(args) { Ok(args[0]) })
    assert_eq(fd.call([hcl_str("hi")]).unwrap().as_string().unwrap(), "hi")
    }

    FuncDef::builder

    fn FuncDef::builder() -> FuncDefBuilder

    Create a FuncDefBuilder

    test {
    let b = FuncDef::builder()
    let fd = b
    .param(ParamType::ParamNumber)
    .build("abs", fn(args) { Ok(args[0]) })
    assert_true(fd.call([hcl_int(-5)]) is Ok(_))
    }

    FuncDef::call

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

    Call function with argument validation

    test {
    let fd = FuncDef::builder()
    .param(ParamType::ParamNumber)
    .build("abs", fn(args) { Ok(args[0]) })
    assert_eq(fd.call([hcl_int(5)]).unwrap().as_int().unwrap(), 5)
    assert_true(fd.call([hcl_str("x")]) is Err(_))
    }

    FuncDefBuilder

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

    Builder for FuncDef

    test {
    let fd = FuncDefBuilder::new()
    .param(ParamType::ParamString)
    .variadic(ParamType::ParamString)
    .build("f", fn(args) { Ok(hcl_int(args.length())) })
    assert_eq(fd.call([hcl_str("a"), hcl_str("b")]).unwrap().as_int().unwrap(), 2)
    }

    FuncDefBuilder::build

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

    Build FuncDef with name and function body

    test {
    let fd = FuncDefBuilder::new()
    .param(ParamType::ParamNumber)
    .build("negate", fn(args) { Ok(hcl_int(-args[0].as_int().unwrap())) })
    assert_eq(fd.call([hcl_int(3)]).unwrap().as_int().unwrap(), -3)
    }

    FuncDefBuilder::new

    Create new FuncDefBuilder

    test {
    let b = FuncDefBuilder::new()
    let fd = b.build("noop", fn(_args) { Ok(hcl_null()) })
    assert_true(fd.call([]) is Ok(_))
    }

    FuncDefBuilder::param

    Add a positional parameter

    test {
    let fd = FuncDefBuilder::new()
    .param(ParamType::ParamNumber)
    .build("f", fn(args) { Ok(args[0]) })
    assert_true(fd.call([hcl_int(1)]) is Ok(_))
    assert_true(fd.call([hcl_str("x")]) is Err(_))
    }

    FuncDefBuilder::variadic

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

    Set variadic parameter type

    test {
    let fd = FuncDefBuilder::new()
    .param(ParamType::ParamString)
    .variadic(ParamType::ParamNumber)
    .build("f", fn(args) { Ok(hcl_int(args.length())) })
    assert_eq(
    fd.call([hcl_str("a"), hcl_int(1), hcl_int(2)]).unwrap().as_int().unwrap(),
    3,
    )
    }

    FuncRegistry

    pub struct FuncRegistry {
    funcs : Map[String, FuncDef]
    }

    Registry for managing custom and builtin functions

    test {
    let reg = FuncRegistry::with_builtins()
    let f = reg.build()
    assert_true(f.contains("upper"))
    }

    FuncRegistry::build

    fn FuncRegistry::build(self : FuncRegistry) -> Map[String, FuncDef]

    Build and return the final Map[String, FuncDef]

    test {
    let reg = FuncRegistry::new()
    assert_eq(reg.build().length(), 0)
    }

    FuncRegistry::merge

    fn FuncRegistry::merge(self : FuncRegistry, other : Map[String, FuncDef]) -> FuncRegistry

    Merge another Map[String, FuncDef] into this registry

    test {
    let fd = FuncDef::builder().build("custom", fn(_args) { Ok(hcl_null()) })
    let extra : Map[String, FuncDef] = { "custom": fd }
    let reg = FuncRegistry::new().merge(extra)
    assert_true(reg.build().contains("custom"))
    }

    FuncRegistry::new

    Create an empty FuncRegistry

    test {
    let reg = FuncRegistry::new()
    assert_eq(reg.build().length(), 0)
    }

    FuncRegistry::register

    fn FuncRegistry::register(self : FuncRegistry, name : String, def : FuncDef) -> FuncRegistry

    Register a single function definition (fluent API, returns self)

    test {
    let fd = FuncDef::builder().build("greet", fn(_args) { Ok(hcl_str("hello")) })
    let reg = FuncRegistry::new().register("greet", fd)
    assert_true(reg.build().contains("greet"))
    }

    FuncRegistry::with_builtins

    fn FuncRegistry::with_builtins() -> FuncRegistry

    Create a FuncRegistry pre-loaded with all builtin functions

    test {
    let reg = FuncRegistry::with_builtins()
    let f = reg.build()
    assert_true(f.contains("abs"))
    assert_true(f.contains("lower"))
    }

    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)
    MultipleErrors(Array[HCLError])
    } derive(Eq,
    Debug
    )

    HCL Error types

    test {
    let e = HCLError::type_mismatch("Int", "string")
    assert_eq(e.message(), "Type error: expected Int, got string")
    }

    HCLError::division_by_zero

    fn HCLError::division_by_zero() -> HCLError

    test {
    assert_eq(HCLError::division_by_zero().message(), "Division by zero")
    }

    HCLError::encoding_error

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

    test {
    assert_eq(HCLError::encoding_error("e").message(), "Encoding error: e")
    }

    HCLError::invalid_value

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

    test {
    assert_eq(HCLError::invalid_value("bad").message(), "Invalid value: bad")
    }

    HCLError::io_error

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

    test {
    assert_eq(HCLError::io_error("disk").message(), "IO error: disk")
    }

    HCLError::message

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

    test {
    assert_eq(HCLError::missing_field("port").message(), "Missing field: port")
    assert_eq(HCLError::division_by_zero().message(), "Division by zero")
    }

    HCLError::missing_field

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

    test {
    assert_eq(HCLError::missing_field("name").message(), "Missing field: name")
    }

    HCLError::multi

    fn HCLError::multi(errors : Array[HCLError]) -> HCLError

    test {
    let e = HCLError::multi([
    HCLError::type_mismatch("Int", "string"),
    HCLError::missing_field("x"),
    ])
    assert_eq(
    e.message(),
    "Type error: expected Int, got string\nMissing field: x",
    )
    }

    HCLError::parse_error

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

    test {
    let e = HCLError::parse_error("boom", 1, 5, 4)
    assert_eq(e.message(), "Parse error at line 1, column 5: boom")
    }

    HCLError::parse_error_with_context

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

    test {
    let e = HCLError::parse_error_with_context("boom", 1, 2, 1, "x =")
    assert_true(e.message().contains("x ="))
    }

    HCLError::to_display_string

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

    Render this error as a miette-style human-readable report: an error: header, a --> line N, col M location, the offending source line with a caret under the error position, and — for MultipleErrors — one such report per sub-error, separated by a blank line.

    error: Expected '=', got '}' --> line 1, col 12 | 1 | resource x { | ^

    Parse errors render the full report; errors without a source line (type errors, validation errors, ...) render as a single error: header line. An empty MultipleErrors renders the empty string.

    test {
    let err = HCLError::parse_error_with_context(
    "Expected '=', got '}'", 1, 12, 11, "resource x {",
    )
    let out = err.to_display_string()
    assert_true(out.contains("--> line 1, col 12"))
    assert_true(out.contains("resource x {"))
    assert_true(out.contains("^"))
    }

    HCLError::to_string

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

    Render this error as a human-readable report (same output as [to_display_string]). Use this whenever an HCLError needs to be shown to a user.

    test {
    let err = HCLError::type_error("boom")
    assert_eq(err.to_string(), "error: Type error: expected type error, got boom")
    }

    HCLError::type_error

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

    test {
    let e = HCLError::type_error("boom")
    assert_eq(e.message(), "Type error: expected type error, got boom")
    }

    HCLError::type_mismatch

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

    test {
    let e = HCLError::type_mismatch("Int", "string")
    assert_eq(e.message(), "Type error: expected Int, got string")
    }

    HCLError::undefined_function

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

    test {
    assert_eq(
    HCLError::undefined_function("f").message(),
    "Undefined function: f",
    )
    }

    HCLError::undefined_property

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

    test {
    assert_eq(
    HCLError::undefined_property("p").message(),
    "Undefined property: p",
    )
    }

    HCLError::undefined_variable

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

    test {
    assert_eq(
    HCLError::undefined_variable("x").message(),
    "Undefined variable: x",
    )
    }

    HCLError::validation_error

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

    test {
    assert_eq(
    HCLError::validation_error("a.b", "bad").message(),
    "Validation error at a.b: bad",
    )
    }

    HCLObjectBuilder

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

    Builder for constructing HCLObject incrementally

    test {
    let o = HCLObjectBuilder::new().entry("a", hcl_int(1)).build()
    assert_eq(o["a"].as_int().unwrap(), 1)
    }

    HCLObjectBuilder::build

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

    Build the HCLObject

    test {
    let o = HCLObjectBuilder::new().entry("x", hcl_str("y")).build()
    assert_eq(o["x"].as_string().unwrap(), "y")
    }

    HCLObjectBuilder::entry

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

    Add a key-value pair

    test {
    let o = HCLObjectBuilder::new().entry("port", hcl_int(8080)).build()
    assert_eq(o["port"].as_int().unwrap(), 8080)
    }

    HCLObjectBuilder::entry_hcl

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

    Add a key-value pair from ToHCL value

    test {
    let o = HCLObjectBuilder::new().entry_hcl("count", 3).build()
    assert_eq(o["count"].as_int().unwrap(), 3)
    }

    HCLObjectBuilder::entry_if

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

    Add a key-value pair conditionally

    test {
    let o = HCLObjectBuilder::new()
    .entry_if("a", hcl_int(1), true)
    .entry_if("b", hcl_int(2), false)
    .build()
    assert_true(o.contains("a"))
    assert_eq(o.contains("b"), false)
    }

    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)

    test {
    let some : Int? = Some(5)
    let none : Int? = None
    let o = HCLObjectBuilder::new()
    .entry_option("a", some)
    .entry_option("b", none)
    .build()
    assert_true(o.contains("a"))
    assert_eq(o.contains("b"), false)
    }

    HCLObjectBuilder::extend_with

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

    Add all entries from another HCLObject

    test {
    let o = HCLObjectBuilder::new()
    .extend_with(hcl_object_from_pairs([("a", hcl_int(1))]))
    .build()
    assert_eq(o["a"].as_int().unwrap(), 1)
    }

    HCLObjectBuilder::new

    Create a new HCLObjectBuilder

    test {
    let b = HCLObjectBuilder::new()
    assert_eq(b.build().is_empty(), true)
    }

    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

    test {
    let v = HCLValue::int(42)
    assert_true(v.is_number())
    assert_eq(v.as_int().unwrap(), 42)
    }
    impl FromHCL for HCLValue
    impl ToHCL for HCLValue

    HCLValue::array

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

    Create array value with empty decor

    test {
    let a = HCLValue::array([hcl_int(1)])
    assert_eq(a.as_array().unwrap().length(), 1)
    }

    HCLValue::as_array

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

    Get the array value, or None if not an array

    test {
    let a = HCLValue::array([hcl_int(1), hcl_int(2)])
    assert_eq(a.as_array().unwrap().length(), 2)
    }

    HCLValue::as_bool

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

    Get the boolean value, or None if not a bool

    test {
    assert_eq(HCLValue::bool(true).as_bool().unwrap(), true)
    assert_eq(HCLValue::int(1).as_bool(), None)
    }

    HCLValue::as_float

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

    Get the float value, or None if not a number

    test {
    assert_eq(HCLValue::float(1.5).as_float().unwrap(), 1.5)
    }

    HCLValue::as_int

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

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

    test {
    assert_eq(HCLValue::int(42).as_int().unwrap(), 42)
    assert_eq(HCLValue::string("x").as_int(), None)
    }

    HCLValue::as_int64

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

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

    test {
    assert_eq(HCLValue::int64(7L).as_int64().unwrap(), 7L)
    }

    HCLValue::as_number

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

    Get the Number value, or None if not a number

    test {
    assert_eq(HCLValue::int(1).as_number().unwrap().as_int().unwrap(), 1)
    match HCLValue::bool(true).as_number() {
    None => ()
    Some(_) => panic()
    }
    }

    HCLValue::as_object

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

    Get the object value, or None if not an object

    test {
    let o = HCLValue::object({ "a": hcl_int(1) })
    assert_eq(o.as_object().unwrap()["a"].as_int().unwrap(), 1)
    }

    HCLValue::as_string

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

    Get the string value, or None if not a string

    test {
    assert_eq(HCLValue::string("hi").as_string().unwrap(), "hi")
    assert_eq(HCLValue::int(1).as_string(), None)
    }

    HCLValue::bool

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

    Create bool value with empty decor

    test {
    assert_eq(HCLValue::bool(false).as_bool().unwrap(), false)
    }

    HCLValue::float

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

    Create float value with empty decor

    test {
    assert_eq(HCLValue::float(2.5).as_float().unwrap(), 2.5)
    }

    HCLValue::get_decor

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

    Get decoration from HCLValue

    test {
    let v = HCLValue::string("x")
    assert_eq(v.get_decor(), Decor::empty())
    }

    HCLValue::int

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

    Create int value with empty decor

    test {
    assert_eq(HCLValue::int(7).as_int().unwrap(), 7)
    }

    HCLValue::int64

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

    Create int64 value with empty decor

    test {
    assert_eq(HCLValue::int64(7L).as_int64().unwrap(), 7L)
    }

    HCLValue::is_array

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

    Check if value is an array

    test {
    assert_eq(HCLValue::array([hcl_int(1)]).is_array(), true)
    }

    HCLValue::is_bool

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

    Check if value is a boolean

    test {
    assert_eq(HCLValue::bool(true).is_bool(), true)
    assert_eq(HCLValue::int(1).is_bool(), false)
    }

    HCLValue::is_null

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

    Check if value is null

    test {
    assert_eq(HCLValue::null().is_null(), true)
    assert_eq(HCLValue::int(1).is_null(), false)
    }

    HCLValue::is_number

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

    Check if value is a number

    test {
    assert_eq(HCLValue::int(1).is_number(), true)
    assert_eq(HCLValue::string("x").is_number(), false)
    }

    HCLValue::is_object

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

    Check if value is an object

    test {
    assert_eq(HCLValue::object({ "a": hcl_int(1) }).is_object(), true)
    }

    HCLValue::is_string

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

    Check if value is a string

    test {
    assert_eq(HCLValue::string("x").is_string(), true)
    }

    HCLValue::is_unknown

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

    Check if value is unknown (Terraform plan-stage)

    test {
    assert_eq(HCLValue::unknown().is_unknown(), true)
    assert_eq(HCLValue::int(1).is_unknown(), false)
    }

    HCLValue::null

    fn HCLValue::null() -> HCLValue

    Create null value with empty decor

    test {
    assert_true(HCLValue::null().is_null())
    }

    HCLValue::object

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

    Create object value with empty decor

    test {
    let o = HCLValue::object({ "k": hcl_str("v") })
    assert_eq(o.as_object().unwrap()["k"].as_string().unwrap(), "v")
    }

    HCLValue::set_decor

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

    Set decoration on HCLValue

    test {
    let v = HCLValue::int(1).set_decor(Decor::new(Some(" "), None))
    assert_eq(v.get_decor().get_prefix(), Some(" "))
    }

    HCLValue::string

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

    Create string value with empty decor

    test {
    assert_eq(HCLValue::string("hi").as_string().unwrap(), "hi")
    }

    HCLValue::to_json_string

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

    Convert HCLValue to JSON-compatible string representation

    test {
    assert_eq(HCLValue::int(42).to_json_string(), "42")
    assert_eq(HCLValue::string("hi").to_json_string(), "\"hi\"")
    assert_eq(HCLValue::bool(true).to_json_string(), "true")
    }

    HCLValue::type_name

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

    Get type name as string

    test {
    assert_eq(HCLValue::int(1).type_name(), "number")
    assert_eq(HCLValue::string("x").type_name(), "string")
    }

    HCLValue::unknown

    fn HCLValue::unknown() -> HCLValue

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

    test {
    assert_true(HCLValue::unknown().is_unknown())
    }

    Heredoc

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

    Heredoc template

    test {
    let h : Heredoc = {
    delimiter: "EOT",
    content: "hi\n",
    strip_mode: HeredocStripMode::NoStrip,
    }
    assert_eq(h.delimiter, "EOT")
    assert_eq(h.content, "hi\n")
    }

    HeredocStripMode

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

    Heredoc strip mode

    test {
    let h : Heredoc = {
    delimiter: "EOT",
    content: " hi\n",
    strip_mode: HeredocStripMode::StripMode,
    }
    assert_eq(h.strip_mode, HeredocStripMode::StripMode)
    let h2 : Heredoc = {
    delimiter: "EOT",
    content: "hi\n",
    strip_mode: HeredocStripMode::NoStrip,
    }
    assert_eq(h2.strip_mode, HeredocStripMode::NoStrip)
    }

    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

    test {
    let id = Ident::new("name")
    assert_eq(id.as_str(), "name")
    assert_eq(id.len(), 4)
    }

    Ident::as_str

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

    Get the identifier as a string reference.

    test {
    assert_eq(Ident::new("x").as_str(), "x")
    }

    Ident::hash

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

    Implement hash for Ident (delegates to inner string)

    test {
    assert_eq(Ident::new("a").hash(), Ident::new("a").hash())
    }

    Ident::into_string

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

    Consume the Ident and return the inner String.

    test {
    assert_eq(Ident::new("x").into_string(), "x")
    }

    Ident::is_empty

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

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

    test {
    assert_eq(Ident::new("x").is_empty(), false)
    assert_eq(Ident::new_unchecked("").is_empty(), true)
    }

    Ident::len

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

    Get the length of the identifier.

    test {
    assert_eq(Ident::new("abcd").len(), 4)
    }

    Ident::new

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

    Create a new Ident after validating.

    Panics if the identifier is empty or contains invalid characters.

    test {
    let id = Ident::new("server")
    assert_eq(id.as_str(), "server")
    }

    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 "_"

    test {
    assert_eq(Ident::new_sanitized("my name").as_str(), "my_name")
    assert_eq(Ident::new_sanitized("").as_str(), "_")
    }

    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.

    test {
    let id = Ident::new_unchecked("anything")
    assert_eq(id.as_str(), "anything")
    }

    Ident::output

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

    Implement Display for Ident (output the raw string)

    test {
    assert_eq(Ident::new("x").output(), "x")
    }

    Ident::to_string

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

    Debug representation

    test {
    assert_eq(Ident::new("foo").to_string(), "Ident(foo)")
    }

    Ident::try_new

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

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

    test {
    assert_eq(Ident::try_new("ok_name").unwrap().as_str(), "ok_name")
    assert_true(Ident::try_new("bad name") is Err(_))
    }

    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

    test {
    match JsonValue::JsonString("x") {
    JsonValue::JsonString(s) => assert_eq(s, "x")
    _ => panic()
    }
    }

    LabelSchema

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

    Schema for a block label

    test {
    let ls = LabelSchema::required()
    let bs = BlockSchema::new(BodySchema::new()).with_labels([ls])
    let s = BodySchema::new().with_blocks({ "server": bs })
    assert_true(extract_body(parse("server \"web\" {}\n").unwrap(), s) is Ok(_))
    }

    LabelSchema::optional

    fn LabelSchema::optional() -> LabelSchema

    Create an optional LabelSchema

    test {
    let bs = BlockSchema::new(BodySchema::new()).with_labels([
    LabelSchema::optional(),
    ])
    let s = BodySchema::new().with_blocks({ "server": bs })
    assert_true(extract_body(parse("server {}\n").unwrap(), s) is Ok(_))
    }

    LabelSchema::required

    fn LabelSchema::required() -> LabelSchema

    Create a required LabelSchema

    test {
    let bs = BlockSchema::new(BodySchema::new()).with_labels([
    LabelSchema::required(),
    ])
    let s = BodySchema::new().with_blocks({ "server": bs })
    assert_true(extract_body(parse("server {}\n").unwrap(), s) is Err(_))
    }

    Lexer

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

    HCL Lexer - tokenizes HCL input

    test {
    let lx = Lexer::new("a = 1")
    assert_eq(lx.tokenize().unwrap().length(), 4)
    }

    Lexer::collect_comment

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

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

    test {
    let (_, cm) = Lexer::new("// hi\nx").collect_comment()
    assert_eq(cm, Some("// hi"))
    }

    Lexer::collect_whitespace

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

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

    test {
    let (_, ws) = Lexer::new(" x").collect_whitespace()
    assert_eq(ws, Some(" "))
    }

    Lexer::get_line

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

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

    test {
    let lx = Lexer::new("a = 1")
    assert_eq(lx.get_line(1), "a = 1")
    }

    Lexer::location

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

    Get current position info

    test {
    let lx = Lexer::new("a = 1")
    let (_, _, offset) = lx.location()
    assert_eq(offset, 0)
    }

    Lexer::new

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

    Create a new lexer from string input

    test {
    let lx = Lexer::new("a = 1")
    let (t, _) = lx.next_token().unwrap()
    assert_eq(t, Token::Ident("a"))
    }

    Lexer::next_token

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

    Get the next token

    test {
    let (t, lx2) = Lexer::new("a").next_token().unwrap()
    assert_eq(t, Token::Ident("a"))
    let (t2, _) = lx2.next_token().unwrap()
    assert_eq(t2, Token::EOF)
    }

    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)

    test {
    let (t, _, tr) = Lexer::new("a").next_token_with_trivia().unwrap()
    assert_eq(t, Token::Ident("a"))
    assert_eq(tr, None)
    }

    Lexer::tokenize

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

    Tokenize entire input

    test {
    let toks = Lexer::new("a = 1").tokenize().unwrap()
    assert_eq(toks.length(), 4)
    assert_eq(toks[0], Token::Ident("a"))
    assert_eq(toks[3], Token::EOF)
    }

    Lexer::validate_input

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

    Validate input encoding (no BOM allowed)

    test {
    assert_true(Lexer::validate_input("a = 1") is Ok(_))
    assert_true(Lexer::validate_input("\u{FEFF}hello") is Err(_))
    }
    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.

    test {
    assert_true(Number::from_int(5).is_pos_int())
    assert_true(Number::from_int(-5).is_neg_int())
    assert_true(Number::from_double(1.5).is_float())
    }

    Number

    pub struct Number {
    n : N
    }

    test {
    let n = Number::from_int(42)
    assert_eq(n.as_int().unwrap(), 42)
    }

    Number::as_f64

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

    Get Number value as f64 (always succeeds)

    test {
    assert_eq(Number::from_int(3).as_f64(), 3.0)
    }

    Number::as_float

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

    Get Number value as Double (alias for as_f64)

    test {
    assert_eq(Number::from_int(3).as_float(), 3.0)
    }

    Number::as_i64

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

    If Number is an integer, return as Int64

    test {
    assert_eq(Number::from_int64(7L).as_i64().unwrap(), 7L)
    assert_eq(Number::from_double(1.5).as_i64(), None)
    }

    Number::as_int

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

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

    test {
    assert_eq(Number::from_int(42).as_int().unwrap(), 42)
    assert_eq(Number::from_double(1.5).as_int(), None)
    }

    Number::as_int64

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

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

    test {
    assert_eq(Number::from_int(7).as_int64().unwrap(), 7L)
    }

    Number::as_u64

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

    If Number is a positive integer, return as UInt64

    test {
    assert_eq(Number::from_uint64(7UL).as_u64().unwrap(), 7UL)
    assert_eq(Number::from_int(-1).as_u64(), None)
    }

    Number::from_double

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

    Create Number from Double

    test {
    assert_eq(Number::from_double(3.5).as_float(), 3.5)
    assert_eq(Number::from_double(42.0).as_int().unwrap(), 42)
    }

    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.

    test {
    assert_eq(Number::from_f64(1.5).unwrap().as_float(), 1.5)
    let nan = 0.0 / 0.0
    match Number::from_f64(nan) {
    None => ()
    Some(_) => panic()
    }
    }

    Number::from_finite_f64

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

    Create a Number from f64, assumes finite

    test {
    assert_eq(Number::from_finite_f64(2.0).as_int().unwrap(), 2)
    }

    Number::from_int

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

    Create Number from Int

    test {
    assert_eq(Number::from_int(-5).as_int().unwrap(), -5)
    }

    Number::from_int64

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

    Create Number from Int64

    test {
    assert_eq(Number::from_int64(-5L).as_int64().unwrap(), -5L)
    }

    Number::from_uint64

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

    Create Number from UInt64

    test {
    assert_eq(Number::from_uint64(5UL).as_u64().unwrap(), 5UL)
    }

    Number::is_f64

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

    Check if Number is a float

    test {
    assert_eq(Number::from_double(1.5).is_f64(), true)
    assert_eq(Number::from_int(1).is_f64(), false)
    }

    Number::is_float

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

    Check if Number is a float (alias for is_f64)

    test {
    assert_eq(Number::from_double(1.5).is_float(), true)
    }

    Number::is_int

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

    Check if Number is any integer (PosInt or NegInt)

    test {
    assert_eq(Number::from_int(5).is_int(), true)
    assert_eq(Number::from_double(1.5).is_int(), false)
    }

    Number::is_int64

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

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

    test {
    assert_eq(Number::from_int64(-5L).is_int64(), true)
    assert_eq(Number::from_int(5).is_int64(), false)
    }

    Number::is_neg_int

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

    Check if Number is a negative integer

    test {
    assert_eq(Number::from_int(-5).is_neg_int(), true)
    assert_eq(Number::from_int(5).is_neg_int(), false)
    }

    Number::is_pos_int

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

    Check if Number is a positive integer

    test {
    assert_eq(Number::from_int(5).is_pos_int(), true)
    assert_eq(Number::from_int(-5).is_pos_int(), false)
    }

    ObjectKey

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

    Object key type - can be identifier or expression

    test {
    assert_eq(ObjectKey::Identifier("x").to_string(), "x")
    assert_eq(ObjectKey::Expression(expr_int(1)).to_string(), "1")
    }

    ObjectKey::to_string

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

    Convert ObjectKey to string representation

    test {
    assert_eq(ObjectKey::Identifier("x").to_string(), "x")
    assert_eq(ObjectKey::Expression(expr_int(2)).to_string(), "2")
    }

    Operation

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

    Operation (binary or unary)

    test {
    let e = parse("v = 1 + 2").unwrap().find_attr("v").unwrap().get_value()
    match e {
    Expression::ExprOperation(Operation::Binary(_)) => ()
    _ => panic()
    }
    }

    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

    test {
    assert_eq(ParamType::ParamString.is_satisfied_by(hcl_str("x")), true)
    assert_eq(ParamType::ParamString.is_satisfied_by(hcl_int(1)), false)
    assert_eq(ParamType::Any.is_satisfied_by(hcl_int(1)), true)
    }

    ParamType::display_name

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

    Get display name for ParamType (for error messages)

    test {
    assert_eq(ParamType::ParamString.display_name(), "string")
    assert_eq(ParamType::ParamNumber.display_name(), "number")
    assert_eq(
    ParamType::Nullable(ParamType::ParamString).display_name(),
    "string?",
    )
    }

    ParamType::is_satisfied_by

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

    Check if a value satisfies this parameter type

    test {
    assert_eq(ParamType::ParamNumber.is_satisfied_by(hcl_int(1)), true)
    assert_eq(ParamType::ParamBool.is_satisfied_by(hcl_bool(true)), true)
    assert_eq(
    ParamType::ParamArray(ParamType::ParamNumber).is_satisfied_by(
    hcl_array([hcl_int(1)]),
    ),
    true,
    )
    }

    Parser

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

    HCL Parser - parses HCL input into structured data

    test {
    let p = Parser::new("a = 1").unwrap()
    assert_eq(p.parse_body().unwrap().len(), 1)
    }

    Parser::from_lexer

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

    Create a new parser from lexer

    test {
    let p = Parser::from_lexer(Lexer::new("x = 1")).unwrap()
    assert_eq(p.parse_body().unwrap().len(), 1)
    }

    Parser::new

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

    Create a new parser from string input

    test {
    let p = Parser::new("x = 1").unwrap()
    assert_eq(p.parse_body().unwrap().len(), 1)
    }

    Parser::parse_body

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

    Parse HCL input into a Body

    test {
    let p = Parser::new("x = 1").unwrap()
    assert_eq(p.parse_body().unwrap().len(), 1)
    }

    Parser::parse_body_with_recovery

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

    Parse HCL input into a Body with error recovery

    test {
    let p = Parser::new("x = 1").unwrap()
    let (r, errs) = p.parse_body_with_recovery()
    assert_true(r is Ok(_))
    assert_eq(errs.length(), 0)
    }

    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

    test {
    let s = Span::new(1, 2, 0, 1, 5, 4)
    assert_eq(s, Span::new(1, 2, 0, 1, 5, 4))
    }

    Span::empty

    fn Span::empty() -> Span

    Create an empty (zero) Span

    test {
    assert_eq(Span::empty(), Span::new(0, 0, 0, 0, 0, 0))
    }

    Span::merge

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

    Merge two spans: start from a, end from b

    test {
    let a = Span::new(1, 1, 0, 1, 3, 2)
    let b = Span::new(2, 1, 5, 2, 4, 8)
    let m = Span::merge(a, b)
    assert_eq(m.start_line, 1)
    assert_eq(m.end_line, 2)
    assert_eq(m.end_offset, 8)
    }

    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

    test {
    let s = Span::new(1, 1, 0, 2, 1, 10)
    assert_eq(s.end_line, 2)
    assert_eq(s.start_col, 1)
    }

    Spanned

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

    Value with optional source span

    test {
    let s : Spanned[Int] = Spanned::bare(42)
    assert_eq(s.unwrap(), 42)
    assert_eq(s.get_span(), None)
    }

    Spanned::bare

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

    Create a Spanned value without span

    test {
    let s = Spanned::bare("x")
    assert_eq(s.unwrap(), "x")
    assert_eq(s.get_span(), None)
    }

    Spanned::get_span

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

    Get the span

    test {
    assert_eq(Spanned::bare(7).get_span(), None)
    let s = Spanned::new(7, Span::new(1, 1, 0, 1, 2, 1))
    assert_eq(s.get_span().unwrap(), Span::new(1, 1, 0, 1, 2, 1))
    }

    Spanned::new

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

    Create a Spanned value with span

    test {
    let s = Spanned::new(42, Span::empty())
    assert_eq(s.unwrap(), 42)
    assert_true(s.get_span() is Some(_))
    }

    Spanned::unwrap

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

    Get the inner value

    test {
    assert_eq(Spanned::bare(7).unwrap(), 7)
    }

    Template

    pub struct Template {
    parts : Array[TemplatePart]
    }

    Template representation

    test {
    let t = Template::from_string("hello").unwrap()
    assert_eq(t.evaluate(Map([]), Map([])).unwrap(), "hello")
    }

    Template::evaluate

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

    Evaluate template with given context

    test {
    let t = Template::from_string("Hello, ${name}!").unwrap()
    let vars : Map[String, HCLValue] = { "name": hcl_str("Moon") }
    assert_eq(t.evaluate(vars, Map([])).unwrap(), "Hello, Moon!")
    }

    Template::from_heredoc

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

    Parse heredoc content

    test {
    let t = Template::from_heredoc("hello\n", "EOT", false).unwrap()
    assert_eq(t.evaluate(Map([]), Map([])).unwrap(), "hello\n")
    }

    Template::from_string

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

    Parse string with template expressions

    test {
    let t = Template::from_string("Hello, ${name}!").unwrap()
    let vars : Map[String, HCLValue] = { "name": hcl_str("World") }
    assert_eq(t.evaluate(vars, Map([])).unwrap(), "Hello, World!")
    }

    Template::new

    fn Template::new() -> Template

    Create new template

    test {
    let t = Template::new()
    assert_eq(t.evaluate(Map([]), Map([])).unwrap(), "")
    }

    TemplateExpr

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

    Template expression (heredoc or interpolated string)

    test {
    let h : Heredoc = {
    delimiter: "EOT",
    content: "hi\n",
    strip_mode: HeredocStripMode::NoStrip,
    }
    match TemplateExpr::Heredoc(h) {
    TemplateExpr::Heredoc(inner) => assert_eq(inner.content, "hi\n")
    _ => panic()
    }
    }

    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

    test {
    let t = parse_template("hello ${x}").unwrap()
    match t.parts[0] {
    TemplatePart::Text(s) => assert_eq(s, "hello ")
    _ => panic()
    }
    }

    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

    test {
    assert_eq(Token::Ident("x").is_literal(), true)
    assert_eq(Token::Equals.is_delimiter(), false)
    assert_eq(Token::Plus.precedence(), 5)
    }

    Token::is_delimiter

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

    test {
    assert_eq(Token::LBrace.is_delimiter(), true)
    assert_eq(Token::RParen.is_delimiter(), true)
    assert_eq(Token::Equals.is_delimiter(), false)
    }

    Token::is_literal

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

    test {
    assert_eq(Token::Ident("x").is_literal(), true)
    assert_eq(Token::NumberLit("42").is_literal(), true)
    assert_eq(Token::Equals.is_literal(), false)
    }

    Token::is_operator

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

    test {
    assert_eq(Token::Plus.is_operator(), true)
    assert_eq(Token::AndAnd.is_operator(), true)
    assert_eq(Token::Ident("x").is_operator(), false)
    }

    Token::precedence

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

    test {
    assert_eq(Token::OrOr.precedence(), 1)
    assert_eq(Token::Plus.precedence(), 5)
    assert_eq(Token::Star.precedence(), 6)
    assert_eq(Token::Equals.precedence(), 0)
    }

    Traversal

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

    Traversal (property/element access)

    test {
    let t = TraversalBuilder::new(expr_str("obj")).attr("key").build()
    assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"obj\".key")
    }

    Traversal::builder

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

    Create a TraversalBuilder starting from this Traversal

    test {
    let b = Traversal::builder(expr_str("o"))
    assert_eq(
    expr_to_string(Expression::ExprTraversal(b.attr("k").build())),
    "\"o\".k",
    )
    }

    TraversalBuilder

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

    Builder for constructing Traversal expressions incrementally

    test {
    let t = TraversalBuilder::new(expr_str("o")).attr("a").build()
    assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"o\".a")
    }

    TraversalBuilder::attr

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

    Add an attribute access operator (.attr)

    test {
    let t = TraversalBuilder::new(expr_str("o")).attr("a").attr("b").build()
    assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"o\".a.b")
    }

    TraversalBuilder::build

    Build the Traversal expression

    test {
    let t = TraversalBuilder::new(expr_str("o")).build()
    assert_true(Expression::ExprTraversal(t) is Expression::ExprTraversal(_))
    }

    TraversalBuilder::index

    Add an index access operator ([expr])

    test {
    let t = TraversalBuilder::new(expr_str("o")).index(expr_int(0)).build()
    assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"o\"[0]")
    }

    TraversalBuilder::new

    Create a new TraversalBuilder from a base expression

    test {
    let b = TraversalBuilder::new(expr_str("o"))
    assert_eq(expr_to_string(Expression::ExprTraversal(b.build())), "\"o\"")
    }

    TraversalBuilder::splat

    Add a splat access operator (.*)

    test {
    let t = TraversalBuilder::new(expr_str("o")).splat().attr("a").build()
    assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"o\".*.a")
    }

    TraversalOperator

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

    Traversal operator

    test {
    assert_eq(
    expr_to_string(
    Expression::ExprTraversal(
    TraversalBuilder::new(expr_str("o")).attr("a").build(),
    ),
    ),
    "\"o\".a",
    )
    }

    TypeName

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

    HCL type categories for unification

    test {
    assert_eq(type_of(hcl_int(42)), TypeName::TNumber)
    assert_eq(type_of(hcl_str("x")), TypeName::TString)
    }

    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

    test {
    assert_true(is_valid(hcl_int(42), TypeSchema::int()))
    assert_true(is_valid(hcl_str("x"), TypeSchema::string()))
    }

    TypeSchema::any

    fn TypeSchema::any() -> TypeSchema

    Schema for any value

    test {
    assert_true(is_valid(hcl_int(1), TypeSchema::any()))
    assert_true(is_valid(hcl_str("x"), TypeSchema::any()))
    }

    TypeSchema::array

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

    Schema for array

    test {
    let s = TypeSchema::array(TypeSchema::int())
    assert_true(is_valid(hcl_array([hcl_int(1), hcl_int(2)]), s))
    assert_eq(is_valid(hcl_array([hcl_str("x")]), s), false)
    }

    TypeSchema::bool

    fn TypeSchema::bool() -> TypeSchema

    Schema for boolean

    test {
    assert_true(is_valid(hcl_bool(true), TypeSchema::bool()))
    assert_eq(is_valid(hcl_int(1), TypeSchema::bool()), false)
    }

    TypeSchema::float

    fn TypeSchema::float() -> TypeSchema

    Schema for float

    test {
    assert_true(is_valid(hcl_float(1.5), TypeSchema::float()))
    assert_eq(is_valid(hcl_int(1), TypeSchema::float()), false)
    }

    TypeSchema::int

    fn TypeSchema::int() -> TypeSchema

    Schema for integer

    test {
    assert_true(is_valid(hcl_int(42), TypeSchema::int()))
    assert_eq(is_valid(hcl_str("x"), TypeSchema::int()), false)
    }

    TypeSchema::int64

    fn TypeSchema::int64() -> TypeSchema

    Schema for 64-bit integer

    test {
    assert_true(is_valid(hcl_int64(42L), TypeSchema::int64()))
    }

    TypeSchema::null

    fn TypeSchema::null() -> TypeSchema

    Schema for null

    test {
    assert_true(is_valid(hcl_null(), TypeSchema::null()))
    assert_eq(is_valid(hcl_int(1), TypeSchema::null()), false)
    }

    TypeSchema::number

    fn TypeSchema::number() -> TypeSchema

    Schema for number (int or float)

    test {
    assert_true(is_valid(hcl_int(1), TypeSchema::number()))
    assert_true(is_valid(hcl_float(1.5), TypeSchema::number()))
    assert_eq(is_valid(hcl_str("x"), TypeSchema::number()), false)
    }

    TypeSchema::object

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

    Schema for object

    test {
    let s = TypeSchema::object({
    "name": FieldSchema::required(TypeSchema::string()),
    })
    assert_true(is_valid(hcl_object({ "name": hcl_str("x") }), s))
    }

    TypeSchema::string

    fn TypeSchema::string() -> TypeSchema

    Schema for string

    test {
    assert_true(is_valid(hcl_str("x"), TypeSchema::string()))
    assert_eq(is_valid(hcl_int(1), TypeSchema::string()), false)
    }

    UnaryOp

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

    Unary operation

    test {
    let e = parse("v = -x").unwrap().find_attr("v").unwrap().get_value()
    match e {
    Expression::ExprOperation(Operation::Unary(u)) =>
    assert_eq(u.op, UnaryOperator::Negate)
    _ => panic()
    }
    }

    UnaryOperator

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

    Unary operator

    test {
    let e = parse("v = !x").unwrap().find_attr("v").unwrap().get_value()
    match e {
    Expression::ExprOperation(Operation::Unary(u)) =>
    assert_eq(u.op, UnaryOperator::Not)
    _ => panic()
    }
    }

    Variable

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

    Variable reference

    test {
    let e = parse("v = x").unwrap().find_attr("v").unwrap().get_value()
    match e {
    Expression::ExprVariable(_) => ()
    _ => panic()
    }
    }

    body_to_json

    fn body_to_json(body : Body) -> String

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

    test {
    let body = parse("name = \"foo\"").unwrap()
    assert_eq(body_to_json(body), "{\"name\":\"foo\"}")
    }

    body_to_json_pretty

    fn body_to_json_pretty(body : Body, indent? : Int) -> String

    Convert Body to JSON string with pretty printing

    test {
    let body = parse("name = \"foo\"").unwrap()
    assert_eq(body_to_json_pretty(body), "{\n \"name\": \"foo\"\n}")
    }

    builtin_functions

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

    Get all built-in functions

    test {
    let f = builtin_functions()
    assert_true(f.contains("abs"))
    assert_true(f.contains("upper"))
    assert_true(f.contains("length"))
    }

    collect_functions

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

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

    test {
    let body = parse("a = upper(\"x\")\nb = lower(\"y\")").unwrap()
    assert_eq(collect_functions(body), ["lower", "upper"])
    }

    collect_functions_from_expr

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

    Collect all unique function names from a single expression

    test {
    let e = parse("a = upper(x)").unwrap().find_attr("a").unwrap().get_value()
    assert_eq(collect_functions_from_expr(e), ["upper"])
    }

    collect_traversals

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

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

    test {
    let body = parse("a = obj.key1\nb = other.attr").unwrap()
    assert_eq(collect_traversals(body), ["obj", "other"])
    }

    collect_traversals_from_expr

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

    Collect all unique traversal root variable names from a single expression

    test {
    let e = parse("a = obj.key").unwrap().find_attr("a").unwrap().get_value()
    assert_eq(collect_traversals_from_expr(e), ["obj"])
    }

    collect_variables

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

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

    test {
    let body = parse("a = x\nb = y").unwrap()
    assert_eq(collect_variables(body), ["x", "y"])
    }

    collect_variables_from_expr

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

    Collect all unique variable names from a single expression

    test {
    let e = parse("a = x + y").unwrap().find_attr("a").unwrap().get_value()
    assert_eq(collect_variables_from_expr(e), ["x", "y"])
    }

    convert_value

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

    Convert a value to the target type per HCL conversion rules

    test {
    let r = convert_value(hcl_int(42), TypeName::TString)
    assert_eq(r.unwrap().as_string().unwrap(), "42")
    assert_eq(
    convert_value(hcl_int(42), TypeName::TNumber).unwrap().as_int().unwrap(),
    42,
    )
    }

    decode_attr

    fn[T : FromHCL] decode_attr(body : Body, key : String) -> Result[T, HCLError]

    Decode a required attribute from a Body into a typed value

    test {
    let body = parse("port = 8080").unwrap()
    let port : Int = decode_attr(body, "port").unwrap()
    assert_eq(port, 8080)
    }

    decode_block

    fn[T : FromHCL] decode_block(body : Body, type_name : String) -> Result[T, HCLError]

    Decode the body of a required block into a typed value

    test {
    let body = parse("server {\n port = 8080\n}").unwrap()
    let cfg : Map[String, Int] = decode_block(body, "server").unwrap()
    assert_eq(cfg["port"], 8080)
    }

    decode_blocks

    fn[T : FromHCL] decode_blocks(body : Body, type_name : String) -> Result[Array[T], HCLError]

    Decode every block of a type into an array of typed values

    test {
    let body = parse("server {\n port = 8080\n}\nserver {\n port = 3000\n}").unwrap()
    let cfgs : Array[Map[String, Int]] = decode_blocks(body, "server").unwrap()
    assert_eq(cfgs.length(), 2)
    assert_eq(cfgs[0]["port"], 8080)
    assert_eq(cfgs[1]["port"], 3000)
    }

    decode_opt_attr

    fn[T : FromHCL] decode_opt_attr(body : Body, key : String) -> Result[T?, HCLError]

    Decode an optional attribute from a Body (None when absent)

    test {
    let body = parse("port = 8080").unwrap()
    let port : Int? = decode_opt_attr(body, "port").unwrap()
    let missing : Int? = decode_opt_attr(body, "host").unwrap()
    assert_eq(port, Some(8080))
    assert_eq(missing, None)
    }

    decode_opt_block

    fn[T : FromHCL] decode_opt_block(body : Body, type_name : String) -> Result[T?, HCLError]

    Decode the body of an optional block (None when absent)

    test {
    let body = parse("server {\n port = 8080\n}").unwrap()
    let cfg : Map[String, Int]? = decode_opt_block(body, "server").unwrap()
    let missing : Map[String, Int]? = decode_opt_block(body, "db").unwrap()
    assert_true(cfg is Some(_))
    assert_eq(missing, None)
    }

    decorated_expr_to_string

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

    Convert Decorated[Expression] to string

    test {
    let de = Decorated::expr_with_decor(
    expr_str("hi"),
    Decor::new(Some("# "), Some(" #")),
    )
    assert_eq(decorated_expr_to_string(de), "# \"hi\" #")
    }

    encode_attr

    fn[T : ToHCL] encode_attr(key : String, value : T) -> Attr

    Encode a value as an HCL attribute (key = name)

    test {
    let attr = encode_attr("port", 8080)
    assert_eq(attr.get_key(), "port")
    assert_eq(expr_to_string(attr.get_value()), "8080")
    }

    encode_block

    fn[T : ToHCL] encode_block(type_name : String, labels : Array[String], value : T) -> Result[Block, HCLError]

    Encode a value as a labeled HCL block (value must encode to an object)

    test {
    let cfg = encode_block("server", ["web"], { "port": 8080 }).unwrap()
    assert_eq(cfg.get_type_name(), "server")
    assert_eq(cfg.get_labels(), ["web"])
    assert_eq(expr_to_string(cfg.find_attr("port").unwrap().get_value()), "8080")
    }

    encode_blocks

    fn[T : ToHCL] encode_blocks(type_name : String, labels : Array[String], values : Array[T]) -> Result[Array[Block], HCLError]

    Encode values as repeated labeled HCL blocks

    test {
    let cfgs = encode_blocks("server", ["web"], [
    { "port": 8080 },
    { "port": 3000 },
    ]).unwrap()
    assert_eq(cfgs.length(), 2)
    assert_eq(cfgs[0].get_labels(), ["web"])
    assert_eq(
    expr_to_string(cfgs[1].find_attr("port").unwrap().get_value()),
    "3000",
    )
    }

    encode_opt_attr

    fn[T : ToHCL] encode_opt_attr(key : String, value : T?) -> Attr?

    Encode an optional value as an attribute (None produces no attribute)

    test {
    let some : Int? = Some(8080)
    let none : Int? = None
    assert_eq(encode_opt_attr("port", some).unwrap().get_key(), "port")
    assert_eq(encode_opt_attr("port", none), None)
    }

    escape_hcl_string

    fn escape_hcl_string(s : String) -> String

    Escape a string for HCL

    test {
    assert_eq(escape_hcl_string("hello"), "\"hello\"")
    assert_eq(escape_hcl_string("a\"b"), "\"a\\\"b\"")
    assert_eq(escape_hcl_string("cost ${price}"), "\"cost $${price}\"")
    }

    eval_binary

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

    Evaluate binary operation on two HCLValues

    test {
    assert_eq(
    eval_binary(hcl_int(2), "+", hcl_int(3)).unwrap().as_int().unwrap(),
    5,
    )
    assert_eq(
    eval_binary(hcl_int(2), "*", hcl_int(3)).unwrap().as_int().unwrap(),
    6,
    )
    }

    eval_conditional

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

    Evaluate conditional expression (cond ? true : false)

    test {
    assert_eq(
    eval_conditional(hcl_bool(true), hcl_int(1), hcl_int(2))
    .unwrap()
    .as_int()
    .unwrap(),
    1,
    )
    assert_eq(
    eval_conditional(hcl_bool(false), hcl_int(1), hcl_int(2))
    .unwrap()
    .as_int()
    .unwrap(),
    2,
    )
    }

    eval_expr

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

    Evaluate expression (handles all expression types)

    test {
    let vars : Map[String, HCLValue] = { "x": hcl_int(10) }
    let e = parse("v = x + 5").unwrap().find_attr("v").unwrap().get_value()
    assert_eq(eval_expr(e, vars, Map([])).unwrap().as_int().unwrap(), 15)
    }

    eval_expr_simple

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

    Evaluate expression with default empty context

    test {
    assert_eq(eval_expr_simple(expr_int(42)).unwrap().as_int().unwrap(), 42)
    assert_eq(
    eval_expr_simple(expr_str("hi")).unwrap().as_string().unwrap(),
    "hi",
    )
    }

    eval_expr_with_funcs

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

    Evaluate expression with builtin functions merged with extra custom functions

    test {
    let vars : Map[String, HCLValue] = { "x": hcl_int(2) }
    let e = parse("v = upper(\"hi\")")
    .unwrap()
    .find_attr("v")
    .unwrap()
    .get_value()
    assert_eq(
    eval_expr_with_funcs(e, vars, Map([])).unwrap().as_string().unwrap(),
    "HI",
    )
    }

    eval_unary

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

    Evaluate unary operation on HCLValue

    test {
    assert_eq(eval_unary("-", hcl_int(5)).unwrap().as_int().unwrap(), -5)
    assert_eq(eval_unary("!", hcl_bool(true)).unwrap().as_bool().unwrap(), false)
    }

    evaluate_template

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

    Evaluate template string directly

    test {
    let vars : Map[String, HCLValue] = { "name": hcl_str("Moon") }
    assert_eq(
    evaluate_template("Hello, ${name}!", vars, Map([])).unwrap(),
    "Hello, Moon!",
    )
    }

    expr_array

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

    Create Expression array

    test {
    assert_eq(expr_to_string(expr_array([expr_int(1), expr_int(2)])), "[1, 2]")
    }

    expr_bool

    fn expr_bool(v : Bool) -> Expression

    Create Expression from Bool

    test {
    assert_eq(expr_to_string(expr_bool(true)), "true")
    }

    expr_func_call

    fn expr_func_call(fc : FuncCall) -> Expression

    Create Expression from FuncCall

    test {
    let fc = FuncCallBuilder::new("upper").arg(expr_str("x")).build()
    assert_eq(expr_to_string(expr_func_call(fc)), "upper(\"x\")")
    }

    expr_int

    fn expr_int(v : Int) -> Expression

    Create Expression from Int

    test {
    assert_eq(expr_to_string(expr_int(7)), "7")
    }

    expr_null

    fn expr_null() -> Expression

    Null Expression

    test {
    assert_eq(expr_to_string(expr_null()), "null")
    }

    expr_str

    fn expr_str(v : String) -> Expression

    Create Expression from String

    test {
    assert_eq(expr_to_string(expr_str("hi")), "\"hi\"")
    }

    expr_to_hcl_value

    fn expr_to_hcl_value(expr : Expression) -> HCLValue

    Convert Expression to HCLValue (bridge for serializers)

    test {
    assert_eq(expr_to_hcl_value(expr_int(1)).as_int().unwrap(), 1)
    assert_eq(expr_to_hcl_value(expr_str("x")).as_string().unwrap(), "x")
    }

    expr_to_string

    fn expr_to_string(expr : Expression) -> String

    Convert Expression to string representation

    test {
    assert_eq(expr_to_string(expr_int(42)), "42")
    assert_eq(expr_to_string(expr_str("hi")), "\"hi\"")
    }

    expr_unknown

    fn expr_unknown() -> Expression

    Unknown Expression (Terraform plan-stage)

    test {
    assert_eq(expr_to_string(expr_unknown()), "unknown")
    }

    extract_body

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

    Extract structured data from an HCL Body using a BodySchema

    test {
    let body = parse("name = \"test\"\ncount = 42\n").unwrap()
    let schema = BodySchema::new().with_attrs({
    "name": AttrSchema::required(TypeSchema::string()),
    "count": AttrSchema::required(TypeSchema::int()),
    })
    let extracted = extract_body(body, schema).unwrap()
    assert_eq(extracted.get_attr("name").unwrap().as_string().unwrap(), "test")
    assert_eq(extracted.get_attr("count").unwrap().as_int().unwrap(), 42)
    }

    format_attr_with_decor

    fn format_attr_with_decor(attr : Attr) -> String

    Format Attr with decor

    test {
    let a = Attr::new("x", expr_int(1))
    assert_eq(format_attr_with_decor(a), "x = 1")
    }

    format_body

    fn format_body(body : Body) -> String

    Format HCL Body to string

    test {
    let body = parse("a = 1").unwrap()
    assert_eq(format_body(body), "a = 1")
    }

    format_body_with_decor

    fn format_body_with_decor(body : Body) -> String

    Format Body with decor

    test {
    let body = parse("a = 1").unwrap()
    assert_eq(format_body_with_decor(body), "a = 1")
    }

    format_value_content

    fn format_value_content(value : HCLValue) -> String

    Format HCLValue content without decor

    test {
    assert_eq(format_value_content(hcl_str("hi")), "\"hi\"")
    assert_eq(format_value_content(hcl_null()), "null")
    }

    format_value_with_decor

    fn format_value_with_decor(value : HCLValue) -> String

    Format HCLValue with decor

    test {
    assert_eq(format_value_with_decor(hcl_int(1)), "1")
    }

    from_hcl_body

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

    Deserialize from HCL string to Body

    test {
    let body = from_hcl_body("x = 1").unwrap()
    assert_eq(body.len(), 1)
    }

    from_hcl_bool

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

    Deserialize from HCL string to Bool

    test {
    assert_eq(from_hcl_bool("x = true").unwrap(), true)
    }

    from_hcl_int

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

    Deserialize from HCL string to Int

    test {
    assert_eq(from_hcl_int("x = 42").unwrap(), 42)
    }

    from_hcl_str

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

    Parse HCL string to any FromHCL type

    test {
    let r : HCLResult[Map[String, Int]] = from_hcl_str("a = 1")
    assert_eq(r.unwrap()["a"], 1)
    }

    from_hcl_string

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

    Deserialize from HCL string to String

    test {
    assert_eq(from_hcl_string("x = \"hi\"").unwrap(), "hi")
    }

    from_hcl_value

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

    Deserialize from HCL string to HCLValue

    test {
    let v = from_hcl_value("x = 1").unwrap()
    assert_eq(v.as_object().unwrap()["x"].as_int().unwrap(), 1)
    }

    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

    test {
    let schema = BodySchema::new().with_attrs({
    "x": AttrSchema::required(TypeSchema::int()),
    })
    let r = from_hcl_with_body_schema("x = 42", schema)
    assert_true(r is Ok(_))
    assert_eq(r.unwrap().get_attr("x").unwrap().as_int().unwrap(), 42)
    }

    from_hcl_with_schema

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

    Deserialize HCL with schema validation

    test {
    let schema = TypeSchema::object({
    "x": FieldSchema::required(TypeSchema::int()),
    })
    assert_true(from_hcl_with_schema("x = 1", schema) is Ok(_))
    let bad = TypeSchema::object({
    "x": FieldSchema::required(TypeSchema::string()),
    })
    assert_true(from_hcl_with_schema("x = 1", bad) is Err(_))
    }

    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

    test {
    let schema = TypeSchema::object({
    "x": FieldSchema::required(TypeSchema::int()),
    })
    match from_hcl_with_schema_full("x = \"no\"", schema) {
    Err(errs) => assert_eq(errs.length(), 1)
    Ok(_) => panic()
    }
    }

    hcl_array

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

    Create Array HCLValue

    test {
    let a = hcl_array([hcl_int(1), hcl_int(2)])
    assert_eq(a.as_array().unwrap().length(), 2)
    }

    hcl_bool

    fn hcl_bool(v : Bool) -> HCLValue

    Create Bool HCLValue

    test {
    assert_eq(hcl_bool(true).as_bool().unwrap(), true)
    }

    hcl_float

    fn hcl_float(v : Double) -> HCLValue

    Create Float HCLValue

    test {
    assert_eq(hcl_float(1.5).as_float().unwrap(), 1.5)
    }

    hcl_int

    fn hcl_int(v : Int) -> HCLValue

    Create Int HCLValue

    test {
    assert_eq(hcl_int(42).as_int().unwrap(), 42)
    }

    hcl_int64

    fn hcl_int64(v : Int64) -> HCLValue

    Create Int64 HCLValue

    test {
    assert_eq(hcl_int64(7L).as_int64().unwrap(), 7L)
    }

    hcl_null

    fn hcl_null() -> HCLValue

    Create Null HCLValue

    test {
    assert_true(hcl_null().is_null())
    }

    hcl_object

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

    Create Object HCLValue

    test {
    let o = hcl_object({ "a": hcl_int(1) })
    assert_eq(o.as_object().unwrap()["a"].as_int().unwrap(), 1)
    }

    hcl_object_entries

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

    Get key-value pairs in insertion order

    test {
    let o = hcl_object_from_pairs([("a", hcl_int(1))])
    let es = hcl_object_entries(o)
    assert_eq(es.length(), 1)
    assert_eq(es[0].0, "a")
    }

    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)

    test {
    let a = hcl_object_from_pairs([("x", hcl_int(1))])
    let b = hcl_object_from_pairs([("y", hcl_int(2))])
    hcl_object_extend(a, b)
    assert_eq(a["y"].as_int().unwrap(), 2)
    }

    hcl_object_from_pairs

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

    Create HCLObject from array of key-value pairs

    test {
    let o = hcl_object_from_pairs([("a", hcl_int(1)), ("b", hcl_int(2))])
    assert_eq(o["a"].as_int().unwrap(), 1)
    assert_eq(o["b"].as_int().unwrap(), 2)
    }

    hcl_object_keys

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

    Get keys in insertion order

    test {
    let o = hcl_object_from_pairs([("a", hcl_int(1)), ("b", hcl_int(2))])
    assert_eq(hcl_object_keys(o), ["a", "b"])
    }

    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.

    test {
    let a = hcl_object_from_pairs([("x", hcl_int(1)), ("y", hcl_int(2))])
    let b = hcl_object_from_pairs([("y", hcl_int(3))])
    let m = hcl_object_merge(a, b)
    assert_eq(m["x"].as_int().unwrap(), 1)
    assert_eq(m["y"].as_int().unwrap(), 3)
    }

    hcl_object_values

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

    Get values in insertion order

    test {
    let o = hcl_object_from_pairs([("a", hcl_int(1)), ("b", hcl_int(2))])
    let vs = hcl_object_values(o)
    assert_eq(vs.length(), 2)
    assert_eq(vs[0].as_int().unwrap(), 1)
    }

    hcl_str

    fn hcl_str(v : String) -> HCLValue

    Create String HCLValue

    test {
    assert_eq(hcl_str("hi").as_string().unwrap(), "hi")
    }

    hcl_to_json

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

    Convert HCL string to JSON string

    test {
    assert_eq(hcl_to_json("a = 1").unwrap(), "{\"a\":1}")
    assert_eq(
    hcl_to_json("region = \"us-east-1\"").unwrap(),
    "{\"region\":\"us-east-1\"}",
    )
    }

    hcl_to_json_pretty

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

    Convert HCL string to JSON string with pretty printing

    test {
    assert_eq(hcl_to_json_pretty("a = 1").unwrap(), "{\n \"a\": 1\n}")
    }

    hcl_value_to_expression

    fn hcl_value_to_expression(value : HCLValue) -> Expression

    Convert HCLValue to Expression

    test {
    assert_eq(expr_to_string(hcl_value_to_expression(hcl_int(5))), "5")
    assert_eq(expr_to_string(hcl_value_to_expression(hcl_str("x"))), "\"x\"")
    }

    int_in_range

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

    Validator: int in range

    test {
    let v = int_in_range(0, 150)
    assert_eq(v(hcl_int(25), "age").length(), 0)
    assert_eq(v(hcl_int(200), "age").length(), 1)
    }

    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)

    test {
    assert_eq(is_id_continue('a'), true)
    assert_eq(is_id_continue('1'), true)
    assert_eq(is_id_continue('-'), true)
    assert_eq(is_id_continue(' '), false)
    }

    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.)

    test {
    assert_eq(is_id_start('a'), true)
    assert_eq(is_id_start('_'), true)
    assert_eq(is_id_start('1'), false)
    }

    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

    test {
    assert_eq(is_ident("server_name"), true)
    assert_eq(is_ident("1x"), false)
    assert_eq(is_ident(""), false)
    }

    is_valid

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

    Check if value is valid

    test {
    assert_eq(is_valid(hcl_int(1), TypeSchema::int()), true)
    assert_eq(is_valid(hcl_str("x"), TypeSchema::int()), false)
    }

    json_to_body

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

    Convert JSON string to HCL Body

    test {
    let body = json_to_body("{\"name\": \"John\", \"age\": 30}").unwrap()
    assert_eq(body.len(), 2)
    assert_eq(
    expr_to_string(body.find_attr("name").unwrap().get_value()),
    "\"John\"",
    )
    assert_eq(expr_to_string(body.find_attr("age").unwrap().get_value()), "30")
    }

    json_to_hcl_string

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

    Convert JSON string to HCL formatted string

    test {
    let out = json_to_hcl_string("{\"a\": 1}").unwrap()
    assert_eq(out, "a = 1")
    }

    merge_funcs

    fn merge_funcs(base : Map[String, FuncDef], extra : Map[String, FuncDef]) -> Map[String, FuncDef]

    Merge two function maps, extra overrides base on conflict

    test {
    let base = builtin_functions()
    let extra : Map[String, FuncDef] = Map([])
    let merged = merge_funcs(base, extra)
    assert_true(merged.contains("abs"))
    }

    new_hcl_object

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

    Create an empty HCLObject

    test {
    let o = new_hcl_object()
    assert_eq(o.is_empty(), true)
    }

    parse

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

    Parse HCL string into Body

    test {
    let body = parse("x = 1").unwrap()
    assert_eq(body.len(), 1)
    assert_eq(body.find_attr("x").unwrap().get_key(), "x")
    }

    parse_template

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

    Parse template from string (simple version)

    test {
    let t = parse_template("hi ${x}").unwrap()
    let vars : Map[String, HCLValue] = { "x": hcl_int(1) }
    assert_eq(t.evaluate(vars, Map([])).unwrap(), "hi 1")
    }

    parse_with_recovery

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

    Parse HCL string into Body with error recovery

    test {
    let (result, errors) = parse_with_recovery("a = 1\nb = ")
    assert_true(result is Ok(_))
    assert_eq(errors.length(), 1)
    }

    simplify_body

    fn simplify_body(body : Body) -> Body

    Simplify all values in a Body by evaluating constant expressions

    test {
    let body = parse("a = 1 + 2").unwrap()
    let simp = simplify_body(body)
    assert_eq(expr_to_string(simp.find_attr("a").unwrap().get_value()), "3")
    }

    string_not_empty

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

    Validator: string not empty

    test {
    let v = string_not_empty()
    assert_eq(v(hcl_str("x"), "name").length(), 0)
    assert_eq(v(hcl_str(""), "name").length(), 1)
    }

    string_starts_with

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

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

    test {
    let v = string_starts_with("usr_")
    assert_eq(v(hcl_str("usr_1"), "id").length(), 0)
    assert_eq(v(hcl_str("abc"), "id").length(), 1)
    }

    substring

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

    Extract substring from string

    test {
    assert_eq(substring("hello", 1, 3), "el")
    assert_eq(substring("hello", 0, 5), "hello")
    }

    to_hcl_body

    fn to_hcl_body(body : Body) -> String

    Serialize Body to HCL string

    test {
    let body = parse("a = 1").unwrap()
    assert_eq(to_hcl_body(body), "a = 1")
    }

    to_hcl_bool

    fn to_hcl_bool(value : Bool) -> String

    Serialize Bool to HCL string

    test {
    assert_eq(to_hcl_bool(true), "true")
    assert_eq(to_hcl_bool(false), "false")
    }

    to_hcl_int

    fn to_hcl_int(value : Int) -> String

    Serialize Int to HCL string

    test {
    assert_eq(to_hcl_int(42), "42")
    }

    to_hcl_str

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

    Convert any ToHCL type to HCL string

    test {
    assert_eq(to_hcl_str(42), "42")
    assert_eq(to_hcl_str(true), "true")
    assert_true(to_hcl_str([1, 2]).contains("1"))
    }

    to_hcl_string

    fn to_hcl_string(value : String) -> String

    Serialize String to HCL string

    test {
    assert_eq(to_hcl_string("hi"), "\"hi\"")
    }

    to_hcl_value

    fn to_hcl_value(value : HCLValue) -> String

    Serialize HCLValue to HCL string

    test {
    assert_eq(to_hcl_value(hcl_int(1)), "1")
    assert_eq(to_hcl_value(hcl_str("x")), "\"x\"")
    }

    type_of

    fn type_of(v : HCLValue) -> TypeName

    Get the TypeName for a given HCLValue

    test {
    assert_eq(type_of(hcl_bool(true)), TypeName::TBool)
    assert_eq(type_of(hcl_null()), TypeName::TNull)
    }

    unify_types

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

    Find the common type for two types per HCL spec rules

    test {
    assert_eq(
    unify_types(TypeName::TNumber, TypeName::TString).unwrap(),
    TypeName::TString,
    )
    assert_eq(
    unify_types(TypeName::TNull, TypeName::TBool).unwrap(),
    TypeName::TBool,
    )
    assert_true(unify_types(TypeName::TNumber, TypeName::TBool) is Err(_))
    }

    validate

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

    Validate a value against a schema

    test {
    assert_eq(validate(hcl_int(1), TypeSchema::int()).length(), 0)
    assert_eq(validate(hcl_str("x"), TypeSchema::int()).length(), 1)
    }

    validate_ex

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

    Validate with custom validators

    test {
    let fx = FieldSchemaEx::new(FieldSchema::required(TypeSchema::int())).add_validator(
    int_in_range(0, 10),
    )
    assert_eq(
    validate_ex(hcl_object({ "age": hcl_int(5) }), { "age": fx }).length(),
    0,
    )
    assert_eq(
    validate_ex(hcl_object({ "age": hcl_int(99) }), { "age": fx }).length(),
    1,
    )
    }

    validate_one

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

    Validate and return first error, or Ok

    test {
    assert_true(validate_one(hcl_int(1), TypeSchema::int()) is Ok(_))
    assert_true(validate_one(hcl_str("x"), TypeSchema::int()) is Err(_))
    }

    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