HCL parser, formatter, and serialization library for MoonBit
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.
import {
"lenitain/hcl@0.2.0"
}moon add lenitain/hcl///|
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}")
}///|
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")
}///|
test "parse errors" {
match parse("age thirty") {
Err(e) => assert_true(e.to_display_string().contains("--> line 1"))
Ok(_) => panic()
}
}///|
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\"")
}///|
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)
}///|
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"])
}///|
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()
}
}///|
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()
}
}///|
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()
}
}///|
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()
}
}///|
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")
}///|
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()
}
}# 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| Category | Functions |
|---|---|
| Parse | parse(String) -> HCLResult[Body], parse_with_recovery(String) -> (Body?, Array[HCLError]) |
| Serialize | to_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]] |
| Deserialize | from_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[...] |
| JSON | hcl_to_json(String) -> String, body_to_json(Body) -> String, body_to_json_pretty(Body) -> String, json_to_body(String) -> HCLResult[Body] |
| Eval | eval_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[...] |
| Schema | TypeSchema, FieldSchema, BodySchema, Validator, from_hcl_with_schema |
| Types | TypeName enum, unify_types(TypeName, TypeName) -> HCLResult[TypeName], convert_value(HCLValue, TypeName) -> HCLResult[HCLValue] |
| Static analysis | collect_variables(Body) -> Array[String], collect_functions(Body) -> Array[String], collect_traversals(Body) -> Array[String] |
| Ident | Ident::new(String) -> HCLResult[Ident] (validates XID_Start/XID_Continue) |
| Span | Span struct, Spanned[T] wrapper with start/end line+column |
| FuncDef | FuncDefBuilder for defining functions with typed params, variadic, OneOf |
| FuncRegistry | FuncRegistry::new(), with_builtins(), register(name, def), merge(other), build() |
| Decor | Decor, Decorated[T], format_body_with_decor, format_attr_with_decor |
| Visit | Visit trait (immutable), VisitMut trait (mutable) |
test {
let pairs : ExprObject = [(ObjectKey::Identifier("a"), expr_int(1))]
assert_eq(expr_to_string(Expression::ExprObject(pairs)), "{ a = 1 }")
}test {
let o : HCLObject = { "a": hcl_int(1) }
assert_eq(o["a"].as_int().unwrap(), 1)
}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(_))
}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)
}test {
let r : HCLResult[Map[String, Int]] = from_hcl_str("a = 1")
assert_eq(r.unwrap()["a"], 1)
}test {
assert_eq(to_hcl_str(42), "42")
assert_eq(to_hcl_str("hi"), "\"hi\"")
}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
}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
}test {
let a = Attr::new("port", expr_int(80))
assert_eq(a.get_key(), "port")
}test {
assert_eq(Attr::new("x", expr_int(1)).get_decor(), Decor::empty())
}test {
let a = Attr::new("x", expr_int(1))
assert_eq(a.get_decorated_key().get_value(), "x")
}test {
assert_eq(Attr::new("x", expr_int(1)).get_key(), "x")
}test {
let a = Attr::new("x", expr_int(1))
assert_eq(expr_to_string(a.get_spanned_value().unwrap()), "1")
}test {
let a = Attr::new("x", expr_int(1))
assert_eq(expr_to_string(a.get_value()), "1")
}test {
let a = Attr::new("port", expr_int(80))
assert_eq(a.get_key(), "port")
assert_eq(expr_to_string(a.get_value()), "80")
}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(_))
}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(_))
}test {
let s = BodySchema::new().with_attrs({
"x": AttrSchema::optional(TypeSchema::int()),
})
assert_true(extract_body(Body::new(), s) is Ok(_))
}test {
let s = BodySchema::new().with_attrs({
"x": AttrSchema::required(TypeSchema::int()),
})
assert_true(extract_body(Body::new(), s) is Err(_))
}pub(all) struct BinaryOp {
left : Expression
op : BinaryOperator
right : Expression
} derive(Eq, Debug)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()
}
}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()
}
}test {
let blk = Block::simple("server", Body::new())
assert_eq(blk.get_type_name(), "server")
}test {
let b = Block::builder("resource")
let blk = b.build()
assert_eq(blk.get_type_name(), "resource")
}test {
let blk = Block::simple("server", Body::new().add_attr("port", expr_int(80)))
assert_eq(blk.find_attr("port").unwrap().get_key(), "port")
}test {
let blk = Block::simple("server", Body::new().add_attr("x", expr_int(1)))
assert_eq(blk.get_body().len(), 1)
}test {
assert_eq(Block::simple("server", Body::new()).get_decor(), Decor::empty())
}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")
}test {
let blk = Block::simple("server", Body::new())
assert_eq(blk.get_decorated_type_name().get_value(), "server")
}test {
let blk = Block::new("server", ["web", "prod"], Body::new())
assert_eq(blk.get_labels(), ["web", "prod"])
}test {
assert_eq(Block::simple("server", Body::new()).get_span(), None)
}test {
assert_eq(Block::simple("server", Body::new()).get_type_name(), "server")
}test {
let blk = Block::new("server", ["web"], Body::new())
assert_eq(blk.get_type_name(), "server")
assert_eq(blk.get_labels(), ["web"])
}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(_))
}test {
let blk = Block::simple("server", Body::new())
assert_eq(blk.get_type_name(), "server")
assert_eq(blk.get_labels().length(), 0)
}test {
let blk = Block::with_decor(
Decorated::bare("server"),
[Decorated::bare("web")],
Body::new(),
Decor::empty(),
)
assert_eq(blk.get_type_name(), "server")
}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"])
}test {
let blk = Block::builder("server").attr("port", expr_int(80)).build()
assert_eq(blk.find_attr("port").unwrap().get_key(), "port")
}test {
let blk = Block::builder("server").attr_hcl("port", 8080).build()
assert_eq(expr_to_string(blk.find_attr("port").unwrap().get_value()), "8080")
}fn BlockBuilder::attr_if(self : BlockBuilder, key : String, value : Expression, cond : Bool) -> BlockBuildertest {
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)
}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)
}test {
let blk = Block::builder("server").label("web").build()
assert_eq(blk.get_type_name(), "server")
assert_eq(blk.get_labels().length(), 1)
}test {
let blk = Block::builder("server").label("web").label("prod").build()
assert_eq(blk.get_labels(), ["web", "prod"])
}pub struct BlockSchema {
required : Bool
max_items : Int?
labels : Array[LabelSchema]
body : BodySchema
} derive(Eq, Debug)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(_))
}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(_))
}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(_),
)
}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(_))
}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(_),
)
}test {
let b = Body::new().add_attr("x", expr_int(1))
assert_eq(b.len(), 1)
}test {
let b = Body::new().add_attr("x", expr_int(1))
assert_eq(b.find_attr("x").unwrap().get_key(), "x")
}test {
let b = Body::new().add_block(Block::simple("server", Body::new()))
assert_eq(b.find_block("server").unwrap().get_type_name(), "server")
}test {
let b = Body::builder()
assert_eq(b.build().len(), 0)
}test {
let b = Body::new().add_attr("x", expr_int(1))
assert_eq(expr_to_string(b.find_attr("x").unwrap().get_value()), "1")
}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)
}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)
}test {
let b = Body::from_items([BodyItem::Attribute(Attr::new("x", expr_int(1)))])
assert_eq(b.len(), 1)
}test {
let b = Body::new()
assert_eq(b.get_decor(), Decor::empty())
}test {
let b = Body::new().add_attr("x", expr_int(1))
assert_eq(b.get_items().length(), 1)
}test {
assert_eq(Body::new().get_span(), None)
}test {
assert_eq(Body::new().is_empty(), true)
assert_eq(Body::new().add_attr("x", expr_int(1)).is_empty(), false)
}test {
let b = Body::new().add_attr("x", expr_int(1))
assert_eq(b.len(), 1)
}test {
let b = Body::new()
assert_eq(b.len(), 0)
assert_true(b.is_empty())
}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))
}test {
let b = Body::builder().attr("x", expr_int(1)).build()
assert_eq(b.len(), 1)
}test {
let b = Body::builder().attr("x", expr_int(1)).build()
assert_eq(b.find_attr("x").unwrap().get_key(), "x")
}test {
let b = Body::builder().attr_hcl("port", 8080).build()
assert_eq(expr_to_string(b.find_attr("port").unwrap().get_value()), "8080")
}fn BodyBuilder::attr_if(self : BodyBuilder, key : String, value : Expression, cond : Bool) -> BodyBuildertest {
let b = Body::builder()
.attr_if("a", expr_int(1), true)
.attr_if("b", expr_int(2), false)
.build()
assert_eq(b.len(), 1)
}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)
}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")
}test {
let b = Body::builder().attr("x", expr_int(1)).build()
assert_eq(b.len(), 1)
}test {
let it = BodyItem::Attribute(Attr::new("x", expr_int(1)))
let b = Body::from_items([it])
assert_eq(b.len(), 1)
}pub struct BodySchema {
attrs : Map[String, AttrSchema]
blocks : Map[String, BlockSchema]
extra_attrs : Bool
extra_blocks : Bool
} derive(Eq, Debug)test {
let s = BodySchema::new()
assert_eq(extract_body(Body::new(), s).unwrap().get_attr("x"), None)
}test {
let s = BodySchema::new()
assert_true(extract_body(Body::new(), s) is Ok(_))
}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")
}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)
}pub(all) struct Conditional {
condition : Expression
true_expr : Expression
false_expr : Expression
} derive(Eq, Debug)test {
let e = parse("v = c ? 1 : 2").unwrap().find_attr("v").unwrap().get_value()
match e {
Expression::ExprConditional(_) => ()
_ => panic()
}
}test {
let d = Decor::new(Some("# "), Some(" #"))
assert_eq(d.get_prefix(), Some("# "))
assert_eq(d.get_suffix(), Some(" #"))
}test {
let d = Decor::new(Some("#"), Some("#")).clear()
assert_eq(d, Decor::empty())
}test {
assert_eq(Decor::empty(), Decor::new(None, None))
}test {
assert_eq(Decor::empty().get_prefix(), None)
assert_eq(Decor::new(Some("x"), None).get_prefix(), Some("x"))
}test {
assert_eq(Decor::empty().get_suffix(), None)
assert_eq(Decor::new(None, Some("y")).get_suffix(), Some("y"))
}test {
let d = Decor::new(Some(" "), Some(" "))
assert_eq(d.get_prefix(), Some(" "))
assert_eq(d.get_suffix(), Some(" "))
}test {
let d = Decor::empty().set_prefix(" ")
assert_eq(d.get_prefix(), Some(" "))
assert_eq(d.get_suffix(), None)
}test {
let v = Decorated::new(42, Decor::new(Some(" "), Some(" ")))
assert_eq(v.get_value(), 42)
}test {
let v = Decorated::bare(7)
assert_eq(v.get_value(), 7)
assert_eq(v.get_decor(), Decor::empty())
}test {
let de = Decorated::expr(expr_str("hi"))
assert_eq(expr_to_string(de.get_expr()), "\"hi\"")
}test {
let de = Decorated::expr_with_decor(
expr_str("hi"),
Decor::new(Some(" /* c */ "), None),
)
assert_eq(decorated_expr_to_string(de), " /* c */ \"hi\"")
}test {
let d = Decor::new(Some("#"), None)
assert_eq(Decorated::new(1, d).get_decor(), d)
}test {
let de = Decorated::expr(expr_int(7))
assert_eq(expr_to_string(de.get_expr()), "7")
}test {
assert_eq(Decorated::bare(1).get_value(), 1)
}test {
let v = Decorated::new("x", Decor::empty())
assert_eq(v.get_value(), "x")
assert_eq(v.get_decor(), Decor::empty())
}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)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]")
}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"))
}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"))
}pub struct ExtractedBody {
attrs : Map[String, HCLValue]
blocks : Map[String, Array[ExtractedBlock]]
extra_blocks : Array[ExtractedBlock]
} derive(Eq, Debug)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")
}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)
}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)
}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)
}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)
}test {
let e = ExtractedBody::new()
assert_eq(e.get_attr("x"), None)
assert_eq(e.get_blocks("x").length(), 0)
}pub struct FieldSchema {
schema : TypeSchema
required : Bool
description : String
} derive(Eq, Debug)test {
let f = FieldSchema::required(TypeSchema::int())
let s = TypeSchema::object({ "age": f })
assert_true(is_valid(hcl_object({ "age": hcl_int(1) }), s))
}test {
let f = FieldSchema::optional(TypeSchema::int())
assert_eq(is_valid(hcl_object({}), TypeSchema::object({ "age": f })), true)
}test {
let f = FieldSchema::required(TypeSchema::int())
assert_eq(is_valid(hcl_object({}), TypeSchema::object({ "age": f })), false)
}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))
}pub struct FieldSchemaEx {
base : FieldSchema
validators : Array[(HCLValue, String) -> Array[HCLError]]
}test {
let fx = FieldSchemaEx::new(FieldSchema::required(TypeSchema::string()))
assert_eq(
validate_ex(hcl_object({ "name": hcl_str("x") }), { "name": fx }).length(),
0,
)
}fn FieldSchemaEx::add_validator(self : FieldSchemaEx, v : (HCLValue, String) -> Array[HCLError]) -> FieldSchemaExtest {
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,
)
}test {
let fx = FieldSchemaEx::new(FieldSchema::required(TypeSchema::int()))
assert_eq(
validate_ex(hcl_object({ "age": hcl_int(1) }), { "age": fx }).length(),
0,
)
}test {
let e = parse("v = [for x in xs : x]")
.unwrap()
.find_attr("v")
.unwrap()
.get_value()
match e {
Expression::ExprFor(ForExpr::List(_)) => ()
_ => panic()
}
}pub(all) struct ForListExpr {
var_name : String
collection : Expression
value_expr : Expression
filter : Expression?
} derive(Eq, Debug)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()
}
}pub(all) struct ForObjectExpr {
key_var : String
value_var : String
collection : Expression
key_expr : Expression
value_expr : Expression
filter : Expression?
} derive(Eq, Debug)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()
}
}test {
let c = FormatConfig::default()
assert_eq(c.indent, " ")
assert_eq(c.dense, false)
}test {
let c = FormatConfig::compact()
assert_eq(c.dense, true)
assert_eq(c.compact_arrays, true)
assert_eq(c.prefer_ident_keys, true)
}test {
let c = FormatConfig::default()
assert_eq(c.indent, " ")
assert_eq(c.compact_arrays, false)
}test {
let c = FormatConfig::dense()
assert_eq(c.dense, true)
assert_eq(c.compact_arrays, false)
}test {
let fmt = Formatter::new()
assert_eq(fmt.format_value(hcl_int(1)), "1")
}test {
let fmt = Formatter::new().set_prefer_ident_keys(true)
let body = parse("a = 1").unwrap()
assert_eq(fmt.format_body(body), "a = 1")
}test {
let fmt = Formatter::new().set_compact_arrays(true)
assert_eq(fmt.format_value(hcl_array([hcl_int(1), hcl_int(2)])), "[1, 2]")
}test {
let fmt = Formatter::new()
assert_eq(fmt.get_config().indent, " ")
}test {
let fmt = Formatter::new()
assert_eq(fmt.get_config().indent, " ")
}test {
let fmt = Formatter::new().set_compact_arrays(true)
assert_eq(fmt.get_config().compact_arrays, true)
}test {
let fmt = Formatter::new().set_compact_objects(true)
assert_eq(fmt.get_config().compact_objects, true)
}test {
let fmt = Formatter::new().set_dense(true)
assert_eq(fmt.get_config().dense, true)
}test {
let fmt = Formatter::new().set_indent(" ")
assert_eq(fmt.get_config().indent, " ")
}test {
let fmt = Formatter::new().set_prefer_ident_keys(true)
assert_eq(fmt.get_config().prefer_ident_keys, true)
}test {
let fmt = Formatter::with_config(FormatConfig::compact())
assert_eq(fmt.get_config().dense, true)
}test {
let fc = FuncCallBuilder::new("upper").arg(expr_str("x")).build()
assert_eq(expr_to_string(Expression::ExprFuncCall(fc)), "upper(\"x\")")
}test {
let fc = FuncCall::builder("len").arg(expr_str("x")).build()
assert_eq(expr_to_string(Expression::ExprFuncCall(fc)), "len(\"x\")")
}test {
let fc = FuncCallBuilder::new("max").arg(expr_int(1)).build()
assert_eq(expr_to_string(Expression::ExprFuncCall(fc)), "max(1)")
}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)")
}test {
let fc = FuncCallBuilder::new("min").arg(expr_int(1)).build()
assert_eq(fc.name, "min")
}test {
let b = FuncCallBuilder::new("max")
assert_eq(expr_to_string(Expression::ExprFuncCall(b.build())), "max()")
}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")
}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(_))
}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(_))
}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)
}fn FuncDefBuilder::build(self : FuncDefBuilder, name : String, func : (Array[HCLValue]) -> Result[HCLValue, HCLError]) -> FuncDeftest {
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)
}test {
let b = FuncDefBuilder::new()
let fd = b.build("noop", fn(_args) { Ok(hcl_null()) })
assert_true(fd.call([]) is Ok(_))
}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(_))
}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,
)
}test {
let reg = FuncRegistry::with_builtins()
let f = reg.build()
assert_true(f.contains("upper"))
}test {
let reg = FuncRegistry::new()
assert_eq(reg.build().length(), 0)
}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"))
}test {
let reg = FuncRegistry::new()
assert_eq(reg.build().length(), 0)
}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"))
}test {
let reg = FuncRegistry::with_builtins()
let f = reg.build()
assert_true(f.contains("abs"))
assert_true(f.contains("lower"))
}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)test {
let e = HCLError::type_mismatch("Int", "string")
assert_eq(e.message(), "Type error: expected Int, got string")
}test {
assert_eq(HCLError::division_by_zero().message(), "Division by zero")
}test {
assert_eq(HCLError::encoding_error("e").message(), "Encoding error: e")
}test {
assert_eq(HCLError::invalid_value("bad").message(), "Invalid value: bad")
}test {
assert_eq(HCLError::io_error("disk").message(), "IO error: disk")
}test {
assert_eq(HCLError::missing_field("port").message(), "Missing field: port")
assert_eq(HCLError::division_by_zero().message(), "Division by zero")
}test {
assert_eq(HCLError::missing_field("name").message(), "Missing field: name")
}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",
)
}test {
let e = HCLError::parse_error("boom", 1, 5, 4)
assert_eq(e.message(), "Parse error at line 1, column 5: boom")
}test {
let e = HCLError::parse_error_with_context("boom", 1, 2, 1, "x =")
assert_true(e.message().contains("x ="))
}error: Expected '=', got '}'
--> line 1, col 12
|
1 | resource x {
| ^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("^"))
}test {
let err = HCLError::type_error("boom")
assert_eq(err.to_string(), "error: Type error: expected type error, got boom")
}test {
let e = HCLError::type_error("boom")
assert_eq(e.message(), "Type error: expected type error, got boom")
}test {
let e = HCLError::type_mismatch("Int", "string")
assert_eq(e.message(), "Type error: expected Int, got string")
}test {
assert_eq(
HCLError::undefined_function("f").message(),
"Undefined function: f",
)
}test {
assert_eq(
HCLError::undefined_property("p").message(),
"Undefined property: p",
)
}test {
assert_eq(
HCLError::undefined_variable("x").message(),
"Undefined variable: x",
)
}test {
let o = HCLObjectBuilder::new().entry("a", hcl_int(1)).build()
assert_eq(o["a"].as_int().unwrap(), 1)
}test {
let o = HCLObjectBuilder::new().entry("x", hcl_str("y")).build()
assert_eq(o["x"].as_string().unwrap(), "y")
}fn HCLObjectBuilder::entry(self : HCLObjectBuilder, key : String, value : HCLValue) -> HCLObjectBuildertest {
let o = HCLObjectBuilder::new().entry("port", hcl_int(8080)).build()
assert_eq(o["port"].as_int().unwrap(), 8080)
}fn[T : ToHCL] HCLObjectBuilder::entry_hcl(self : HCLObjectBuilder, key : String, value : T) -> HCLObjectBuildertest {
let o = HCLObjectBuilder::new().entry_hcl("count", 3).build()
assert_eq(o["count"].as_int().unwrap(), 3)
}fn HCLObjectBuilder::entry_if(self : HCLObjectBuilder, key : String, value : HCLValue, cond : Bool) -> HCLObjectBuildertest {
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)
}fn[T : ToHCL] HCLObjectBuilder::entry_option(self : HCLObjectBuilder, key : String, value : T?) -> HCLObjectBuildertest {
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)
}fn HCLObjectBuilder::extend_with(self : HCLObjectBuilder, other : Map[String, HCLValue]) -> HCLObjectBuildertest {
let o = HCLObjectBuilder::new()
.extend_with(hcl_object_from_pairs([("a", hcl_int(1))]))
.build()
assert_eq(o["a"].as_int().unwrap(), 1)
}test {
let b = HCLObjectBuilder::new()
assert_eq(b.build().is_empty(), true)
}test {
let v = HCLValue::int(42)
assert_true(v.is_number())
assert_eq(v.as_int().unwrap(), 42)
}test {
let a = HCLValue::array([hcl_int(1)])
assert_eq(a.as_array().unwrap().length(), 1)
}test {
let a = HCLValue::array([hcl_int(1), hcl_int(2)])
assert_eq(a.as_array().unwrap().length(), 2)
}test {
assert_eq(HCLValue::bool(true).as_bool().unwrap(), true)
assert_eq(HCLValue::int(1).as_bool(), None)
}test {
assert_eq(HCLValue::float(1.5).as_float().unwrap(), 1.5)
}test {
assert_eq(HCLValue::int(42).as_int().unwrap(), 42)
assert_eq(HCLValue::string("x").as_int(), None)
}test {
assert_eq(HCLValue::int64(7L).as_int64().unwrap(), 7L)
}test {
assert_eq(HCLValue::int(1).as_number().unwrap().as_int().unwrap(), 1)
match HCLValue::bool(true).as_number() {
None => ()
Some(_) => panic()
}
}test {
let o = HCLValue::object({ "a": hcl_int(1) })
assert_eq(o.as_object().unwrap()["a"].as_int().unwrap(), 1)
}test {
assert_eq(HCLValue::string("hi").as_string().unwrap(), "hi")
assert_eq(HCLValue::int(1).as_string(), None)
}test {
assert_eq(HCLValue::bool(false).as_bool().unwrap(), false)
}test {
assert_eq(HCLValue::float(2.5).as_float().unwrap(), 2.5)
}test {
let v = HCLValue::string("x")
assert_eq(v.get_decor(), Decor::empty())
}test {
assert_eq(HCLValue::int(7).as_int().unwrap(), 7)
}test {
assert_eq(HCLValue::int64(7L).as_int64().unwrap(), 7L)
}test {
assert_eq(HCLValue::array([hcl_int(1)]).is_array(), true)
}test {
assert_eq(HCLValue::bool(true).is_bool(), true)
assert_eq(HCLValue::int(1).is_bool(), false)
}test {
assert_eq(HCLValue::null().is_null(), true)
assert_eq(HCLValue::int(1).is_null(), false)
}test {
assert_eq(HCLValue::int(1).is_number(), true)
assert_eq(HCLValue::string("x").is_number(), false)
}test {
assert_eq(HCLValue::object({ "a": hcl_int(1) }).is_object(), true)
}test {
assert_eq(HCLValue::string("x").is_string(), true)
}test {
assert_eq(HCLValue::unknown().is_unknown(), true)
assert_eq(HCLValue::int(1).is_unknown(), false)
}test {
assert_true(HCLValue::null().is_null())
}test {
let o = HCLValue::object({ "k": hcl_str("v") })
assert_eq(o.as_object().unwrap()["k"].as_string().unwrap(), "v")
}test {
let v = HCLValue::int(1).set_decor(Decor::new(Some(" "), None))
assert_eq(v.get_decor().get_prefix(), Some(" "))
}test {
assert_eq(HCLValue::string("hi").as_string().unwrap(), "hi")
}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")
}test {
assert_eq(HCLValue::int(1).type_name(), "number")
assert_eq(HCLValue::string("x").type_name(), "string")
}pub(all) struct Heredoc {
delimiter : String
content : String
strip_mode : HeredocStripMode
} derive(Eq, Debug)test {
let h : Heredoc = {
delimiter: "EOT",
content: "hi\n",
strip_mode: HeredocStripMode::NoStrip,
}
assert_eq(h.delimiter, "EOT")
assert_eq(h.content, "hi\n")
}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)
}test {
let id = Ident::new("name")
assert_eq(id.as_str(), "name")
assert_eq(id.len(), 4)
}test {
assert_eq(Ident::new("x").as_str(), "x")
}test {
assert_eq(Ident::new("a").hash(), Ident::new("a").hash())
}test {
assert_eq(Ident::new("x").into_string(), "x")
}test {
assert_eq(Ident::new("x").is_empty(), false)
assert_eq(Ident::new_unchecked("").is_empty(), true)
}test {
assert_eq(Ident::new("abcd").len(), 4)
}test {
let id = Ident::new("server")
assert_eq(id.as_str(), "server")
}test {
assert_eq(Ident::new_sanitized("my name").as_str(), "my_name")
assert_eq(Ident::new_sanitized("").as_str(), "_")
}test {
let id = Ident::new_unchecked("anything")
assert_eq(id.as_str(), "anything")
}test {
assert_eq(Ident::new("x").output(), "x")
}test {
assert_eq(Ident::new("foo").to_string(), "Ident(foo)")
}test {
match JsonValue::JsonString("x") {
JsonValue::JsonString(s) => assert_eq(s, "x")
_ => panic()
}
}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(_))
}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(_))
}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(_))
}pub struct Lexer {
input : String
pos : Int
line : Int
col : Int
}test {
let lx = Lexer::new("a = 1")
assert_eq(lx.tokenize().unwrap().length(), 4)
}test {
let (_, cm) = Lexer::new("// hi\nx").collect_comment()
assert_eq(cm, Some("// hi"))
}test {
let (_, ws) = Lexer::new(" x").collect_whitespace()
assert_eq(ws, Some(" "))
}test {
let lx = Lexer::new("a = 1")
assert_eq(lx.get_line(1), "a = 1")
}test {
let lx = Lexer::new("a = 1")
let (_, _, offset) = lx.location()
assert_eq(offset, 0)
}test {
let lx = Lexer::new("a = 1")
let (t, _) = lx.next_token().unwrap()
assert_eq(t, Token::Ident("a"))
}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)
}test {
let (t, _, tr) = Lexer::new("a").next_token_with_trivia().unwrap()
assert_eq(t, Token::Ident("a"))
assert_eq(tr, None)
}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)
}pub(all) enum N {
PosInt(UInt64)
NegInt(Int64)
Float(Double)
}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())
}test {
let n = Number::from_int(42)
assert_eq(n.as_int().unwrap(), 42)
}test {
assert_eq(Number::from_int(3).as_f64(), 3.0)
}test {
assert_eq(Number::from_int(3).as_float(), 3.0)
}test {
assert_eq(Number::from_int64(7L).as_i64().unwrap(), 7L)
assert_eq(Number::from_double(1.5).as_i64(), None)
}test {
assert_eq(Number::from_int(42).as_int().unwrap(), 42)
assert_eq(Number::from_double(1.5).as_int(), None)
}test {
assert_eq(Number::from_int(7).as_int64().unwrap(), 7L)
}test {
assert_eq(Number::from_uint64(7UL).as_u64().unwrap(), 7UL)
assert_eq(Number::from_int(-1).as_u64(), None)
}test {
assert_eq(Number::from_double(3.5).as_float(), 3.5)
assert_eq(Number::from_double(42.0).as_int().unwrap(), 42)
}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()
}
}test {
assert_eq(Number::from_finite_f64(2.0).as_int().unwrap(), 2)
}test {
assert_eq(Number::from_int(-5).as_int().unwrap(), -5)
}test {
assert_eq(Number::from_int64(-5L).as_int64().unwrap(), -5L)
}test {
assert_eq(Number::from_uint64(5UL).as_u64().unwrap(), 5UL)
}test {
assert_eq(Number::from_double(1.5).is_f64(), true)
assert_eq(Number::from_int(1).is_f64(), false)
}test {
assert_eq(Number::from_double(1.5).is_float(), true)
}test {
assert_eq(Number::from_int(5).is_int(), true)
assert_eq(Number::from_double(1.5).is_int(), false)
}test {
assert_eq(Number::from_int64(-5L).is_int64(), true)
assert_eq(Number::from_int(5).is_int64(), false)
}test {
assert_eq(Number::from_int(-5).is_neg_int(), true)
assert_eq(Number::from_int(5).is_neg_int(), false)
}test {
assert_eq(ObjectKey::Identifier("x").to_string(), "x")
assert_eq(ObjectKey::Expression(expr_int(1)).to_string(), "1")
}test {
let e = parse("v = 1 + 2").unwrap().find_attr("v").unwrap().get_value()
match e {
Expression::ExprOperation(Operation::Binary(_)) => ()
_ => panic()
}
}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)
}test {
assert_eq(ParamType::ParamString.display_name(), "string")
assert_eq(ParamType::ParamNumber.display_name(), "number")
assert_eq(
ParamType::Nullable(ParamType::ParamString).display_name(),
"string?",
)
}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,
)
}test {
let p = Parser::new("a = 1").unwrap()
assert_eq(p.parse_body().unwrap().len(), 1)
}test {
let p = Parser::from_lexer(Lexer::new("x = 1")).unwrap()
assert_eq(p.parse_body().unwrap().len(), 1)
}test {
let p = Parser::new("x = 1").unwrap()
assert_eq(p.parse_body().unwrap().len(), 1)
}test {
let p = Parser::new("x = 1").unwrap()
assert_eq(p.parse_body().unwrap().len(), 1)
}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)
}test {
let s = Span::new(1, 2, 0, 1, 5, 4)
assert_eq(s, Span::new(1, 2, 0, 1, 5, 4))
}test {
assert_eq(Span::empty(), Span::new(0, 0, 0, 0, 0, 0))
}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)
}test {
let s : Spanned[Int] = Spanned::bare(42)
assert_eq(s.unwrap(), 42)
assert_eq(s.get_span(), None)
}test {
let s = Spanned::bare("x")
assert_eq(s.unwrap(), "x")
assert_eq(s.get_span(), None)
}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))
}test {
let s = Spanned::new(42, Span::empty())
assert_eq(s.unwrap(), 42)
assert_true(s.get_span() is Some(_))
}test {
let t = Template::from_string("hello").unwrap()
assert_eq(t.evaluate(Map([]), Map([])).unwrap(), "hello")
}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!")
}test {
let t = Template::from_heredoc("hello\n", "EOT", false).unwrap()
assert_eq(t.evaluate(Map([]), Map([])).unwrap(), "hello\n")
}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!")
}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()
}
}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)test {
let t = parse_template("hello ${x}").unwrap()
match t.parts[0] {
TemplatePart::Text(s) => assert_eq(s, "hello ")
_ => panic()
}
}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)test {
assert_eq(Token::Ident("x").is_literal(), true)
assert_eq(Token::Equals.is_delimiter(), false)
assert_eq(Token::Plus.precedence(), 5)
}test {
assert_eq(Token::LBrace.is_delimiter(), true)
assert_eq(Token::RParen.is_delimiter(), true)
assert_eq(Token::Equals.is_delimiter(), false)
}test {
assert_eq(Token::Ident("x").is_literal(), true)
assert_eq(Token::NumberLit("42").is_literal(), true)
assert_eq(Token::Equals.is_literal(), false)
}test {
assert_eq(Token::Plus.is_operator(), true)
assert_eq(Token::AndAnd.is_operator(), true)
assert_eq(Token::Ident("x").is_operator(), false)
}pub(all) struct Traversal {
base : Expression
operators : Array[TraversalOperator]
} derive(Eq, Debug)test {
let t = TraversalBuilder::new(expr_str("obj")).attr("key").build()
assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"obj\".key")
}test {
let b = Traversal::builder(expr_str("o"))
assert_eq(
expr_to_string(Expression::ExprTraversal(b.attr("k").build())),
"\"o\".k",
)
}test {
let t = TraversalBuilder::new(expr_str("o")).attr("a").build()
assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"o\".a")
}test {
let t = TraversalBuilder::new(expr_str("o")).attr("a").attr("b").build()
assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"o\".a.b")
}test {
let t = TraversalBuilder::new(expr_str("o")).build()
assert_true(Expression::ExprTraversal(t) is Expression::ExprTraversal(_))
}test {
let t = TraversalBuilder::new(expr_str("o")).index(expr_int(0)).build()
assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"o\"[0]")
}test {
let b = TraversalBuilder::new(expr_str("o"))
assert_eq(expr_to_string(Expression::ExprTraversal(b.build())), "\"o\"")
}test {
let t = TraversalBuilder::new(expr_str("o")).splat().attr("a").build()
assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"o\".*.a")
}test {
assert_eq(
expr_to_string(
Expression::ExprTraversal(
TraversalBuilder::new(expr_str("o")).attr("a").build(),
),
),
"\"o\".a",
)
}test {
assert_eq(type_of(hcl_int(42)), TypeName::TNumber)
assert_eq(type_of(hcl_str("x")), TypeName::TString)
}pub(all) enum TypeSchema {
Any
NullSchema
BoolSchema
IntSchema
Int64Schema
FloatSchema
NumberSchema
StringSchema
ArraySchema(TypeSchema)
ObjectSchema(Map[String, FieldSchema])
} derive(Eq, Debug)test {
assert_true(is_valid(hcl_int(42), TypeSchema::int()))
assert_true(is_valid(hcl_str("x"), TypeSchema::string()))
}test {
assert_true(is_valid(hcl_int(1), TypeSchema::any()))
assert_true(is_valid(hcl_str("x"), TypeSchema::any()))
}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)
}test {
assert_true(is_valid(hcl_bool(true), TypeSchema::bool()))
assert_eq(is_valid(hcl_int(1), TypeSchema::bool()), false)
}test {
assert_true(is_valid(hcl_float(1.5), TypeSchema::float()))
assert_eq(is_valid(hcl_int(1), TypeSchema::float()), false)
}test {
assert_true(is_valid(hcl_int(42), TypeSchema::int()))
assert_eq(is_valid(hcl_str("x"), TypeSchema::int()), false)
}test {
assert_true(is_valid(hcl_int64(42L), TypeSchema::int64()))
}test {
assert_true(is_valid(hcl_null(), TypeSchema::null()))
assert_eq(is_valid(hcl_int(1), TypeSchema::null()), false)
}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)
}test {
let s = TypeSchema::object({
"name": FieldSchema::required(TypeSchema::string()),
})
assert_true(is_valid(hcl_object({ "name": hcl_str("x") }), s))
}test {
assert_true(is_valid(hcl_str("x"), TypeSchema::string()))
assert_eq(is_valid(hcl_int(1), TypeSchema::string()), false)
}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()
}
}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()
}
}test {
let e = parse("v = x").unwrap().find_attr("v").unwrap().get_value()
match e {
Expression::ExprVariable(_) => ()
_ => panic()
}
}test {
let body = parse("name = \"foo\"").unwrap()
assert_eq(body_to_json(body), "{\"name\":\"foo\"}")
}test {
let body = parse("name = \"foo\"").unwrap()
assert_eq(body_to_json_pretty(body), "{\n \"name\": \"foo\"\n}")
}test {
let f = builtin_functions()
assert_true(f.contains("abs"))
assert_true(f.contains("upper"))
assert_true(f.contains("length"))
}test {
let body = parse("a = upper(\"x\")\nb = lower(\"y\")").unwrap()
assert_eq(collect_functions(body), ["lower", "upper"])
}test {
let e = parse("a = upper(x)").unwrap().find_attr("a").unwrap().get_value()
assert_eq(collect_functions_from_expr(e), ["upper"])
}test {
let body = parse("a = obj.key1\nb = other.attr").unwrap()
assert_eq(collect_traversals(body), ["obj", "other"])
}test {
let e = parse("a = obj.key").unwrap().find_attr("a").unwrap().get_value()
assert_eq(collect_traversals_from_expr(e), ["obj"])
}test {
let body = parse("a = x\nb = y").unwrap()
assert_eq(collect_variables(body), ["x", "y"])
}test {
let e = parse("a = x + y").unwrap().find_attr("a").unwrap().get_value()
assert_eq(collect_variables_from_expr(e), ["x", "y"])
}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,
)
}test {
let body = parse("port = 8080").unwrap()
let port : Int = decode_attr(body, "port").unwrap()
assert_eq(port, 8080)
}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)
}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)
}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)
}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)
}test {
let de = Decorated::expr_with_decor(
expr_str("hi"),
Decor::new(Some("# "), Some(" #")),
)
assert_eq(decorated_expr_to_string(de), "# \"hi\" #")
}test {
let attr = encode_attr("port", 8080)
assert_eq(attr.get_key(), "port")
assert_eq(expr_to_string(attr.get_value()), "8080")
}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")
}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",
)
}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)
}fn escape_hcl_string(s : String) -> Stringtest {
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}\"")
}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,
)
}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,
)
}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)
}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",
)
}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",
)
}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)
}test {
let vars : Map[String, HCLValue] = { "name": hcl_str("Moon") }
assert_eq(
evaluate_template("Hello, ${name}!", vars, Map([])).unwrap(),
"Hello, Moon!",
)
}test {
assert_eq(expr_to_string(expr_array([expr_int(1), expr_int(2)])), "[1, 2]")
}test {
assert_eq(expr_to_string(expr_bool(true)), "true")
}test {
let fc = FuncCallBuilder::new("upper").arg(expr_str("x")).build()
assert_eq(expr_to_string(expr_func_call(fc)), "upper(\"x\")")
}test {
assert_eq(expr_to_string(expr_int(7)), "7")
}test {
assert_eq(expr_to_string(expr_null()), "null")
}test {
assert_eq(expr_to_string(expr_str("hi")), "\"hi\"")
}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")
}test {
assert_eq(expr_to_string(expr_int(42)), "42")
assert_eq(expr_to_string(expr_str("hi")), "\"hi\"")
}test {
assert_eq(expr_to_string(expr_unknown()), "unknown")
}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)
}test {
let a = Attr::new("x", expr_int(1))
assert_eq(format_attr_with_decor(a), "x = 1")
}test {
let body = parse("a = 1").unwrap()
assert_eq(format_body(body), "a = 1")
}test {
let body = parse("a = 1").unwrap()
assert_eq(format_body_with_decor(body), "a = 1")
}test {
assert_eq(format_value_content(hcl_str("hi")), "\"hi\"")
assert_eq(format_value_content(hcl_null()), "null")
}test {
assert_eq(format_value_with_decor(hcl_int(1)), "1")
}test {
let body = from_hcl_body("x = 1").unwrap()
assert_eq(body.len(), 1)
}test {
assert_eq(from_hcl_bool("x = true").unwrap(), true)
}test {
assert_eq(from_hcl_int("x = 42").unwrap(), 42)
}test {
let r : HCLResult[Map[String, Int]] = from_hcl_str("a = 1")
assert_eq(r.unwrap()["a"], 1)
}test {
assert_eq(from_hcl_string("x = \"hi\"").unwrap(), "hi")
}test {
let v = from_hcl_value("x = 1").unwrap()
assert_eq(v.as_object().unwrap()["x"].as_int().unwrap(), 1)
}fn from_hcl_with_body_schema(input : String, schema : BodySchema) -> Result[ExtractedBody, Array[HCLError]]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)
}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(_))
}fn from_hcl_with_schema_full(input : String, schema : TypeSchema) -> Result[HCLValue, Array[HCLError]]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()
}
}test {
let a = hcl_array([hcl_int(1), hcl_int(2)])
assert_eq(a.as_array().unwrap().length(), 2)
}test {
assert_eq(hcl_bool(true).as_bool().unwrap(), true)
}test {
assert_eq(hcl_float(1.5).as_float().unwrap(), 1.5)
}test {
assert_eq(hcl_int(42).as_int().unwrap(), 42)
}test {
assert_eq(hcl_int64(7L).as_int64().unwrap(), 7L)
}test {
assert_true(hcl_null().is_null())
}test {
let o = hcl_object({ "a": hcl_int(1) })
assert_eq(o.as_object().unwrap()["a"].as_int().unwrap(), 1)
}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")
}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)
}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)
}test {
let o = hcl_object_from_pairs([("a", hcl_int(1)), ("b", hcl_int(2))])
assert_eq(hcl_object_keys(o), ["a", "b"])
}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)
}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)
}test {
assert_eq(hcl_str("hi").as_string().unwrap(), "hi")
}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\"}",
)
}test {
assert_eq(hcl_to_json_pretty("a = 1").unwrap(), "{\n \"a\": 1\n}")
}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\"")
}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)
}fn is_id_continue(ch : Char) -> Booltest {
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)
}fn is_id_start(ch : Char) -> Booltest {
assert_eq(is_id_start('a'), true)
assert_eq(is_id_start('_'), true)
assert_eq(is_id_start('1'), false)
}fn is_ident(s : String) -> Booltest {
assert_eq(is_ident("server_name"), true)
assert_eq(is_ident("1x"), false)
assert_eq(is_ident(""), false)
}test {
assert_eq(is_valid(hcl_int(1), TypeSchema::int()), true)
assert_eq(is_valid(hcl_str("x"), TypeSchema::int()), false)
}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")
}test {
let out = json_to_hcl_string("{\"a\": 1}").unwrap()
assert_eq(out, "a = 1")
}test {
let base = builtin_functions()
let extra : Map[String, FuncDef] = Map([])
let merged = merge_funcs(base, extra)
assert_true(merged.contains("abs"))
}test {
let o = new_hcl_object()
assert_eq(o.is_empty(), true)
}test {
let body = parse("x = 1").unwrap()
assert_eq(body.len(), 1)
assert_eq(body.find_attr("x").unwrap().get_key(), "x")
}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")
}test {
let (result, errors) = parse_with_recovery("a = 1\nb = ")
assert_true(result is Ok(_))
assert_eq(errors.length(), 1)
}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")
}test {
let v = string_not_empty()
assert_eq(v(hcl_str("x"), "name").length(), 0)
assert_eq(v(hcl_str(""), "name").length(), 1)
}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)
}fn substring(s : String, start : Int, end : Int) -> Stringtest {
assert_eq(substring("hello", 1, 3), "el")
assert_eq(substring("hello", 0, 5), "hello")
}test {
let body = parse("a = 1").unwrap()
assert_eq(to_hcl_body(body), "a = 1")
}fn to_hcl_bool(value : Bool) -> Stringtest {
assert_eq(to_hcl_bool(true), "true")
assert_eq(to_hcl_bool(false), "false")
}fn to_hcl_int(value : Int) -> Stringtest {
assert_eq(to_hcl_int(42), "42")
}test {
assert_eq(to_hcl_str(42), "42")
assert_eq(to_hcl_str(true), "true")
assert_true(to_hcl_str([1, 2]).contains("1"))
}fn to_hcl_string(value : String) -> Stringtest {
assert_eq(to_hcl_string("hi"), "\"hi\"")
}test {
assert_eq(to_hcl_value(hcl_int(1)), "1")
assert_eq(to_hcl_value(hcl_str("x")), "\"x\"")
}test {
assert_eq(type_of(hcl_bool(true)), TypeName::TBool)
assert_eq(type_of(hcl_null()), TypeName::TNull)
}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(_))
}test {
assert_eq(validate(hcl_int(1), TypeSchema::int()).length(), 0)
assert_eq(validate(hcl_str("x"), TypeSchema::int()).length(), 1)
}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,
)
}test {
assert_true(validate_one(hcl_int(1), TypeSchema::int()) is Ok(_))
assert_true(validate_one(hcl_str("x"), TypeSchema::int()) is Err(_))
}Install
Download zipHCL parser, formatter, and serialization library for MoonBit