HCL parser, formatter, and serialization library for MoonBit
moon test -F "spec fixture *" # all 14 fixture tests
moon test -F "spec fixture comments *"
moon test -F "spec fixture expressions *"
moon test -F "spec fixture structure *"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)
// Evaluate expressions
let expr = hcl.parse("x = 1 + 2 * 3").unwrap()
let result = hcl.simplify_body(expr)moon add github:lenitain/hcl{
"dependencies": {
"hcl": "github:lenitain/hcl"
}
}# 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 |
| Deserialize | from_hcl_body(String) -> HCLResult[Body], from_hcl_with_schema(Body, FieldSchema) -> HCLResult[...], from_hcl_with_body_schema(Body, BodySchema) -> HCLResult[ExtractedBody] |
| 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) |
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
}pub(all) struct BinaryOp {
left : Expression
op : BinaryOperator
right : Expression
} derive(Eq, Debug)fn BlockBuilder::attr_if(self : BlockBuilder, key : String, value : Expression, cond : Bool) -> BlockBuilderpub struct BlockSchema {
required : Bool
max_items : Int?
labels : Array[LabelSchema]
body : BodySchema
} derive(Eq, Debug)fn BodyBuilder::attr_if(self : BodyBuilder, key : String, value : Expression, cond : Bool) -> BodyBuilderpub struct BodySchema {
attrs : Map[String, AttrSchema]
blocks : Map[String, BlockSchema]
extra_attrs : Bool
extra_blocks : Bool
} derive(Eq, Debug)pub(all) struct Conditional {
condition : Expression
true_expr : Expression
false_expr : Expression
} derive(Eq, Debug)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)pub struct ExtractedBody {
attrs : Map[String, HCLValue]
blocks : Map[String, Array[ExtractedBlock]]
extra_blocks : Array[ExtractedBlock]
} derive(Eq, Debug)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, Debug)pub(all) struct ForObjectExpr {
key_var : String
value_var : String
collection : Expression
key_expr : Expression
value_expr : Expression
filter : Expression?
} derive(Eq, Debug)fn FuncDefBuilder::build(self : FuncDefBuilder, name : String, func : (Array[HCLValue]) -> Result[HCLValue, HCLError]) -> FuncDefpub(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)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, Debug)pub struct Lexer {
input : String
pos : Int
line : Int
col : Int
}pub(all) enum N {
PosInt(UInt64)
NegInt(Int64)
Float(Double)
}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)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) struct Traversal {
base : Expression
operators : Array[TraversalOperator]
} 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_body_schema(input : String, schema : BodySchema) -> Result[ExtractedBody, Array[HCLError]]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