1use serde_json::Value;
8
9use super::super::feature::{
10 check_grammar_selection_included_range_data, check_grammar_selection_included_range_form,
11 check_grammar_selection_included_range_grammar, class_expression, feature_expression_fields,
12 operation_form,
13};
14use super::super::{
15 ByteClassItem, CharClassItem, FeatureExpr, FeatureForm, FieldType, FieldValue, Grammar,
16 GrammarDeclarations, GrammarExpr, GrammarFormat, GrammarImportError, GrammarLexer,
17 GrammarMacro, GrammarRule, GrammarScanner, Operation, OperationCategory, PrecedenceEntry,
18 RuleAttributes, RuleKind, UnicodeClassItem,
19};
20
21enum Json {
23 Null,
24 Bool(bool),
25 Int(i64),
26 Str(String),
27 Array(Vec<Self>),
28 Object(Vec<(&'static str, Self)>),
29}
30
31impl Json {
32 fn str(value: &str) -> Self {
33 Self::Str(value.to_owned())
34 }
35
36 fn strings(values: &[String]) -> Self {
37 Self::Array(values.iter().map(|value| Self::str(value)).collect())
38 }
39
40 fn render(&self, indent: usize, out: &mut String) {
41 match self {
42 Self::Null => out.push_str("null"),
43 Self::Bool(value) => out.push_str(if *value { "true" } else { "false" }),
44 Self::Int(value) => out.push_str(&value.to_string()),
45 Self::Str(value) => {
46 out.push_str(&serde_json::to_string(value).unwrap_or_default());
47 }
48 Self::Array(items) if items.is_empty() => out.push_str("[]"),
49 Self::Object(entries) if entries.is_empty() => out.push_str("{}"),
50 Self::Array(items) => {
51 out.push('[');
52 for (index, item) in items.iter().enumerate() {
53 out.push_str(if index == 0 { "\n" } else { ",\n" });
54 push_indent(indent + 1, out);
55 item.render(indent + 1, out);
56 }
57 out.push('\n');
58 push_indent(indent, out);
59 out.push(']');
60 }
61 Self::Object(entries) => {
62 out.push('{');
63 for (index, (key, value)) in entries.iter().enumerate() {
64 out.push_str(if index == 0 { "\n" } else { ",\n" });
65 push_indent(indent + 1, out);
66 out.push('"');
67 out.push_str(key);
68 out.push_str("\": ");
69 value.render(indent + 1, out);
70 }
71 out.push('\n');
72 push_indent(indent, out);
73 out.push('}');
74 }
75 }
76 }
77}
78
79fn push_indent(indent: usize, out: &mut String) {
80 for _ in 0..indent {
81 out.push_str(" ");
82 }
83}
84
85fn int(value: usize) -> Json {
86 Json::Int(i64::try_from(value).unwrap_or(i64::MAX))
87}
88
89fn char_json(value: char) -> Json {
90 Json::Str(value.to_string())
91}
92
93fn unary(kind: &'static str, item: &GrammarExpr) -> Json {
94 Json::Object(vec![
95 ("kind", Json::str(kind)),
96 ("item", expression_json(item)),
97 ])
98}
99
100fn class_json(kind: &'static str, negated: bool, items: Vec<Json>) -> Json {
101 Json::Object(vec![
102 ("kind", Json::str(kind)),
103 ("negated", Json::Bool(negated)),
104 ("items", Json::Array(items)),
105 ])
106}
107
108fn char_item_json(item: &CharClassItem) -> Json {
109 match item {
110 CharClassItem::Char(value) => Json::Object(vec![
111 ("kind", Json::str("char")),
112 ("value", char_json(*value)),
113 ]),
114 CharClassItem::Range(start, end) => Json::Object(vec![
115 ("kind", Json::str("range")),
116 ("start", char_json(*start)),
117 ("end", char_json(*end)),
118 ]),
119 }
120}
121
122fn expressions_json(items: &[GrammarExpr]) -> Json {
123 Json::Array(items.iter().map(expression_json).collect())
124}
125
126fn expression_json(expr: &GrammarExpr) -> Json {
127 let kind = |kind: &str| ("kind", Json::str(kind));
128 match expr {
129 GrammarExpr::Empty => Json::Object(vec![kind("empty")]),
130 GrammarExpr::AnyChar => Json::Object(vec![kind("any")]),
131 GrammarExpr::Terminal(value) => {
132 Json::Object(vec![kind("literal"), ("value", Json::str(value))])
133 }
134 GrammarExpr::TerminalInsensitive(value) => Json::Object(vec![
135 kind("literalInsensitive"),
136 ("value", Json::str(value)),
137 ]),
138 GrammarExpr::CharRange(start, end) => Json::Object(vec![
139 kind("charRange"),
140 ("start", char_json(*start)),
141 ("end", char_json(*end)),
142 ]),
143 GrammarExpr::CharClass { negated, items } => class_json(
144 "charClass",
145 *negated,
146 items.iter().map(char_item_json).collect(),
147 ),
148 GrammarExpr::NonTerminal(name) => {
149 Json::Object(vec![kind("ref"), ("name", Json::str(name))])
150 }
151 GrammarExpr::Choice {
152 ordered,
153 alternatives,
154 } => Json::Object(vec![
155 kind("choice"),
156 ("items", expressions_json(alternatives)),
157 ("ordered", Json::Bool(*ordered)),
158 ]),
159 GrammarExpr::Sequence(items) => {
160 Json::Object(vec![kind("seq"), ("items", expressions_json(items))])
161 }
162 GrammarExpr::Optional(item) => unary("optional", item),
163 GrammarExpr::ZeroOrMore(item) => unary("repeat0", item),
164 GrammarExpr::OneOrMore(item) => unary("repeat1", item),
165 GrammarExpr::And(item) => unary("and", item),
166 GrammarExpr::Not(item) => unary("not", item),
167 GrammarExpr::Repeat { expr, min, max } => Json::Object(vec![
168 kind("repeat"),
169 ("item", expression_json(expr)),
170 ("min", int(*min)),
171 ("max", max.map_or(Json::Null, int)),
172 ]),
173 GrammarExpr::Capture { label, expr } => Json::Object(vec![
174 kind("capture"),
175 ("label", label.as_deref().map_or(Json::Null, Json::str)),
176 ("item", expression_json(expr)),
177 ]),
178 GrammarExpr::Feature(feature) => feature_json(feature),
179 }
180}
181
182fn feature_json(feature: &FeatureExpr) -> Json {
183 match feature {
184 FeatureExpr::UnicodeClass { negated, items } => class_json(
185 "charClass",
186 *negated,
187 items
188 .iter()
189 .map(|item| match item {
190 UnicodeClassItem::Char(value) => char_item_json(&CharClassItem::Char(*value)),
191 UnicodeClassItem::Range(start, end) => {
192 char_item_json(&CharClassItem::Range(*start, *end))
193 }
194 UnicodeClassItem::Category(value) => Json::Object(vec![
195 ("kind", Json::str("category")),
196 ("value", Json::str(value)),
197 ]),
198 UnicodeClassItem::Script(value) => Json::Object(vec![
199 ("kind", Json::str("script")),
200 ("value", Json::str(value)),
201 ]),
202 })
203 .collect(),
204 ),
205 FeatureExpr::ByteClass { negated, items } => class_json(
206 "byteClass",
207 *negated,
208 items
209 .iter()
210 .map(|item| match item {
211 ByteClassItem::Byte(value) => Json::Object(vec![
212 ("kind", Json::str("byte")),
213 ("value", Json::Int(i64::from(*value))),
214 ]),
215 ByteClassItem::Range(start, end) => Json::Object(vec![
216 ("kind", Json::str("byteRange")),
217 ("start", Json::Int(i64::from(*start))),
218 ("end", Json::Int(i64::from(*end))),
219 ]),
220 })
221 .collect(),
222 ),
223 FeatureExpr::Call { name, arguments } => Json::Object(vec![
224 ("kind", Json::str("ref")),
225 ("name", Json::str(name)),
226 ("arguments", expressions_json(arguments)),
227 ]),
228 FeatureExpr::Form(form) => form_json("kind", form),
229 }
230}
231
232fn form_json(head_key: &'static str, form: &FeatureForm) -> Json {
234 check_grammar_selection_included_range_form(form)
235 .expect("a grammar form retains every included-range field");
236 let mut entries = vec![(head_key, Json::str(&form.head))];
237 for ((key, _), value) in form.spec().iter().zip(&form.fields) {
238 let value = match value {
239 FieldValue::Word(text) | FieldValue::Name(text) | FieldValue::Text(text) => {
240 Json::str(text)
241 }
242 FieldValue::Integer(value) => Json::Int(*value),
243 FieldValue::Expression(expr) => expression_json(expr),
244 FieldValue::Expressions(items) => expressions_json(items),
245 FieldValue::Operation(operation) => operation_json(operation),
246 FieldValue::Operations(items) | FieldValue::Block(Some(items)) => {
247 operations_json(items)
248 }
249 FieldValue::Block(None) => continue,
250 };
251 entries.push((key, value));
252 }
253 Json::Object(entries)
254}
255
256fn operation_json(operation: &Operation) -> Json {
257 form_json("operation", operation)
258}
259
260fn operations_json(operations: &[Operation]) -> Json {
261 Json::Array(operations.iter().map(operation_json).collect())
262}
263
264fn rule_json(rule: &GrammarRule) -> Json {
265 let mut entries = vec![
266 ("name", Json::str(&rule.name)),
267 ("kind", Json::str(rule.kind.as_str())),
268 ("expression", expression_json(&rule.expr)),
269 ];
270 let attributes = &rule.attributes;
271 if !attributes.parameters.is_empty() {
272 entries.push(("parameters", Json::strings(&attributes.parameters)));
273 }
274 if let Some(channel) = &attributes.channel {
275 entries.push(("channel", Json::str(channel)));
276 }
277 if let Some(modes) = &attributes.modes {
278 entries.push(("modes", Json::strings(modes)));
279 }
280 if let Some(action) = &attributes.action {
281 entries.push(("action", operations_json(action)));
282 }
283 Json::Object(entries)
284}
285
286fn declarations_json(declarations: &GrammarDeclarations) -> Json {
287 let mut entries = Vec::new();
288 if let Some(matching) = &declarations.matching {
289 entries.push(("matching", Json::str(matching)));
290 }
291 if let Some(settling) = &declarations.settling {
292 entries.push(("settling", Json::strings(settling)));
293 }
294 if !declarations.imports.is_empty() {
295 entries.push(("imports", Json::strings(&declarations.imports)));
296 }
297 if !declarations.modes.is_empty() {
298 entries.push(("modes", Json::strings(&declarations.modes)));
299 }
300 if !declarations.extras.is_empty() {
301 entries.push(("extras", expressions_json(&declarations.extras)));
302 }
303 if !declarations.conflicts.is_empty() {
304 let groups = declarations
305 .conflicts
306 .iter()
307 .map(|group| Json::strings(group));
308 entries.push(("conflicts", Json::Array(groups.collect())));
309 }
310 if !declarations.precedences.is_empty() {
311 let orders = declarations.precedences.iter().map(|order| {
312 Json::Array(
313 order
314 .iter()
315 .map(|entry| {
316 Json::Object(vec![
317 ("kind", Json::str(entry.kind())),
318 ("value", Json::str(entry.value())),
319 ])
320 })
321 .collect(),
322 )
323 });
324 entries.push(("precedences", Json::Array(orders.collect())));
325 }
326 if !declarations.macros.is_empty() {
327 let macros = declarations.macros.iter().map(|declared| {
328 Json::Object(vec![
329 ("name", Json::str(&declared.name)),
330 ("parameters", Json::strings(&declared.parameters)),
331 ("expression", expression_json(&declared.expression)),
332 ])
333 });
334 entries.push(("macros", Json::Array(macros.collect())));
335 }
336 if !declarations.scanners.is_empty() {
337 let scanners = declarations.scanners.iter().map(|scanner| {
338 Json::Object(vec![
339 ("name", Json::str(&scanner.name)),
340 ("tokens", Json::strings(&scanner.tokens)),
341 ("operations", operations_json(&scanner.operations)),
342 ])
343 });
344 entries.push(("scanners", Json::Array(scanners.collect())));
345 }
346 if !declarations.lexers.is_empty() {
347 let lexers = declarations.lexers.iter().map(|lexer| {
348 Json::Object(vec![
349 ("name", Json::str(&lexer.name)),
350 ("expression", expression_json(&lexer.expression)),
351 ])
352 });
353 entries.push(("lexers", Json::Array(lexers.collect())));
354 }
355 Json::Object(entries)
356}
357
358#[must_use]
361pub fn serialize_grammar(grammar: &Grammar) -> String {
362 check_grammar_selection_included_range_grammar(grammar)
363 .expect("a grammar retains every included-range definition");
364 let mut entries = vec![
365 ("schemaVersion", Json::Int(1)),
366 ("start", grammar.start().map_or(Json::Null, Json::str)),
367 (
368 "sourceFormat",
369 grammar
370 .source_format()
371 .map_or(Json::Null, |format| Json::str(format.as_str())),
372 ),
373 (
374 "rules",
375 Json::Array(grammar.rules().iter().map(rule_json).collect()),
376 ),
377 ];
378 if !grammar.declarations().is_empty() {
379 entries.push(("declarations", declarations_json(grammar.declarations())));
380 }
381 let mut out = String::new();
382 Json::Object(entries).render(0, &mut out);
383 out.push('\n');
384 out
385}
386
387fn json_error(detail: impl Into<String>) -> GrammarImportError {
388 GrammarImportError::Parse {
389 format: GrammarFormat::MetaLanguage,
390 message: detail.into(),
391 }
392}
393
394fn invalid(what: &str) -> GrammarImportError {
395 json_error(format!("invalid serialized grammar {what}"))
396}
397
398fn field<'a>(value: &'a Value, key: &str, what: &str) -> Result<&'a Value, GrammarImportError> {
399 value.get(key).ok_or_else(|| invalid(what))
400}
401
402fn string(value: &Value, key: &str, what: &str) -> Result<String, GrammarImportError> {
403 field(value, key, what)?
404 .as_str()
405 .map(str::to_owned)
406 .ok_or_else(|| invalid(what))
407}
408
409fn optional_string(
410 value: &Value,
411 key: &str,
412 what: &str,
413) -> Result<Option<String>, GrammarImportError> {
414 match value.get(key) {
415 None | Some(Value::Null) => Ok(None),
416 Some(Value::String(text)) => Ok(Some(text.clone())),
417 Some(_) => Err(invalid(what)),
418 }
419}
420
421fn strings(value: Option<&Value>, what: &str) -> Result<Vec<String>, GrammarImportError> {
422 match value {
423 None | Some(Value::Null) => Ok(Vec::new()),
424 Some(Value::Array(items)) => items
425 .iter()
426 .map(|item| {
427 item.as_str()
428 .map(str::to_owned)
429 .ok_or_else(|| invalid(what))
430 })
431 .collect(),
432 Some(_) => Err(invalid(what)),
433 }
434}
435
436fn array<'a>(value: &'a Value, key: &str, what: &str) -> Result<&'a [Value], GrammarImportError> {
437 field(value, key, what)?
438 .as_array()
439 .map(Vec::as_slice)
440 .ok_or_else(|| invalid(what))
441}
442
443fn character(value: &Value, key: &str) -> Result<char, GrammarImportError> {
444 let text = string(value, key, "expression")?;
445 let mut chars = text.chars();
446 match (chars.next(), chars.next()) {
447 (Some(value), None) => Ok(value),
448 _ => Err(invalid("expression")),
449 }
450}
451
452fn integer(value: &Value, key: &str, what: &str) -> Result<i64, GrammarImportError> {
453 field(value, key, what)?
454 .as_i64()
455 .ok_or_else(|| invalid(what))
456}
457
458fn count(value: &Value, key: &str) -> Result<usize, GrammarImportError> {
459 usize::try_from(integer(value, key, "expression")?).map_err(|_| invalid("expression"))
460}
461
462fn byte(value: &Value, key: &str) -> Result<u8, GrammarImportError> {
463 u8::try_from(integer(value, key, "expression")?).map_err(|_| invalid("expression"))
464}
465
466fn read_expressions(value: &Value, key: &str) -> Result<Vec<GrammarExpr>, GrammarImportError> {
467 array(value, key, "expression")?
468 .iter()
469 .map(read_expression)
470 .collect()
471}
472
473fn read_item(value: &Value) -> Result<Box<GrammarExpr>, GrammarImportError> {
474 Ok(Box::new(read_expression(field(
475 value,
476 "item",
477 "expression",
478 )?)?))
479}
480
481fn read_expression(value: &Value) -> Result<GrammarExpr, GrammarImportError> {
482 let kind = string(value, "kind", "expression")?;
483 Ok(match kind.as_str() {
484 "empty" => GrammarExpr::Empty,
485 "any" => GrammarExpr::AnyChar,
486 "literal" => GrammarExpr::Terminal(string(value, "value", "expression")?),
487 "literalInsensitive" => {
488 GrammarExpr::TerminalInsensitive(string(value, "value", "expression")?)
489 }
490 "charRange" => GrammarExpr::CharRange(character(value, "start")?, character(value, "end")?),
491 "charClass" => {
492 let negated = value
493 .get("negated")
494 .and_then(Value::as_bool)
495 .unwrap_or(false);
496 let items = array(value, "items", "expression")?
497 .iter()
498 .map(read_class_item)
499 .collect::<Result<_, _>>()?;
500 class_expression(negated, items)
501 }
502 "byteClass" => {
503 let negated = value
504 .get("negated")
505 .and_then(Value::as_bool)
506 .unwrap_or(false);
507 let items = array(value, "items", "expression")?
508 .iter()
509 .map(|item| match string(item, "kind", "expression")?.as_str() {
510 "byte" => Ok(ByteClassItem::Byte(byte(item, "value")?)),
511 "byteRange" => Ok(ByteClassItem::Range(
512 byte(item, "start")?,
513 byte(item, "end")?,
514 )),
515 _ => Err(invalid("expression")),
516 })
517 .collect::<Result<_, _>>()?;
518 GrammarExpr::feature(FeatureExpr::ByteClass { negated, items })
519 }
520 "ref" => {
521 let name = string(value, "name", "expression")?;
522 match value.get("arguments") {
523 None | Some(Value::Null) => GrammarExpr::NonTerminal(name),
524 Some(_) => GrammarExpr::feature(FeatureExpr::Call {
525 name,
526 arguments: read_expressions(value, "arguments")?,
527 }),
528 }
529 }
530 "choice" => GrammarExpr::Choice {
531 ordered: value
532 .get("ordered")
533 .and_then(Value::as_bool)
534 .unwrap_or(false),
535 alternatives: read_expressions(value, "items")?,
536 },
537 "seq" => GrammarExpr::Sequence(read_expressions(value, "items")?),
538 "optional" => GrammarExpr::Optional(read_item(value)?),
539 "repeat0" => GrammarExpr::ZeroOrMore(read_item(value)?),
540 "repeat1" => GrammarExpr::OneOrMore(read_item(value)?),
541 "and" => GrammarExpr::And(read_item(value)?),
542 "not" => GrammarExpr::Not(read_item(value)?),
543 "repeat" => GrammarExpr::Repeat {
544 expr: read_item(value)?,
545 min: count(value, "min")?,
546 max: match value.get("max") {
547 None | Some(Value::Null) => None,
548 Some(_) => Some(count(value, "max")?),
549 },
550 },
551 "capture" => GrammarExpr::Capture {
552 label: optional_string(value, "label", "expression")?,
553 expr: read_item(value)?,
554 },
555 other => {
556 let fields = feature_expression_fields(other).ok_or_else(|| {
557 json_error(format!(
558 "unsupported serialized grammar expression kind {other}"
559 ))
560 })?;
561 GrammarExpr::feature(FeatureExpr::Form(read_form(other, fields, value)?))
562 }
563 })
564}
565
566fn read_class_item(item: &Value) -> Result<UnicodeClassItem, GrammarImportError> {
567 Ok(match string(item, "kind", "expression")?.as_str() {
568 "char" => UnicodeClassItem::Char(character(item, "value")?),
569 "range" => UnicodeClassItem::Range(character(item, "start")?, character(item, "end")?),
570 "category" => UnicodeClassItem::Category(string(item, "value", "expression")?),
571 "script" => UnicodeClassItem::Script(string(item, "value", "expression")?),
572 _ => return Err(invalid("expression")),
573 })
574}
575
576fn read_form(
577 head: &str,
578 fields: &[(&'static str, FieldType)],
579 value: &Value,
580) -> Result<FeatureForm, GrammarImportError> {
581 let mut values = Vec::with_capacity(fields.len());
582 for (key, kind) in fields {
583 let what = "expression";
584 values.push(match kind {
585 FieldType::Choice(words) => {
586 let word = string(value, key, what)?;
587 if !words.contains(&word.as_str()) {
588 return Err(invalid(what));
589 }
590 FieldValue::Word(word)
591 }
592 FieldType::Integer if head == "source-range" || head == "source-field-selector" => {
593 let coordinate = field(value, key, what)?.as_f64().unwrap_or(f64::NAN);
594 let integer =
595 crate::translation::frontend_rules::ml_array::number_index(coordinate)
596 .and_then(|value| i64::try_from(value).ok())
597 .ok_or_else(|| invalid(what))?;
598 FieldValue::Integer(integer)
599 }
600 FieldType::Integer => FieldValue::Integer(integer(value, key, what)?),
601 FieldType::Name => FieldValue::Name(string(value, key, what)?),
602 FieldType::Text => FieldValue::Text(string(value, key, what)?),
603 FieldType::Expression => {
604 FieldValue::Expression(read_expression(field(value, key, what)?)?)
605 }
606 FieldType::Expressions => FieldValue::Expressions(read_expressions(value, key)?),
607 FieldType::Condition => FieldValue::Operation(read_operation(
608 field(value, key, what)?,
609 OperationCategory::Condition,
610 )?),
611 FieldType::Value => FieldValue::Operation(read_operation(
612 field(value, key, what)?,
613 OperationCategory::Value,
614 )?),
615 FieldType::Conditions => FieldValue::Operations(read_operations(
616 array(value, key, what)?,
617 OperationCategory::Condition,
618 )?),
619 FieldType::Block(_, optional) => match value.get(*key) {
620 None | Some(Value::Null) if *optional => FieldValue::Block(None),
621 _ => FieldValue::Block(Some(read_operations(
622 array(value, key, what)?,
623 OperationCategory::Statement,
624 )?)),
625 },
626 });
627 }
628 Ok(FeatureForm::new(head, values))
629}
630
631fn read_operation(
632 value: &Value,
633 category: OperationCategory,
634) -> Result<Operation, GrammarImportError> {
635 let head = string(value, "operation", "operation")?;
636 let (found, fields) = operation_form(&head)
637 .ok_or_else(|| json_error(format!("unsupported serialized grammar operation {head}")))?;
638 if found != category {
639 return Err(json_error(format!(
640 "serialized grammar operation {head} is not a {}",
641 category.as_str()
642 )));
643 }
644 read_form(&head, fields, value)
645}
646
647fn read_operations(
648 values: &[Value],
649 category: OperationCategory,
650) -> Result<Vec<Operation>, GrammarImportError> {
651 values
652 .iter()
653 .map(|value| read_operation(value, category))
654 .collect()
655}
656
657fn read_declarations(value: &Value) -> Result<GrammarDeclarations, GrammarImportError> {
658 let what = "declarations";
659 let mut declarations = GrammarDeclarations {
660 matching: optional_string(value, "matching", what)?,
661 settling: value
662 .get("settling")
663 .filter(|steps| !steps.is_null())
664 .map(|steps| strings(Some(steps), what))
665 .transpose()?,
666 imports: strings(value.get("imports"), what)?,
667 modes: strings(value.get("modes"), what)?,
668 ..GrammarDeclarations::default()
669 };
670 if let Some(Value::Array(extras)) = value.get("extras") {
671 declarations.extras = extras
672 .iter()
673 .map(read_expression)
674 .collect::<Result<_, _>>()?;
675 }
676 if let Some(Value::Array(groups)) = value.get("conflicts") {
677 declarations.conflicts = groups
678 .iter()
679 .map(|group| strings(Some(group), what))
680 .collect::<Result<_, _>>()?;
681 }
682 if let Some(Value::Array(orders)) = value.get("precedences") {
683 for order in orders {
684 let Value::Array(entries) = order else {
685 return Err(invalid(what));
686 };
687 let mut read = Vec::new();
688 for entry in entries {
689 let kind = string(entry, "kind", what)?;
690 let value = string(entry, "value", what)?;
691 let Some(entry) = PrecedenceEntry::from_kind(&kind, value) else {
692 return Err(invalid(what));
693 };
694 read.push(entry);
695 }
696 declarations.precedences.push(read);
697 }
698 }
699 if let Some(Value::Array(macros)) = value.get("macros") {
700 for declared in macros {
701 declarations.macros.push(GrammarMacro {
702 name: string(declared, "name", what)?,
703 parameters: strings(declared.get("parameters"), what)?,
704 expression: read_expression(field(declared, "expression", what)?)?,
705 });
706 }
707 }
708 if let Some(Value::Array(scanners)) = value.get("scanners") {
709 for scanner in scanners {
710 declarations.scanners.push(GrammarScanner {
711 name: string(scanner, "name", what)?,
712 tokens: strings(scanner.get("tokens"), what)?,
713 operations: read_operations(
714 array(scanner, "operations", what)?,
715 OperationCategory::Statement,
716 )?,
717 });
718 }
719 }
720 if let Some(Value::Array(lexers)) = value.get("lexers") {
721 for lexer in lexers {
722 declarations.lexers.push(GrammarLexer {
723 name: string(lexer, "name", what)?,
724 expression: read_expression(field(lexer, "expression", what)?)?,
725 });
726 }
727 }
728 Ok(declarations)
729}
730
731fn read_rule(value: &Value) -> Result<GrammarRule, GrammarImportError> {
732 let name = value.get("name").and_then(Value::as_str);
733 let expression = value
734 .get("expression")
735 .filter(|expr| expr.get("kind").is_some());
736 let (Some(name), Some(expression)) = (name, expression) else {
737 return Err(invalid("rule"));
738 };
739 let kind = match value.get("kind") {
740 None | Some(Value::Null) => RuleKind::Normal,
741 Some(kind) => kind
742 .as_str()
743 .and_then(RuleKind::from_tag)
744 .ok_or_else(|| invalid("rule"))?,
745 };
746 let attributes = RuleAttributes {
747 parameters: strings(value.get("parameters"), "rule")?,
748 channel: optional_string(value, "channel", "rule")?,
749 modes: match value.get("modes") {
750 None | Some(Value::Null) => None,
751 modes => Some(strings(modes, "rule")?),
752 },
753 action: match value.get("action") {
754 None | Some(Value::Null) => None,
755 Some(_) => Some(read_operations(
756 array(value, "action", "rule")?,
757 OperationCategory::Statement,
758 )?),
759 },
760 };
761 Ok(GrammarRule::new(name, read_expression(expression)?)
762 .with_kind(kind)
763 .with_attributes(attributes))
764}
765
766pub fn deserialize_grammar(source: &str) -> Result<Grammar, GrammarImportError> {
775 let value: Value = serde_json::from_str(source)
776 .map_err(|error| json_error(format!("invalid serialized grammar JSON: {error}")))?;
777 check_grammar_selection_included_range_data(&value).map_err(json_error)?;
778 let (Some(1), Some(Value::Array(rules))) = (
779 value.get("schemaVersion").and_then(Value::as_i64),
780 value.get("rules"),
781 ) else {
782 return Err(invalid("document"));
783 };
784 let mut grammar = Grammar::new();
785 for rule in rules {
786 let rule = read_rule(rule)?;
787 if grammar.rule(&rule.name).is_some() {
788 return Err(json_error(format!(
789 "duplicate serialized grammar rule {}",
790 rule.name
791 )));
792 }
793 grammar.add_rule(rule);
794 }
795 if let Some(start) = value.get("start").and_then(Value::as_str) {
796 grammar.set_start(start);
797 }
798 if let Some(format) = value.get("sourceFormat").and_then(Value::as_str) {
799 let format = GrammarFormat::from_tag(format)
800 .ok_or_else(|| json_error(format!("unknown serialized grammar format {format}")))?;
801 grammar.set_source_format(format);
802 }
803 if let Some(declarations) = value.get("declarations").filter(|value| !value.is_null()) {
804 grammar.set_declarations(read_declarations(declarations)?);
805 }
806 if grammar.start_rule().is_none() {
807 return Err(json_error("serialized grammar has no start rule"));
808 }
809 Ok(grammar)
810}