HCL parser, formatter, and serialization library for MoonBit
| Feature | Why Not Possible |
|---|---|
| Serde #[derive(Serialize, Deserialize)] | MoonBit has no procedural macros / derive system |
| Span with byte offsets | MoonBit AST nodes don't track source span |
| Formatted<T> round-trip | MoonBit lacks custom formatting traits |
| winnow combinator parsing | No parser combinator library exists for MoonBit |
| perf features / benchmarks | No benchmarking infrastructure |
| indexmap/vecmap | No equivalent crate exists |
| stdin support | MoonBit stdlib has no stdin API |
| glob file patterns | No glob library for MoonBit |
| Feature | Workaround |
|---|---|
| stdin input | Use --file option to read from file |
| glob patterns | Process files individually in a build script |
import "hcl"
// Parse HCL
let input = "name = \"John\"\nport = 8080"
let body = hcl.parse(input).unwrap()
// Access attributes
let name = body.find_attr("name").unwrap().get_value().as_string()
let port = body.find_attr("port").unwrap().get_value().as_int()
// Serialize back to HCL
let hcl_str = hcl.to_hcl_body(body)
// Convert to JSON
let json_str = hcl.body_to_json_pretty(body)moon add github:lenitain/hcl{
"dependencies": {
"hcl": "github:lenitain/hcl"
}
}let input = `
// Server configuration
server {
host = "localhost"
port = 8080
}
name = "myapp"
version = "1.0.0"
`
let body = hcl.parse(input).unwrap()
// Find block
let server = body.find_block("server").unwrap()
let server_body = server.get_body()
let host = server_body.find_attr("host").unwrap().get_value().as_string()
// Find attribute
let name = body.find_attr("name").unwrap().get_value().as_string()let value = hcl.hcl_object([
("name", hcl.hcl_str("John")),
("age", hcl.hcl_int(30)),
("active", hcl.hcl_bool(true)),
])
let hcl_str = hcl.to_hcl_value(value)
// name = "John"
// age = 30
// active = truelet input = "// Configure server\nhost = \"localhost\"\nport = 8080"
let body = hcl.parse(input).unwrap()
// format_body_with_decor preserves comments
let output = hcl.format_body_with_decor(body)let vars = {
"x": hcl.hcl_int(10),
"y": hcl.hcl_int(3),
}
let funcs = hcl.builtin_functions()
// Evaluate: x + y > 5 ? "yes" : "no"
let expr = hcl.hcl_object([
("type", hcl.hcl_str("conditional")),
("condition", hcl.hcl_object([
("type", hcl.hcl_str("binary_expr")),
("op", hcl.hcl_str(">")),
("left", hcl.hcl_object([
("type", hcl.hcl_str("binary_expr")),
("op", hcl.hcl_str("+")),
("left", hcl.hcl_str("x")),
("right", hcl.hcl_str("y")),
])),
("right", hcl.hcl_int(5)),
])),
("true_expr", hcl.hcl_str("yes")),
("false_expr", hcl.hcl_str("no")),
])
let result = hcl.eval_expr(expr, vars, funcs)
// Ok(String("yes", ...))let schema = hcl.FieldSchema::new()
.attr("name", hcl.TypeSchema::String)
.attr("port", hcl.TypeSchema::Int)
.required("name")
let body = hcl.parse("port = 8080").unwrap()
let result = hcl.from_hcl_with_schema(body, schema)
// Err(HCLError::missing_required("name"))# Parse and convert to JSON
moon run cmd/main --file config.hcl
# Pretty print JSON
moon run cmd/main --file config.hcl --pretty
# Simplify expressions
moon run cmd/main --file config.hcl --simplify
# Validate HCL (exit code 0 or 1)
moon run cmd/main --file config.hcl --validate
# Format HCL
moon run cmd/main --file config.hcl --formatname = "John"
age = 30
active = trueresource "aws_instance" "example" {
ami = "ami-123456"
instance_type = "t2.micro"
}config = {
host = "localhost"
port = 8080
}
items = ["one", "two", "three"]# Arithmetic
count = 1 + 2 * 3
# Conditionals
status = count > 10 ? "high" : "low"
# For expressions
names = [for item in items: item.name]script = <<EOF
#!/bin/bash
echo "Hello"
EOF| Feature | hcl-rs | MoonBit HCL | Note |
|---|---|---|---|
| Parse | ✅ | ✅ | Same API |
| Serialize | ✅ | ✅ | Same API |
| Deserialize | ✅ | ✅ | Manual traits instead of derive |
| Expression eval | ✅ | ✅ | Same built-in functions |
| Schema validation | ✅ | ✅ | Same API |
| Decor/Edit | ✅ | ✅ | Same API |
| Serde derive | ✅ | ❌ | No proc macros |
| Span tracking | ✅ | ❌ | No span in AST |
| Formatted round-trip | ✅ | ❌ | No custom format traits |
| perf features | ✅ | ❌ | No benchmarking infra |
pub(open) trait Visit {
visit_body(Self, Body) -> Unit
visit_body_item(Self, BodyItem) -> Unit
visit_attr(Self, Attr) -> Unit
visit_block(Self, Block) -> Unit
visit_value(Self, HCLValue) -> Unit
visit_expr(Self, Expression) -> Unit
visit_object_key(Self, ObjectKey) -> Unit
visit_traversal(Self, Traversal) -> Unit
visit_traversal_operator(Self, TraversalOperator) -> Unit
visit_func_call(Self, FuncCall) -> Unit
visit_conditional(Self, Conditional) -> Unit
visit_operation(Self, Operation) -> Unit
visit_binary_op(Self, BinaryOp) -> Unit
visit_unary_op(Self, UnaryOp) -> Unit
visit_for_expr(Self, ForExpr) -> Unit
visit_template_expr(Self, TemplateExpr) -> Unit
visit_heredoc(Self, Heredoc) -> Unit
visit_decorated_expr(Self, Decorated[Expression]) -> Unit
}pub(open) trait VisitMut {
visit_body_mut(Self, Body) -> Unit
visit_body_item_mut(Self, BodyItem) -> Unit
visit_attr_mut(Self, Attr) -> Unit
visit_block_mut(Self, Block) -> Unit
visit_value_mut(Self, HCLValue) -> Unit
visit_expr_mut(Self, Expression) -> Unit
visit_object_key_mut(Self, ObjectKey) -> Unit
visit_traversal_mut(Self, Traversal) -> Unit
visit_traversal_operator_mut(Self, TraversalOperator) -> Unit
visit_func_call_mut(Self, FuncCall) -> Unit
visit_conditional_mut(Self, Conditional) -> Unit
visit_operation_mut(Self, Operation) -> Unit
visit_binary_op_mut(Self, BinaryOp) -> Unit
visit_unary_op_mut(Self, UnaryOp) -> Unit
visit_for_expr_mut(Self, ForExpr) -> Unit
visit_template_expr_mut(Self, TemplateExpr) -> Unit
visit_heredoc_mut(Self, Heredoc) -> Unit
visit_decorated_expr_mut(Self, Decorated[Expression]) -> Unit
}fn BlockBuilder::attr_if(self : BlockBuilder, key : String, value : HCLValue, cond : Bool) -> BlockBuilderfn BodyBuilder::attr_if(self : BodyBuilder, key : String, value : HCLValue, cond : Bool) -> BodyBuilderpub(all) struct Conditional {
condition : Expression
true_expr : Expression
false_expr : Expression
} derive(Eq)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)
} derive(Eq)pub struct FieldSchema {
schema : TypeSchema
required : Bool
description : String
} derive(Eq, Debug)pub struct FieldSchemaEx {
base : FieldSchema
validators : Array[(HCLValue, String) -> Array[HCLError]]
}fn FieldSchemaEx::add_validator(self : FieldSchemaEx, v : (HCLValue, String) -> Array[HCLError]) -> FieldSchemaExpub(all) struct ForListExpr {
var_name : String
collection : Expression
value_expr : Expression
filter : Expression?
} derive(Eq)pub(all) struct ForObjectExpr {
key_var : String
value_var : String
collection : Expression
key_expr : Expression
value_expr : Expression
filter : Expression?
} derive(Eq)fn HCLObjectBuilder::entry(self : HCLObjectBuilder, key : String, value : HCLValue) -> HCLObjectBuilderfn[T : ToHCL] HCLObjectBuilder::entry_hcl(self : HCLObjectBuilder, key : String, value : T) -> HCLObjectBuilderfn HCLObjectBuilder::entry_if(self : HCLObjectBuilder, key : String, value : HCLValue, cond : Bool) -> HCLObjectBuilderfn[T : ToHCL] HCLObjectBuilder::entry_option(self : HCLObjectBuilder, key : String, value : T?) -> HCLObjectBuilderfn HCLObjectBuilder::extend(self : HCLObjectBuilder, other : Map[String, HCLValue]) -> HCLObjectBuilderpub(all) struct Heredoc {
delimiter : String
content : String
strip_mode : HeredocStripMode
} derive(Eq)pub struct Lexer {
input : String
pos : Int
line : Int
col : Int
}pub(all) enum N {
PosInt(UInt64)
NegInt(Int64)
Float(Double)
}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)pub(all) enum TypeSchema {
Any
NullSchema
BoolSchema
IntSchema
Int64Schema
FloatSchema
NumberSchema
StringSchema
ArraySchema(TypeSchema)
ObjectSchema(Map[String, FieldSchema])
} derive(Eq, Debug)fn from_hcl_with_schema_full(input : String, schema : TypeSchema) -> Result[HCLValue, Array[HCLError]]fn is_id_continue(ch : Char) -> Boolfn is_id_start(ch : Char) -> Boolfn is_ident(s : String) -> Boolfn substring(s : String, start : Int, end : Int) -> StringInstall
Download zipHCL parser, formatter, and serialization library for MoonBit