///|
/// HCL JSON Conversion - convert HCL to JSON format
///|
/// Convert HCL string to JSON string
///
/// ```mbt check
/// 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\"}",
/// )
/// }
/// ```
pub fn hcl_to_json(input : String) -> HCLResult[String] {
match parse(input) {
Ok(body) => Ok(body_to_json(body))
Err(e) => Err(e)
}
}
///|
/// Convert HCL string to JSON string with pretty printing
///
/// ```mbt check
/// test {
/// assert_eq(hcl_to_json_pretty("a = 1").unwrap(), "{\n \"a\": 1\n}")
/// }
/// ```
pub fn hcl_to_json_pretty(
input : String,
indent? : Int = 2,
) -> HCLResult[String] {
match parse(input) {
Ok(body) => Ok(body_to_json_pretty(body, indent~))
Err(e) => Err(e)
}
}
///|
/// Convert Body to JSON string (HCL JSON spec-compliant)
///
/// ```mbt check
/// test {
/// let body = parse("name = \"foo\"").unwrap()
/// assert_eq(body_to_json(body), "{\"name\":\"foo\"}")
/// }
/// ```
pub fn body_to_json(body : Body) -> String {
let items = body.get_items()
if items.is_empty() {
return "{}"
}
let attrs : Array[Attr] = []
let block_types : Array[(String, Array[Block])] = []
for item in items {
match item {
Attribute(attr) => attrs.push(attr)
Block(block) => {
let type_name = block.get_type_name()
let mut found = false
for i in 0.. String {
let labels = block.get_labels()
if labels.is_empty() {
body_to_json(block.get_body())
} else {
let body_json = body_to_json(block.get_body())
let mut result = body_json
let mut i = labels.length() - 1
while i >= 0 {
result = "{" + escape_json_string(labels[i]) + ":" + result + "}"
i = i - 1
}
result
}
}
///|
/// Convert Body to JSON string with pretty printing
///
/// ```mbt check
/// test {
/// let body = parse("name = \"foo\"").unwrap()
/// assert_eq(body_to_json_pretty(body), "{\n \"name\": \"foo\"\n}")
/// }
/// ```
pub fn body_to_json_pretty(body : Body, indent? : Int = 2) -> String {
body_to_json_pretty_impl(body, 0, indent)
}
///|
/// Internal implementation of pretty JSON conversion (HCL JSON spec-compliant)
fn body_to_json_pretty_impl(
body : Body,
depth : Int,
unit_width : Int,
) -> String {
let items = body.get_items()
if items.is_empty() {
return "{}"
}
let prefix = repeat_string(" ", unit_width * depth)
let inner_prefix = repeat_string(" ", unit_width * (depth + 1))
let attrs : Array[Attr] = []
let block_types : Array[(String, Array[Block])] = []
for item in items {
match item {
Attribute(attr) => attrs.push(attr)
Block(block) => {
let type_name = block.get_type_name()
let mut found = false
for i in 0.. 0 {
result = result + ",\n"
}
result = result +
item_indent +
block_to_json_value_pretty(blocks[i], depth + 2, unit_width)
}
result = result + "\n" + block_indent + "]"
}
}
result + "\n" + prefix + "}"
}
///|
/// Convert a block with labels to nested JSON value (pretty)
fn block_to_json_value_pretty(
block : Block,
depth : Int,
unit_width : Int,
) -> String {
let labels = block.get_labels()
if labels.is_empty() {
body_to_json_pretty_impl(block.get_body(), depth, unit_width)
} else {
let inner_prefix = repeat_string(" ", unit_width * (depth + 1))
let body_json = body_to_json_pretty_impl(
block.get_body(),
depth + labels.length(),
unit_width,
)
let mut result = body_json
let mut i = labels.length() - 1
while i >= 0 {
result = "{\n" +
inner_prefix +
repeat_string(" ", unit_width * (labels.length() - 1 - i)) +
escape_json_string(labels[i]) +
": " +
result +
"\n" +
repeat_string(" ", unit_width * (depth + labels.length() - 1 - i)) +
"}"
i = i - 1
}
result
}
}
///|
/// Convert HCLValue to JSON string
fn value_to_json(value : HCLValue) -> String {
match value {
Null(_) => "null"
Bool(b, _) => if b { "true" } else { "false" }
Number(n, _) => n.to_string()
String(s, _) => escape_json_string(s)
Array(arr, _) =>
if arr.is_empty() {
"[]"
} else {
let items = arr.map(fn(v) { value_to_json(v) })
"[" + items.join(",") + "]"
}
Object(obj, _) =>
if obj.is_empty() {
"{}"
} else {
let mut result = "{"
let mut first = true
for k, v in obj {
if !first {
result = result + ","
}
first = false
result = result + escape_json_string(k) + ":" + value_to_json(v)
}
result + "}"
}
Unknown(_) => "null"
}
}
///|
/// Convert HCLValue to JSON string with pretty printing
fn value_to_json_pretty(
value : HCLValue,
depth : Int,
unit_width : Int,
) -> String {
match value {
Null(_) => "null"
Unknown(_) => "null"
Bool(b, _) => if b { "true" } else { "false" }
Number(n, _) => n.to_string()
String(s, _) => escape_json_string(s)
Array(arr, _) =>
if arr.is_empty() {
"[]"
} else {
let inner_prefix = repeat_string(" ", unit_width * (depth + 1))
let items = arr.map(fn(v) {
value_to_json_pretty(v, depth + 1, unit_width)
})
"[\n" +
inner_prefix +
items.join(",\n" + inner_prefix) +
"\n" +
repeat_string(" ", unit_width * depth) +
"]"
}
Object(obj, _) =>
if obj.is_empty() {
"{}"
} else {
let inner_prefix = repeat_string(" ", unit_width * (depth + 1))
let mut result = "{\n"
let mut first = true
for k, v in obj {
if !first {
result = result + ",\n"
}
first = false
result = result +
inner_prefix +
escape_json_string(k) +
": " +
value_to_json_pretty(v, depth + 1, unit_width)
}
result + "\n" + repeat_string(" ", unit_width * depth) + "}"
}
}
}
///|
/// Escape a string for JSON
fn escape_json_string(s : String) -> String {
let mut result = "\""
for c in s {
match c {
'"' => result = result + "\\\""
'\\' => result = result + "\\\\"
'\n' => result = result + "\\n"
'\r' => result = result + "\\r"
'\t' => result = result + "\\t"
'\b' => result = result + "\\b"
'\f' => result = result + "\\f"
_ => {
let code = c.to_int()
if code < 0x20 {
result = result + "\\u" + format_hex(code, 4)
} else {
result = result + c.to_string()
}
}
}
}
result + "\""
}
///|
/// Format a number as hexadecimal with specified width
fn format_hex(value : Int, width : Int) -> String {
let hex_chars = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
]
let mut result = ""
let mut v = value
for _ in 0..