///|
/// HCL Serialization - convert MoonBit types to HCL
///|
/// Serialize Int to HCL string
///
/// ```mbt check
/// test {
/// assert_eq(to_hcl_int(42), "42")
/// }
/// ```
pub fn to_hcl_int(value : Int) -> String {
format_hcl_value(Number(Number::from_int(value), Decor::empty()), 0)
}
///|
/// Serialize String to HCL string
///
/// ```mbt check
/// test {
/// assert_eq(to_hcl_string("hi"), "\"hi\"")
/// }
/// ```
pub fn to_hcl_string(value : String) -> String {
format_hcl_value(String(value, Decor::empty()), 0)
}
///|
/// Serialize Bool to HCL string
///
/// ```mbt check
/// test {
/// assert_eq(to_hcl_bool(true), "true")
/// assert_eq(to_hcl_bool(false), "false")
/// }
/// ```
pub fn to_hcl_bool(value : Bool) -> String {
format_hcl_value(Bool(value, Decor::empty()), 0)
}
///|
/// Serialize HCLValue to HCL string
///
/// ```mbt check
/// test {
/// assert_eq(to_hcl_value(hcl_int(1)), "1")
/// assert_eq(to_hcl_value(hcl_str("x")), "\"x\"")
/// }
/// ```
pub fn to_hcl_value(value : HCLValue) -> String {
format_hcl_value(value, 0)
}
///|
/// Serialize Body to HCL string
///
/// ```mbt check
/// test {
/// let body = parse("a = 1").unwrap()
/// assert_eq(to_hcl_body(body), "a = 1")
/// }
/// ```
pub fn to_hcl_body(body : Body) -> String {
format_body(body)
}
///|
/// Format HCL value to string
fn format_hcl_value(value : HCLValue, indent : Int) -> String {
let prefix = repeat_string(" ", indent)
match value {
Null(_) => "null"
Bool(b, _) => if b { "true" } else { "false" }
Number(n, _) => n.to_string()
String(s, _) => escape_hcl_string(s)
Array(arr, _) =>
if arr.is_empty() {
"[]"
} else {
let items = arr.map(fn(v) { format_hcl_value(v, indent + 1) })
"[\n" +
prefix +
" " +
items.join(",\n" + prefix + " ") +
"\n" +
prefix +
"]"
}
Object(obj, _) =>
if obj.is_empty() {
"{}"
} else {
let items = []
for k, v in obj {
items.push(
prefix +
" " +
escape_hcl_string(k) +
" = " +
format_hcl_value(v, indent + 1),
)
}
"{\n" + items.join("\n") + "\n" + prefix + "}"
}
Unknown(_) => "unknown"
}
}
///|
/// Format HCL Body to string
///
/// ```mbt check
/// test {
/// let body = parse("a = 1").unwrap()
/// assert_eq(format_body(body), "a = 1")
/// }
/// ```
pub fn format_body(body : Body) -> String {
let lines = []
for item in body.get_items() {
match item {
Attribute(attr) =>
lines.push(
attr.get_key() +
" = " +
format_hcl_value(expr_to_hcl_value(attr.get_value()), 0),
)
Block(block) => {
let labels = block.get_labels()
let block_header = if labels.is_empty() {
block.get_type_name()
} else {
block.get_type_name() +
" " +
labels.map(fn(l) { escape_hcl_string(l) }).join(" ")
}
lines.push(
block_header + " {\n" + format_body(block.get_body()) + "\n}",
)
}
}
}
lines.join("\n")
}
///|
/// Format Body with decor
///
/// ```mbt check
/// test {
/// let body = parse("a = 1").unwrap()
/// assert_eq(format_body_with_decor(body), "a = 1")
/// }
/// ```
pub fn format_body_with_decor(body : Body) -> String {
let mut result = ""
match body.decor.get_prefix() {
Some(prefix) => result = result + prefix
None => ()
}
for item in body.get_items() {
result = result + format_body_item_with_decor(item)
}
match body.decor.get_suffix() {
Some(suffix) => result = result + suffix
None => ()
}
result
}
///|
/// Format BodyItem with decor
fn format_body_item_with_decor(item : BodyItem) -> String {
match item {
Attribute(attr) => format_attr_with_decor(attr)
Block(block) => format_block_with_decor(block)
}
}
///|
/// Format Block with decor
fn format_block_with_decor(block : Block) -> String {
let mut result = ""
match block.decor.get_prefix() {
Some(prefix) => result = result + prefix
None => ()
}
let type_decor = block.type_name.get_decor()
match type_decor.get_prefix() {
Some(tp) => result = result + tp
None => ()
}
result = result + block.type_name.get_value()
match type_decor.get_suffix() {
Some(ts) => result = result + ts
None => ()
}
for label in block.labels {
result = result + " "
let ld = label.get_decor()
match ld.get_prefix() {
Some(lp) => result = result + lp
None => ()
}
result = result + escape_hcl_string(label.get_value())
match ld.get_suffix() {
Some(ls) => result = result + ls
None => ()
}
}
result = result + " {\n"
result = result + format_body_with_decor(block.body)
result = result + "\n}"
match block.decor.get_suffix() {
Some(suffix) => result = result + suffix
None => ()
}
result
}
///|
/// Format Attr with decor
///
/// ```mbt check
/// test {
/// let a = Attr::new("x", expr_int(1))
/// assert_eq(format_attr_with_decor(a), "x = 1")
/// }
/// ```
pub fn format_attr_with_decor(attr : Attr) -> String {
let mut result = ""
match attr.decor.get_prefix() {
Some(prefix) => result = result + prefix
None => ()
}
let key_decor = attr.key.get_decor()
match key_decor.get_prefix() {
Some(key_prefix) => result = result + key_prefix
None => ()
}
result = result + attr.key.get_value()
match key_decor.get_suffix() {
Some(key_suffix) => result = result + key_suffix
None => ()
}
result = result + " = "
result = result + format_value_with_decor(expr_to_hcl_value(attr.get_value()))
match attr.decor.get_suffix() {
Some(suffix) => result = result + suffix
None => ()
}
result
}
///|
/// Format HCLValue with decor
///
/// ```mbt check
/// test {
/// assert_eq(format_value_with_decor(hcl_int(1)), "1")
/// }
/// ```
pub fn format_value_with_decor(value : HCLValue) -> String {
let mut result = ""
match value.get_decor().get_prefix() {
Some(prefix) => result = result + prefix
None => ()
}
result = result + format_value_content(value)
match value.get_decor().get_suffix() {
Some(suffix) => result = result + suffix
None => ()
}
result
}
///|
/// Format HCLValue content without decor
///
/// ```mbt check
/// test {
/// assert_eq(format_value_content(hcl_str("hi")), "\"hi\"")
/// assert_eq(format_value_content(hcl_null()), "null")
/// }
/// ```
pub fn format_value_content(value : HCLValue) -> String {
match value {
Null(_) => "null"
Bool(b, _) => if b { "true" } else { "false" }
Number(n, _) => n.to_string()
String(s, _) => escape_hcl_string(s)
Array(arr, _) =>
if arr.is_empty() {
"[]"
} else {
let items = arr.map(fn(v) { format_value_with_decor(v) })
"[" + items.join(", ") + "]"
}
Object(obj, _) =>
if obj.is_empty() {
"{}"
} else {
let items = []
for k, v in obj {
items.push(escape_hcl_string(k) + " = " + format_value_with_decor(v))
}
"{" + items.join(", ") + "}"
}
Unknown(_) => "unknown"
}
}
///|
/// Escape a string for HCL
///
/// ```mbt check
/// 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}\"")
/// }
/// ```
pub fn escape_hcl_string(s : String) -> String {
let mut result = "\""
let len = s.length()
let mut i = 0
while i < len {
let c = s[i]
if c == '$'.to_int().to_uint16() {
if i + 1 < len && s[i + 1] == '{'.to_int().to_uint16() {
result = result + "$${"
i = i + 2
} else {
result = result + "$"
i = i + 1
}
} else if c == '%'.to_int().to_uint16() {
if i + 1 < len && s[i + 1] == '{'.to_int().to_uint16() {
result = result + "%%{"
i = i + 2
} else {
result = result + "%"
i = i + 1
}
} else if c == '"'.to_int().to_uint16() {
result = result + "\\\""
i = i + 1
} else if c == '\\'.to_int().to_uint16() {
result = result + "\\\\"
i = i + 1
} else if c == '\n'.to_int().to_uint16() {
result = result + "\\n"
i = i + 1
} else if c == '\r'.to_int().to_uint16() {
result = result + "\\r"
i = i + 1
} else if c == '\t'.to_int().to_uint16() {
result = result + "\\t"
i = i + 1
} else if c == '\b'.to_int().to_uint16() {
result = result + "\\b"
i = i + 1
} else if c == '\f'.to_int().to_uint16() {
result = result + "\\f"
i = i + 1
} else {
result = result + c.to_int().unsafe_to_char().to_string()
i = i + 1
}
}
result + "\""
}
///|
/// Repeat a string n times
fn repeat_string(s : String, n : Int) -> String {
let mut result = ""
for _ in 0.. Bool {
is_ident(s)
}
///|
/// Format configuration for HCL output
///
/// ```mbt check
/// test {
/// let c = FormatConfig::default()
/// assert_eq(c.indent, " ")
/// assert_eq(c.dense, false)
/// }
/// ```
pub struct FormatConfig {
indent : String
dense : Bool
compact_arrays : Bool
compact_objects : Bool
prefer_ident_keys : Bool
} derive(Debug, Eq)
///|
/// Create default FormatConfig (2-space indent, all options false)
///
/// ```mbt check
/// test {
/// let c = FormatConfig::default()
/// assert_eq(c.indent, " ")
/// assert_eq(c.compact_arrays, false)
/// }
/// ```
pub fn FormatConfig::default() -> FormatConfig {
{
indent: " ",
dense: false,
compact_arrays: false,
compact_objects: false,
prefer_ident_keys: false,
}
}
///|
/// Create compact FormatConfig (inline arrays/objects)
///
/// ```mbt check
/// test {
/// let c = FormatConfig::compact()
/// assert_eq(c.dense, true)
/// assert_eq(c.compact_arrays, true)
/// assert_eq(c.prefer_ident_keys, true)
/// }
/// ```
pub fn FormatConfig::compact() -> FormatConfig {
{
indent: " ",
dense: true,
compact_arrays: true,
compact_objects: true,
prefer_ident_keys: true,
}
}
///|
/// Create dense FormatConfig (no empty lines between blocks)
///
/// ```mbt check
/// test {
/// let c = FormatConfig::dense()
/// assert_eq(c.dense, true)
/// assert_eq(c.compact_arrays, false)
/// }
/// ```
pub fn FormatConfig::dense() -> FormatConfig {
{
indent: " ",
dense: true,
compact_arrays: false,
compact_objects: false,
prefer_ident_keys: false,
}
}
///|
/// Formatter for HCL output with configuration
///
/// ```mbt check
/// test {
/// let fmt = Formatter::new()
/// assert_eq(fmt.format_value(hcl_int(1)), "1")
/// }
/// ```
pub struct Formatter {
config : FormatConfig
}
///|
/// Create Formatter with default config
///
/// ```mbt check
/// test {
/// let fmt = Formatter::new()
/// assert_eq(fmt.get_config().indent, " ")
/// }
/// ```
pub fn Formatter::new() -> Formatter {
{ config: FormatConfig::default() }
}
///|
/// Create Formatter with given config
///
/// ```mbt check
/// test {
/// let fmt = Formatter::with_config(FormatConfig::compact())
/// assert_eq(fmt.get_config().dense, true)
/// }
/// ```
pub fn Formatter::with_config(config : FormatConfig) -> Formatter {
{ config, }
}
///|
/// Set indent string
///
/// ```mbt check
/// test {
/// let fmt = Formatter::new().set_indent(" ")
/// assert_eq(fmt.get_config().indent, " ")
/// }
/// ```
pub fn Formatter::set_indent(self : Formatter, indent : String) -> Formatter {
{ config: { ..self.config, indent, } }
}
///|
/// Set dense mode
///
/// ```mbt check
/// test {
/// let fmt = Formatter::new().set_dense(true)
/// assert_eq(fmt.get_config().dense, true)
/// }
/// ```
pub fn Formatter::set_dense(self : Formatter, dense : Bool) -> Formatter {
{ config: { ..self.config, dense, } }
}
///|
/// Set compact arrays mode
///
/// ```mbt check
/// test {
/// let fmt = Formatter::new().set_compact_arrays(true)
/// assert_eq(fmt.get_config().compact_arrays, true)
/// }
/// ```
pub fn Formatter::set_compact_arrays(
self : Formatter,
compact_arrays : Bool,
) -> Formatter {
{ config: { ..self.config, compact_arrays, } }
}
///|
/// Set compact objects mode
///
/// ```mbt check
/// test {
/// let fmt = Formatter::new().set_compact_objects(true)
/// assert_eq(fmt.get_config().compact_objects, true)
/// }
/// ```
pub fn Formatter::set_compact_objects(
self : Formatter,
compact_objects : Bool,
) -> Formatter {
{ config: { ..self.config, compact_objects, } }
}
///|
/// Set prefer ident keys mode
///
/// ```mbt check
/// test {
/// let fmt = Formatter::new().set_prefer_ident_keys(true)
/// assert_eq(fmt.get_config().prefer_ident_keys, true)
/// }
/// ```
pub fn Formatter::set_prefer_ident_keys(
self : Formatter,
prefer_ident_keys : Bool,
) -> Formatter {
{ config: { ..self.config, prefer_ident_keys, } }
}
///|
/// Get the formatter config
///
/// ```mbt check
/// test {
/// let fmt = Formatter::new()
/// assert_eq(fmt.get_config().indent, " ")
/// }
/// ```
pub fn Formatter::get_config(self : Formatter) -> FormatConfig {
self.config
}
///|
/// Format HCLValue using formatter config
///
/// ```mbt check
/// test {
/// let fmt = Formatter::new().set_compact_arrays(true)
/// assert_eq(fmt.format_value(hcl_array([hcl_int(1), hcl_int(2)])), "[1, 2]")
/// }
/// ```
pub fn Formatter::format_value(self : Formatter, value : HCLValue) -> String {
self.format_hcl_value_impl(value, 0)
}
///|
/// Format Body using formatter config
///
/// ```mbt check
/// test {
/// let fmt = Formatter::new().set_prefer_ident_keys(true)
/// let body = parse("a = 1").unwrap()
/// assert_eq(fmt.format_body(body), "a = 1")
/// }
/// ```
pub fn Formatter::format_body(self : Formatter, body : Body) -> String {
self.format_body_impl(body, 0)
}
///|
/// Format key for object/attribute (respecting prefer_ident_keys)
fn Formatter::format_key(self : Formatter, key : String) -> String {
if self.config.prefer_ident_keys && is_valid_ident_key(key) {
key
} else {
escape_hcl_string(key)
}
}
///|
/// Internal: format HCLValue with config and indent level
fn Formatter::format_hcl_value_impl(
self : Formatter,
value : HCLValue,
indent_level : Int,
) -> String {
let prefix = repeat_string(self.config.indent, indent_level)
match value {
Null(_) => "null"
Bool(b, _) => if b { "true" } else { "false" }
Number(n, _) => n.to_string()
String(s, _) => escape_hcl_string(s)
Array(arr, _) =>
if arr.is_empty() {
"[]"
} else if self.config.compact_arrays {
let items = arr.map(fn(v) {
self.format_hcl_value_impl(v, indent_level)
})
"[" + items.join(", ") + "]"
} else {
let items = arr.map(fn(v) {
self.format_hcl_value_impl(v, indent_level + 1)
})
"[\n" +
prefix +
self.config.indent +
items.join(",\n" + prefix + self.config.indent) +
"\n" +
prefix +
"]"
}
Object(obj, _) =>
if obj.is_empty() {
"{}"
} else if self.config.compact_objects {
let items = []
for k, v in obj {
items.push(
self.format_key(k) +
" = " +
self.format_hcl_value_impl(v, indent_level),
)
}
"{ " + items.join(", ") + " }"
} else {
let items = []
for k, v in obj {
items.push(
prefix +
self.config.indent +
self.format_key(k) +
" = " +
self.format_hcl_value_impl(v, indent_level + 1),
)
}
"{\n" + items.join("\n") + "\n" + prefix + "}"
}
Unknown(_) => "unknown"
}
}
///|
/// Internal: format Body with config and indent level
fn Formatter::format_body_impl(
self : Formatter,
body : Body,
indent_level : Int,
) -> String {
let prefix = repeat_string(self.config.indent, indent_level)
let lines = []
for item in body.get_items() {
match item {
Attribute(attr) =>
lines.push(
prefix +
self.format_key(attr.get_key()) +
" = " +
self.format_hcl_value_impl(
expr_to_hcl_value(attr.get_value()),
indent_level,
),
)
Block(block) => {
let labels = block.get_labels()
let block_header = if labels.is_empty() {
block.get_type_name()
} else {
block.get_type_name() +
" " +
labels.map(fn(l) { escape_hcl_string(l) }).join(" ")
}
let inner = self.format_body_impl(block.get_body(), indent_level + 1)
lines.push(prefix + block_header + " {\n" + inner + "\n" + prefix + "}")
}
}
}
if self.config.dense {
lines.join("\n")
} else {
lines.join("\n\n")
}
}
///|
/// Create Int HCLValue
///
/// ```mbt check
/// test {
/// assert_eq(hcl_int(42).as_int().unwrap(), 42)
/// }
/// ```
pub fn hcl_int(v : Int) -> HCLValue {
Number(Number::from_int(v), Decor::empty())
}
///|
/// Create Int64 HCLValue
///
/// ```mbt check
/// test {
/// assert_eq(hcl_int64(7L).as_int64().unwrap(), 7L)
/// }
/// ```
pub fn hcl_int64(v : Int64) -> HCLValue {
Number(Number::from_int64(v), Decor::empty())
}
///|
/// Create Float HCLValue
///
/// ```mbt check
/// test {
/// assert_eq(hcl_float(1.5).as_float().unwrap(), 1.5)
/// }
/// ```
pub fn hcl_float(v : Double) -> HCLValue {
Number(Number::from_finite_f64(v), Decor::empty())
}
///|
/// Create Bool HCLValue
///
/// ```mbt check
/// test {
/// assert_eq(hcl_bool(true).as_bool().unwrap(), true)
/// }
/// ```
pub fn hcl_bool(v : Bool) -> HCLValue {
Bool(v, Decor::empty())
}
///|
/// Create String HCLValue
///
/// ```mbt check
/// test {
/// assert_eq(hcl_str("hi").as_string().unwrap(), "hi")
/// }
/// ```
pub fn hcl_str(v : String) -> HCLValue {
String(v, Decor::empty())
}
///|
/// Create Null HCLValue
///
/// ```mbt check
/// test {
/// assert_true(hcl_null().is_null())
/// }
/// ```
pub fn hcl_null() -> HCLValue {
Null(Decor::empty())
}
///|
/// Create Array HCLValue
///
/// ```mbt check
/// test {
/// let a = hcl_array([hcl_int(1), hcl_int(2)])
/// assert_eq(a.as_array().unwrap().length(), 2)
/// }
/// ```
pub fn hcl_array(items : Array[HCLValue]) -> HCLValue {
Array(items, Decor::empty())
}
///|
/// Create Object HCLValue
///
/// ```mbt check
/// test {
/// let o = hcl_object({ "a": hcl_int(1) })
/// assert_eq(o.as_object().unwrap()["a"].as_int().unwrap(), 1)
/// }
/// ```
pub fn hcl_object(entries : HCLObject) -> HCLValue {
Object(entries, Decor::empty())
}
///|
/// Encode a value as an HCL attribute (key = name)
///
/// ```mbt check
/// test {
/// let attr = encode_attr("port", 8080)
/// assert_eq(attr.get_key(), "port")
/// assert_eq(expr_to_string(attr.get_value()), "8080")
/// }
/// ```
pub fn[T : ToHCL] encode_attr(key : String, value : T) -> Attr {
Attr::new(key, hcl_value_to_expression(value.to_hcl()))
}
///|
/// Encode an optional value as an attribute (None produces no attribute)
///
/// ```mbt check
/// 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)
/// }
/// ```
pub fn[T : ToHCL] encode_opt_attr(key : String, value : T?) -> Attr? {
match value {
Some(v) => Some(encode_attr(key, v))
None => None
}
}
///|
/// Encode a value as a labeled HCL block (value must encode to an object)
///
/// ```mbt check
/// 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")
/// }
/// ```
pub fn[T : ToHCL] encode_block(
type_name : String,
labels : Array[String],
value : T,
) -> HCLResult[Block] {
match value.to_hcl() {
Object(obj, _) => {
let items = []
for k, v in obj {
items.push(
BodyItem::Attribute(Attr::new(k, hcl_value_to_expression(v))),
)
}
Ok(Block::new(type_name, labels, Body::from_items(items)))
}
_ =>
Err(
HCLError::type_error(
"encode_block: value must encode to an HCL object to form a block body",
),
)
}
}
///|
/// Encode values as repeated labeled HCL blocks
///
/// ```mbt check
/// 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",
/// )
/// }
/// ```
pub fn[T : ToHCL] encode_blocks(
type_name : String,
labels : Array[String],
values : Array[T],
) -> HCLResult[Array[Block]] {
let result = []
for value in values {
match encode_block(type_name, labels, value) {
Ok(block) => result.push(block)
Err(e) => return Err(e)
}
}
Ok(result)
}