1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
//! Value enum for heterogeneous property types in Gram notation
use std::fmt;
/// Represents all possible value types in Gram notation property records.
/// Supports all value types defined in the tree-sitter-gram grammar.
#[derive(Debug, Clone)]
pub enum Value {
/// Unquoted or quoted string
/// Example: `"Alice"`, `hello`
String(String),
/// Integer value with full i64 range
/// Example: `42`, `-10`, `0`
Integer(i64),
/// Decimal/floating-point value
/// Example: `3.14`, `-2.5`, `0.0`
Decimal(f64),
/// Boolean value
/// Example: `true`, `false`
Boolean(bool),
/// Array of values (may be heterogeneous)
/// Example: `["rust", 42, true]`
Array(Vec<Value>),
/// Numeric range with inclusive bounds
/// Example: `1..10`, `0..100`
Range { lower: i64, upper: i64 },
/// Tagged string with format identifier
/// Example: `"""markdown # Heading"""`
TaggedString { tag: String, content: String },
}
impl Value {
// TODO: tree-sitter parsing methods removed during nom parser migration
// Value parsing is now handled by parser::value module
/* Commented out during migration to nom parser
pub fn from_tree_sitter_node_OLD(
node: &TREE_SITTER_NODE,
source: &str,
) -> Result<Self, ParseError> {
match node.kind() {
"symbol" => {
let text = node
.utf8_text(source.as_bytes())
.map_err(|e| Self::node_parse_error(node, format!("UTF-8 error: {}", e)))?;
Ok(Value::String(text.to_string()))
}
"string_literal" => {
let content = extract_string_content(node, source)?;
Ok(Value::String(content))
}
"integer" => {
let text = node
.utf8_text(source.as_bytes())
.map_err(|e| Self::node_parse_error(node, format!("UTF-8 error: {}", e)))?;
let value = text
.parse::<i64>()
.map_err(|e| Self::node_parse_error(node, format!("Invalid integer: {}", e)))?;
Ok(Value::Integer(value))
}
"decimal" => {
let text = node
.utf8_text(source.as_bytes())
.map_err(|e| Self::node_parse_error(node, format!("UTF-8 error: {}", e)))?;
let value = text
.parse::<f64>()
.map_err(|e| Self::node_parse_error(node, format!("Invalid decimal: {}", e)))?;
Ok(Value::Decimal(value))
}
"boolean_literal" => {
let text = node
.utf8_text(source.as_bytes())
.map_err(|e| Self::node_parse_error(node, format!("UTF-8 error: {}", e)))?;
let value = text == "true";
Ok(Value::Boolean(value))
}
"array" => {
let mut values = Vec::new();
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.is_named() && child.kind() != "," {
values.push(Value::from_tree_sitter_node(&child, source)?);
}
}
Ok(Value::Array(values))
}
"range" => {
let lower = extract_range_bound(node, "lower", source)?;
let upper = extract_range_bound(node, "upper", source)?;
Ok(Value::Range { lower, upper })
}
"tagged_string" => {
let (tag, content) = extract_tagged_string(node, source)?;
Ok(Value::TaggedString { tag, content })
}
_ => panic!("tree-sitter parsing no longer supported"),
}
}
*/
// End of commented tree-sitter code
/// Serialize value to gram notation
pub fn to_gram_notation(&self) -> String {
match self {
// Strings are always quoted in gram notation property values
Value::String(s) => format!("\"{}\"", escape_string(s)),
Value::Integer(i) => i.to_string(),
Value::Decimal(f) => format_decimal(*f),
Value::Boolean(b) => b.to_string(),
Value::Array(values) => {
let items: Vec<String> = values.iter().map(|v| v.to_gram_notation()).collect();
format!("[{}]", items.join(", "))
}
Value::Range { lower, upper } => format!("{}..{}", lower, upper),
Value::TaggedString { tag, content } => {
if tag.is_empty() {
format!("\"\"\"{}\"\"\"", content)
} else {
// Use backtick format: tag`content` (the format the parser actually handles).
// Escape backslashes first, then backticks — order matters: if backticks were
// escaped first, the newly inserted backslashes would be double-escaped on the
// second pass, corrupting content that contains a literal backslash before a
// backtick (e.g. "\`" → "\\`" → "\\\`" instead of "\\\\`").
let escaped = content.replace('\\', "\\\\").replace('`', "\\`");
format!("{}`{}`", tag, escaped)
}
}
}
}
/// Get the type name of this value (for error messages)
pub fn type_name(&self) -> &'static str {
match self {
Value::String(_) => "string",
Value::Integer(_) => "integer",
Value::Decimal(_) => "decimal",
Value::Boolean(_) => "boolean",
Value::Array(_) => "array",
Value::Range { .. } => "range",
Value::TaggedString { .. } => "tagged string",
}
}
// TODO: node_parse_error removed during migration
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_gram_notation())
}
}
impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Value::String(a), Value::String(b)) => a == b,
(Value::Integer(a), Value::Integer(b)) => a == b,
(Value::Decimal(a), Value::Decimal(b)) => {
// Use epsilon comparison for floats
(a - b).abs() < f64::EPSILON
}
(Value::Boolean(a), Value::Boolean(b)) => a == b,
(Value::Array(a), Value::Array(b)) => a == b,
(
Value::Range {
lower: l1,
upper: u1,
},
Value::Range {
lower: l2,
upper: u2,
},
) => l1 == l2 && u1 == u2,
(
Value::TaggedString {
tag: t1,
content: c1,
},
Value::TaggedString {
tag: t2,
content: c2,
},
) => t1 == t2 && c1 == c2,
_ => false,
}
}
}
// Helper Functions
/// Escape special characters in strings
pub(crate) fn escape_string(s: &str) -> String {
s.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
.replace('\t', "\\t")
.replace('\r', "\\r")
}
/// Format decimal to avoid unnecessary trailing zeros while distinguishing from integers
pub(crate) fn format_decimal(f: f64) -> String {
if f.fract() == 0.0 && f.is_finite() {
format!("{:.1}", f) // Always include .0 to distinguish from integer
} else {
f.to_string()
}
}
// TODO: tree-sitter helper functions removed during migration to nom parser
// Value parsing is now handled by parser::value module
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_string_value_serialization() {
// Strings are always quoted in gram notation property values
assert_eq!(
Value::String("hello".to_string()).to_gram_notation(),
"\"hello\""
);
assert_eq!(
Value::String("Hello World".to_string()).to_gram_notation(),
"\"Hello World\""
);
assert_eq!(Value::String("".to_string()).to_gram_notation(), "\"\"");
}
#[test]
fn test_integer_value_serialization() {
assert_eq!(Value::Integer(42).to_gram_notation(), "42");
assert_eq!(Value::Integer(-10).to_gram_notation(), "-10");
assert_eq!(Value::Integer(0).to_gram_notation(), "0");
}
#[test]
fn test_decimal_value_serialization() {
assert_eq!(Value::Decimal(3.14).to_gram_notation(), "3.14");
assert_eq!(Value::Decimal(0.0).to_gram_notation(), "0.0");
assert_eq!(Value::Decimal(-2.5).to_gram_notation(), "-2.5");
}
#[test]
fn test_boolean_value_serialization() {
assert_eq!(Value::Boolean(true).to_gram_notation(), "true");
assert_eq!(Value::Boolean(false).to_gram_notation(), "false");
}
#[test]
fn test_array_value_serialization() {
let v = Value::Array(vec![
Value::Integer(1),
Value::Integer(2),
Value::Integer(3),
]);
assert_eq!(v.to_gram_notation(), "[1, 2, 3]");
// Heterogeneous array
let v = Value::Array(vec![
Value::String("rust".to_string()),
Value::Integer(42),
Value::Boolean(true),
]);
// Strings are always quoted
assert_eq!(v.to_gram_notation(), "[\"rust\", 42, true]");
// Empty array
assert_eq!(Value::Array(vec![]).to_gram_notation(), "[]");
}
#[test]
fn test_range_value_serialization() {
let v = Value::Range {
lower: 1,
upper: 10,
};
assert_eq!(v.to_gram_notation(), "1..10");
let v = Value::Range {
lower: -5,
upper: 5,
};
assert_eq!(v.to_gram_notation(), "-5..5");
}
#[test]
fn test_tagged_string_serialization() {
let v = Value::TaggedString {
tag: "markdown".to_string(),
content: "# Heading".to_string(),
};
assert_eq!(v.to_gram_notation(), "markdown`# Heading`");
let v = Value::TaggedString {
tag: String::new(),
content: "Plain text".to_string(),
};
assert_eq!(v.to_gram_notation(), "\"\"\"Plain text\"\"\"");
// Verify backtick and backslash escaping in content
let v = Value::TaggedString {
tag: "h3".to_string(),
content: "8f283082aa20c00".to_string(),
};
assert_eq!(v.to_gram_notation(), "h3`8f283082aa20c00`");
let v = Value::TaggedString {
tag: "raw".to_string(),
content: "has`backtick".to_string(),
};
assert_eq!(v.to_gram_notation(), "raw`has\\`backtick`");
let v = Value::TaggedString {
tag: "raw".to_string(),
content: "has\\backslash".to_string(),
};
assert_eq!(v.to_gram_notation(), "raw`has\\\\backslash`");
// Backslash immediately before a backtick: both must be escaped independently.
let v = Value::TaggedString {
tag: "raw".to_string(),
content: "end\\`here".to_string(),
};
assert_eq!(v.to_gram_notation(), "raw`end\\\\\\`here`");
}
#[test]
fn test_value_type_names() {
assert_eq!(Value::String("".to_string()).type_name(), "string");
assert_eq!(Value::Integer(0).type_name(), "integer");
assert_eq!(Value::Decimal(0.0).type_name(), "decimal");
assert_eq!(Value::Boolean(false).type_name(), "boolean");
assert_eq!(Value::Array(vec![]).type_name(), "array");
assert_eq!(Value::Range { lower: 0, upper: 0 }.type_name(), "range");
assert_eq!(
Value::TaggedString {
tag: String::new(),
content: String::new()
}
.type_name(),
"tagged string"
);
}
#[test]
fn test_value_equality() {
assert_eq!(Value::Integer(42), Value::Integer(42));
assert_ne!(Value::Integer(42), Value::Integer(43));
assert_ne!(Value::Integer(42), Value::String("42".to_string()));
// Decimal epsilon comparison
assert_eq!(Value::Decimal(1.0), Value::Decimal(1.0));
// Arrays
assert_eq!(
Value::Array(vec![Value::Integer(1), Value::Integer(2)]),
Value::Array(vec![Value::Integer(1), Value::Integer(2)])
);
}
#[test]
fn test_escape_string() {
assert_eq!(escape_string("hello"), "hello");
assert_eq!(escape_string("hello\"world"), "hello\\\"world");
assert_eq!(escape_string("line1\nline2"), "line1\\nline2");
assert_eq!(escape_string("tab\there"), "tab\\there");
assert_eq!(escape_string("back\\slash"), "back\\\\slash");
}
#[test]
fn test_format_decimal() {
assert_eq!(format_decimal(3.14), "3.14");
assert_eq!(format_decimal(0.0), "0.0");
assert_eq!(format_decimal(1.0), "1.0");
assert_eq!(format_decimal(-2.5), "-2.5");
}
}