1use std::collections::{HashMap, HashSet, VecDeque};
8use std::fmt;
9use std::sync::Arc;
10
11#[path = "load_lexers.rs"]
12mod lexical;
13#[path = "load_selection.rs"]
14mod selection;
15#[path = "load_trivia.rs"]
16mod trivia;
17
18use super::compile::Compiler;
19use super::forking::GrammarFacts;
20use super::program::{
21 Compiled, Expr, Program, Rule, Scanner, Settling, SettlingStep, Target, Trivia,
22};
23use super::token_ranks::token_ranks;
24use crate::grammar::feature::check_grammar_selection_included_range_grammar;
25use crate::grammar::interchange::render_native_expression;
26use crate::grammar::{
27 FeatureExpr, FeatureForm, FieldValue, Grammar, GrammarExpr, GrammarFormat, GrammarMacro,
28 GrammarScanner, Operation, PrecedenceEntry, RuleAttributes, RuleKind, default_settling,
29 settling_problem,
30};
31
32#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct GrammarRuntimeError {
37 pub reason: &'static str,
39 pub message: String,
41}
42
43impl fmt::Display for GrammarRuntimeError {
44 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
45 write!(formatter, "{} ({})", self.message, self.reason)
46 }
47}
48
49impl std::error::Error for GrammarRuntimeError {}
50
51pub(super) type LoadResult<T> = Result<T, GrammarRuntimeError>;
52
53pub(super) fn refuse<T>(reason: &'static str, message: impl Into<String>) -> LoadResult<T> {
55 Err(GrammarRuntimeError {
56 reason,
57 message: message.into(),
58 })
59}
60
61pub(super) type Resolver<'a> = Option<&'a dyn Fn(&str) -> Option<Grammar>>;
63
64const INSTANCE_LIMIT: usize = 1000;
65
66struct Ordered<T> {
68 items: Vec<(String, T)>,
69 index: HashMap<String, usize>,
70}
71
72impl<T> Ordered<T> {
73 fn new() -> Self {
74 Self {
75 items: Vec::new(),
76 index: HashMap::new(),
77 }
78 }
79
80 fn set(&mut self, name: String, value: T) {
81 if let Some(&position) = self.index.get(&name) {
82 self.items[position].1 = value;
83 } else {
84 self.index.insert(name.clone(), self.items.len());
85 self.items.push((name, value));
86 }
87 }
88
89 fn get(&self, name: &str) -> Option<&T> {
90 self.index
91 .get(name)
92 .map(|&position| &self.items[position].1)
93 }
94
95 fn contains(&self, name: &str) -> bool {
96 self.index.contains_key(name)
97 }
98
99 const fn len(&self) -> usize {
100 self.items.len()
101 }
102}
103
104pub(super) fn form_of<'a>(expr: &'a GrammarExpr, head: &str) -> Option<&'a FeatureForm> {
106 match expr {
107 GrammarExpr::Feature(feature) => match &**feature {
108 FeatureExpr::Form(form) if form.head == head => Some(form),
109 _ => None,
110 },
111 _ => None,
112 }
113}
114
115pub(super) fn map_children_mut(expr: &mut GrammarExpr, map: &mut impl FnMut(&mut GrammarExpr)) {
117 match expr {
118 GrammarExpr::Optional(inner)
119 | GrammarExpr::ZeroOrMore(inner)
120 | GrammarExpr::OneOrMore(inner)
121 | GrammarExpr::And(inner)
122 | GrammarExpr::Not(inner)
123 | GrammarExpr::Repeat { expr: inner, .. }
124 | GrammarExpr::Capture { expr: inner, .. } => map(inner),
125 GrammarExpr::Choice { alternatives, .. } => alternatives.iter_mut().for_each(map),
126 GrammarExpr::Sequence(items) => items.iter_mut().for_each(map),
127 GrammarExpr::Feature(feature) => feature.map_expressions(map),
128 GrammarExpr::Empty
129 | GrammarExpr::Terminal(_)
130 | GrammarExpr::TerminalInsensitive(_)
131 | GrammarExpr::CharRange(..)
132 | GrammarExpr::CharClass { .. }
133 | GrammarExpr::AnyChar
134 | GrammarExpr::NonTerminal(_) => {}
135 }
136}
137
138fn try_map_children(
140 expr: &GrammarExpr,
141 mut map: impl FnMut(&GrammarExpr) -> LoadResult<GrammarExpr>,
142) -> LoadResult<GrammarExpr> {
143 let mut copy = expr.clone();
144 let mut failure = None;
145 map_children_mut(&mut copy, &mut |child: &mut GrammarExpr| {
146 if failure.is_none() {
147 match map(child) {
148 Ok(mapped) => *child = mapped,
149 Err(error) => failure = Some(error),
150 }
151 }
152 });
153 failure.map_or(Ok(copy), Err)
154}
155
156fn try_map_operations(
158 operations: &[Operation],
159 mut map: impl FnMut(&GrammarExpr) -> LoadResult<GrammarExpr>,
160) -> LoadResult<Vec<Operation>> {
161 let mut copy = operations.to_vec();
162 let mut failure = None;
163 for operation in &mut copy {
164 operation.map_expressions(&mut |child: &mut GrammarExpr| {
165 if failure.is_none() {
166 match map(child) {
167 Ok(mapped) => *child = mapped,
168 Err(error) => failure = Some(error),
169 }
170 }
171 });
172 }
173 failure.map_or(Ok(copy), Err)
174}
175
176struct Context<'a> {
178 resolver: Resolver<'a>,
179 programs: Vec<Program>,
180 languages: HashMap<String, usize>,
181 root_name: Option<String>,
182 capture_origins: bool,
183}
184
185impl Context<'_> {
186 fn resolve(&self, name: &str, purpose: &'static str) -> LoadResult<Grammar> {
187 let resolved = self.resolver.and_then(|resolve| resolve(name));
188 resolved.map_or_else(
189 || {
190 let what = if purpose == "import" {
191 "imported grammar"
192 } else {
193 "embedded language"
194 };
195 refuse(purpose, format!("{what} {name} cannot be resolved"))
196 },
197 Ok,
198 )
199 }
200}
201
202struct Resolved {
204 start: Option<String>,
205 peg_source: bool,
206 matching: Option<String>,
207 settling: Option<Vec<String>>,
208 rules: Ordered<(RuleKind, GrammarExpr, RuleAttributes)>,
209 modes: Vec<String>,
210 extras: Vec<GrammarExpr>,
211 conflicts: Vec<Vec<String>>,
212 precedences: Vec<Vec<PrecedenceEntry>>,
213 macros: Ordered<GrammarMacro>,
214 scanners: Vec<GrammarScanner>,
215 lexers: Vec<crate::grammar::GrammarLexer>,
216}
217
218fn resolve_imports(
223 grammar: &Grammar,
224 context: &Context<'_>,
225 chain: &[String],
226) -> LoadResult<Resolved> {
227 if let Err(message) = check_grammar_selection_included_range_grammar(grammar) {
228 return refuse("selection", message);
229 }
230 let declarations = grammar.declarations();
231 let mut resolved = Resolved {
232 start: grammar
233 .start()
234 .map(str::to_owned)
235 .or_else(|| grammar.rules().first().map(|rule| rule.name.clone())),
236 peg_source: grammar.source_format() == Some(GrammarFormat::Peg),
237 matching: declarations.matching.clone(),
238 settling: declarations.settling.clone(),
239 rules: Ordered::new(),
240 modes: Vec::new(),
241 extras: Vec::new(),
242 conflicts: Vec::new(),
243 precedences: Vec::new(),
244 macros: Ordered::new(),
245 scanners: Vec::new(),
246 lexers: Vec::new(),
247 };
248 for name in &declarations.imports {
249 let mut next = chain.to_vec();
250 next.push(name.clone());
251 if chain.contains(name) {
252 return refuse("import", format!("import cycle {}", next.join(" -> ")));
253 }
254 let imported = context.resolve(name, "import")?;
255 let inner = resolve_imports(&imported, context, &next)?;
256 for (rule_name, rule) in inner.rules.items {
257 resolved.rules.set(rule_name, rule);
258 }
259 resolved.modes.extend(inner.modes);
260 resolved.extras.extend(inner.extras);
261 resolved.conflicts.extend(inner.conflicts);
262 resolved.precedences.extend(inner.precedences);
263 for (macro_name, item) in inner.macros.items {
264 resolved.macros.set(macro_name, item);
265 }
266 resolved.scanners.extend(inner.scanners);
267 resolved.lexers.extend(inner.lexers);
268 }
269 for rule in grammar.rules() {
270 resolved.rules.set(
271 rule.name.clone(),
272 (rule.kind, rule.expr.clone(), rule.attributes.clone()),
273 );
274 }
275 resolved.modes.extend(declarations.modes.iter().cloned());
276 resolved.extras.extend(declarations.extras.iter().cloned());
277 resolved
278 .conflicts
279 .extend(declarations.conflicts.iter().cloned());
280 resolved
281 .precedences
282 .extend(declarations.precedences.iter().cloned());
283 for item in &declarations.macros {
284 resolved.macros.set(item.name.clone(), item.clone());
285 }
286 resolved
287 .scanners
288 .extend(declarations.scanners.iter().cloned());
289 resolved.lexers.extend(declarations.lexers.iter().cloned());
290 Ok(resolved)
291}
292
293fn substitute(expr: &GrammarExpr, bindings: &HashMap<String, GrammarExpr>) -> GrammarExpr {
294 if let Some(bound) = form_of(expr, "parameter")
295 .and_then(|form| form.text("name"))
296 .and_then(|name| bindings.get(name))
297 {
298 return bound.clone();
299 }
300 let mut copy = expr.clone();
301 map_children_mut(&mut copy, &mut |child: &mut GrammarExpr| {
302 *child = substitute(child, bindings);
303 });
304 copy
305}
306
307fn expand_macros(
310 expr: &GrammarExpr,
311 macros: &Ordered<GrammarMacro>,
312 active: &mut Vec<String>,
313) -> LoadResult<GrammarExpr> {
314 let Some(form) = form_of(expr, "expand") else {
315 return try_map_children(expr, |child| expand_macros(child, macros, active));
316 };
317 let name = form.text("name").unwrap_or_default();
318 let arguments = form.expressions("arguments");
319 let Some(definition) = macros.get(name) else {
320 return refuse("macro", format!("undefined macro {name}"));
321 };
322 if active.iter().any(|item| item == name) {
323 return refuse(
324 "macro",
325 format!("recursive macro {} -> {name}", active.join(" -> ")),
326 );
327 }
328 if definition.parameters.len() != arguments.len() {
329 return refuse(
330 "macro",
331 format!(
332 "macro {name} takes {} arguments, not {}",
333 definition.parameters.len(),
334 arguments.len()
335 ),
336 );
337 }
338 let mut bindings = HashMap::new();
339 for (parameter, argument) in definition.parameters.iter().zip(arguments) {
340 bindings.insert(parameter.clone(), expand_macros(argument, macros, active)?);
341 }
342 active.push(name.to_owned());
343 let expanded = expand_macros(
344 &substitute(&definition.expression, &bindings),
345 macros,
346 active,
347 );
348 active.pop();
349 expanded
350}
351
352struct Source {
354 kind: RuleKind,
355 expression: GrammarExpr,
356 action: Option<Vec<Operation>>,
357 attributes: RuleAttributes,
358}
359
360struct Instance {
362 node_kind: String,
363 source: String,
364 expression: GrammarExpr,
365 action: Option<Vec<Operation>>,
366}
367
368struct Pending {
369 name: String,
370 target: String,
371 bindings: HashMap<String, GrammarExpr>,
372}
373
374struct Instantiator<'a> {
377 sources: &'a Ordered<Source>,
378 external: &'a HashMap<String, usize>,
379 rules: Ordered<Instance>,
380 pending: VecDeque<Pending>,
381 queued: HashSet<String>,
382}
383
384impl Instantiator<'_> {
385 fn instantiate(
386 &mut self,
387 expr: &GrammarExpr,
388 bindings: Option<&HashMap<String, GrammarExpr>>,
389 owner: &str,
390 ) -> LoadResult<GrammarExpr> {
391 if let Some(form) = form_of(expr, "parameter") {
392 let name = form.text("name").unwrap_or_default();
393 return bindings.and_then(|bound| bound.get(name)).map_or_else(
394 || {
395 refuse(
396 "parameter",
397 format!("parameter {name} is not a parameter of {owner}"),
398 )
399 },
400 |bound| Ok(bound.clone()),
401 );
402 }
403 let (name, arguments): (&str, &[GrammarExpr]) = match expr {
404 GrammarExpr::NonTerminal(name) => (name, &[]),
405 GrammarExpr::Feature(feature) => match &**feature {
406 FeatureExpr::Call { name, arguments } => (name, arguments),
407 _ => {
408 return try_map_children(expr, |child| {
409 self.instantiate(child, bindings, owner)
410 });
411 }
412 },
413 _ => return try_map_children(expr, |child| self.instantiate(child, bindings, owner)),
414 };
415 if self.external.contains_key(name) {
416 if !arguments.is_empty() {
417 return refuse(
418 "parameter",
419 format!("external token {name} takes no arguments"),
420 );
421 }
422 return Ok(GrammarExpr::NonTerminal(name.to_owned()));
423 }
424 let Some(target) = self.sources.get(name) else {
425 return refuse("reference", format!("undefined rule {name} in {owner}"));
426 };
427 let parameters = &target.attributes.parameters;
428 if arguments.len() != parameters.len() {
429 return refuse(
430 "parameter",
431 format!(
432 "rule {name} takes {} arguments, not {}",
433 parameters.len(),
434 arguments.len()
435 ),
436 );
437 }
438 if parameters.is_empty() {
439 return Ok(GrammarExpr::NonTerminal(name.to_owned()));
440 }
441 let concrete = arguments
442 .iter()
443 .map(|argument| self.instantiate(argument, bindings, owner))
444 .collect::<LoadResult<Vec<_>>>()?;
445 let rendered = concrete
446 .iter()
447 .map(render_native_expression)
448 .collect::<Vec<_>>();
449 let instance = format!("{name}({})", rendered.join(", "));
450 if !self.rules.contains(&instance) && !self.queued.contains(&instance) {
451 if self.rules.len() + self.pending.len() >= INSTANCE_LIMIT + self.sources.len() {
452 return refuse(
453 "parameter",
454 format!("parameterized rule {name} needs more than {INSTANCE_LIMIT} instances"),
455 );
456 }
457 self.queued.insert(instance.clone());
458 self.pending.push_back(Pending {
459 name: instance.clone(),
460 target: name.to_owned(),
461 bindings: parameters.iter().cloned().zip(concrete).collect(),
462 });
463 }
464 Ok(GrammarExpr::NonTerminal(instance))
465 }
466
467 fn instantiate_operations(
468 &mut self,
469 operations: &[Operation],
470 bindings: Option<&HashMap<String, GrammarExpr>>,
471 owner: &str,
472 ) -> LoadResult<Vec<Operation>> {
473 try_map_operations(operations, |expr| self.instantiate(expr, bindings, owner))
474 }
475
476 fn drain(&mut self) -> LoadResult<()> {
477 while let Some(Pending {
478 name,
479 target,
480 bindings,
481 }) = self.pending.pop_front()
482 {
483 let source = self
484 .sources
485 .get(&target)
486 .expect("a pending instance names a rule");
487 let owner = format!("rule {target}");
488 let expression = self.instantiate(&source.expression, Some(&bindings), &owner)?;
489 let action = match &source.action {
490 Some(action) => {
491 Some(self.instantiate_operations(action, Some(&bindings), &owner)?)
492 }
493 None => None,
494 };
495 self.rules.set(
496 name,
497 Instance {
498 node_kind: target.clone(),
499 source: target,
500 expression,
501 action,
502 },
503 );
504 }
505 Ok(())
506 }
507}
508
509pub(super) fn load(
511 grammar: &Grammar,
512 resolver: Resolver<'_>,
513 root_name: Option<&str>,
514) -> LoadResult<Compiled> {
515 let mut context = Context {
516 resolver,
517 programs: Vec::new(),
518 languages: HashMap::new(),
519 root_name: root_name.map(str::to_owned),
520 capture_origins: root_name.is_some(),
521 };
522 let main = load_in_context(grammar, &mut context)?;
523 Ok(Compiled {
524 programs: context.programs,
525 languages: context.languages,
526 main,
527 })
528}
529
530fn nesting_extras(
538 trivia: &[Trivia],
539 rules: &[Rule],
540 rule_index: &HashMap<String, usize>,
541) -> HashSet<Arc<str>> {
542 fn targets<'e>(expr: &'e Expr, found: &mut Vec<&'e Target>) {
543 match expr {
544 Expr::Ref(target) => found.push(target),
545 Expr::Seq(items) | Expr::Choice { items, .. } | Expr::Longest(items) => {
546 for item in items {
547 targets(item, found);
548 }
549 }
550 Expr::Repeat { item, .. }
551 | Expr::LexicalScope { item, .. }
552 | Expr::Capture { item, .. }
553 | Expr::Alias { item, .. }
554 | Expr::Precedence { item, .. }
555 | Expr::DynamicPrecedence { item, .. }
556 | Expr::LexicalPrecedence { item, .. }
557 | Expr::Predicate { item, .. }
558 | Expr::Missing { item, .. }
559 | Expr::Embed { item, .. } => targets(item, found),
560 Expr::And(item) | Expr::Not(item) | Expr::Token(item) | Expr::ImmediateToken(item) => {
561 targets(item, found);
562 }
563 Expr::Recover { item, synchronize } => {
564 targets(item, found);
565 targets(synchronize, found);
566 }
567 Expr::Empty | Expr::LexicalToken { .. } | Expr::Terminal { .. } => {}
568 }
569 }
570 let mut nesting = HashSet::new();
571 for kind in trivia.iter().filter_map(|item| item.kind.as_ref()) {
572 let Some(&index) = rule_index.get(&**kind) else {
573 continue;
574 };
575 if !matches!(rules[index].kind, RuleKind::Normal) {
576 continue;
577 }
578 let mut seen = HashSet::from([index]);
579 let mut pending = vec![index];
580 let mut scanned = false;
581 while let Some(at) = pending.pop() {
582 let mut found = Vec::new();
583 targets(&rules[at].expression, &mut found);
584 for target in found {
585 match target {
586 Target::External(_) => scanned = true,
587 Target::Rule(next) => {
588 if seen.insert(*next) {
589 pending.push(*next);
590 }
591 }
592 }
593 }
594 if scanned {
595 break;
596 }
597 }
598 if !scanned {
599 nesting.insert(kind.clone());
600 }
601 }
602 nesting
603}
604
605fn load_in_context(grammar: &Grammar, context: &mut Context<'_>) -> LoadResult<usize> {
606 let source_grammar = grammar;
607 let resolved = resolve_imports(grammar, context, &[])?;
608 let lexical_sources = lexical::read_lexers(&resolved)?;
609 let macros = &resolved.macros;
610 let expand = |expr: &GrammarExpr| expand_macros(expr, macros, &mut Vec::new());
611
612 let mut external = HashMap::new();
613 for (index, scanner) in resolved.scanners.iter().enumerate() {
614 for token in &scanner.tokens {
615 if external.contains_key(token) {
616 return refuse(
617 "declaration",
618 format!("external token {token} is declared twice"),
619 );
620 }
621 if resolved.rules.contains(token) {
622 return refuse(
623 "declaration",
624 format!("external token {token} is also a rule"),
625 );
626 }
627 external.insert(token.clone(), index);
628 }
629 }
630 let mut modes: HashSet<String> = HashSet::from(["default".to_owned()]);
631 modes.extend(resolved.modes.iter().cloned());
632
633 let mut sources = Ordered::new();
634 for (name, (kind, expression, attributes)) in &resolved.rules.items {
635 let action = match &attributes.action {
636 Some(action) => Some(try_map_operations(action, expand)?),
637 None => None,
638 };
639 sources.set(
640 name.clone(),
641 Source {
642 kind: *kind,
643 expression: expand(expression)?,
644 action,
645 attributes: attributes.clone(),
646 },
647 );
648 }
649
650 let mut instantiator = Instantiator {
651 sources: &sources,
652 external: &external,
653 rules: Ordered::new(),
654 pending: VecDeque::new(),
655 queued: HashSet::new(),
656 };
657 for (name, source) in &sources.items {
658 if !source.attributes.parameters.is_empty() {
659 continue;
660 }
661 let owner = format!("rule {name}");
662 let expression = instantiator.instantiate(&source.expression, None, &owner)?;
663 let action = match &source.action {
664 Some(action) => Some(instantiator.instantiate_operations(action, None, &owner)?),
665 None => None,
666 };
667 instantiator.rules.set(
668 name.clone(),
669 Instance {
670 node_kind: name.clone(),
671 source: name.clone(),
672 expression,
673 action,
674 },
675 );
676 }
677 instantiator.drain()?;
678
679 let start = resolved.start.clone();
680 let Some(start_source) = start.as_deref().and_then(|name| sources.get(name)) else {
681 return refuse(
682 "reference",
683 format!(
684 "undefined start rule {}",
685 start.as_deref().unwrap_or("null")
686 ),
687 );
688 };
689 if !start_source.attributes.parameters.is_empty() {
690 return refuse(
691 "parameter",
692 format!(
693 "start rule {} is parameterized",
694 start.as_deref().unwrap_or_default()
695 ),
696 );
697 }
698
699 let mut extras = Vec::new();
700 for extra in &resolved.extras {
701 extras.push(instantiator.instantiate(&expand(extra)?, None, "an extra")?);
702 }
703 let mut scanner_operations = Vec::new();
704 for scanner in &resolved.scanners {
705 let expanded = try_map_operations(&scanner.operations, expand)?;
706 let owner = format!("scanner {}", scanner.name);
707 scanner_operations.push(instantiator.instantiate_operations(&expanded, None, &owner)?);
708 }
709 instantiator.drain()?;
710
711 let mut conflicts = HashSet::new();
712 for group in &resolved.conflicts {
713 for name in group {
714 if !sources.contains(name) {
715 return refuse(
716 "declaration",
717 format!("conflict names undefined rule {name}"),
718 );
719 }
720 conflicts.insert(name.clone());
721 }
722 }
723 for order in &resolved.precedences {
725 for entry in order {
726 if let PrecedenceEntry::Rule(name) = entry
727 && !sources.contains(name)
728 {
729 return refuse(
730 "declaration",
731 format!("precedences names undefined rule {name}"),
732 );
733 }
734 }
735 }
736
737 let peg = resolved
738 .matching
739 .as_deref()
740 .map_or(resolved.peg_source, |matching| matching == "peg");
741 let matching = resolved
742 .matching
743 .as_deref()
744 .unwrap_or(if peg { "peg" } else { "generalized" });
745 let settling = match &resolved.settling {
748 Some(steps) => {
749 if let Some(problem) = settling_problem(steps) {
750 return refuse("declaration", problem);
751 }
752 Settling::new(steps)
753 }
754 None => Settling::new(default_settling(matching)),
755 };
756 let instances = instantiator.rules;
757 let rule_index: HashMap<String, usize> = instances
758 .items
759 .iter()
760 .enumerate()
761 .map(|(index, (name, _))| (name.clone(), index))
762 .collect();
763 let node_kinds = instances
764 .items
765 .iter()
766 .map(|(name, instance)| (name.clone(), Arc::from(instance.node_kind.as_str())))
767 .collect();
768 let mut compiler = Compiler::new(&rule_index, &external, &modes, node_kinds);
769 lexical::configure_compiler(&mut compiler, &lexical_sources);
770 let mut consults = Vec::new();
774 for (scanner, operations) in resolved.scanners.iter().zip(&scanner_operations) {
775 let mut items = Vec::new();
776 if !scanner.tokens.is_empty() {
777 expected_items(operations, &mut items);
778 }
779 consults.push(!items.is_empty());
780 for item in items {
781 if let Some(key) = compiler.expectation(item) {
782 let id = compiler.expectations.len();
783 compiler.expectations.entry(key).or_insert(id);
784 }
785 }
786 }
787 let expected_references = compiler
788 .expectations
789 .iter()
790 .filter_map(|(key, &id)| Some((key.strip_prefix("ref ")?.to_owned(), id)))
791 .collect();
792
793 let mut trivia = Vec::new();
796 for extra in &extras {
797 let expression = compiler.expression(extra, "an extra")?;
798 let (source, projection_name, projection_anonymous) = trivia::extra_source(&expression);
801 let kind = match source {
802 Expr::Ref(Target::Rule(index)) => Some(Arc::from(instances.items[*index].0.as_str())),
803 Expr::Ref(Target::External(name)) => Some(name.clone()),
804 _ => projection_name.clone(),
805 };
806 trivia.push(Trivia {
807 expression,
808 kind,
809 projection_name,
810 projection_anonymous,
811 modes: None,
812 });
813 }
814 let mut rules = Vec::new();
815 for (index, (name, instance)) in instances.items.iter().enumerate() {
816 let source = sources
817 .get(&instance.source)
818 .expect("an instance has a source");
819 let owner = format!("rule {}", instance.node_kind);
820 compiler.requesting = true;
821 let expression = compiler.expression(&instance.expression, &owner);
822 compiler.requesting = false;
823 let expression =
824 lexical::wrap_parser_owner(expression?, source_grammar, &lexical_sources, name);
825 let action = match &instance.action {
826 Some(action) => {
827 if source.kind == RuleKind::Silent && action.iter().any(builds_node) {
828 return refuse(
829 "operation",
830 format!("silent {owner} has no node for its action"),
831 );
832 }
833 Some(compiler.statements(action, "action", &owner, None)?)
834 }
835 None => None,
836 };
837 let rule_modes = match &source.attributes.modes {
838 Some(rule_modes) => {
839 for mode in rule_modes {
840 compiler.check_mode(mode, &owner)?;
841 }
842 Some(
843 rule_modes
844 .iter()
845 .map(|mode| Arc::from(mode.as_str()))
846 .collect(),
847 )
848 }
849 None => None,
850 };
851 let lexical_priority = form_of(&instance.expression, "lexicalPrecedence")
852 .and_then(|form| form.integer("level"))
853 .unwrap_or(0);
854 let node_kind: Arc<str> = Arc::from(instance.node_kind.as_str());
855 if !lexical::is_elected(&lexical_sources, name)
856 && source
857 .attributes
858 .channel
859 .as_deref()
860 .is_some_and(|channel| channel != "default")
861 {
862 trivia.push(Trivia {
863 expression: super::program::Expr::Ref(Target::Rule(index)),
864 kind: Some(node_kind.clone()),
865 projection_name: None,
866 projection_anonymous: false,
867 modes: rule_modes.clone(),
868 });
869 }
870 rules.push(Rule {
871 name: Arc::from(name.as_str()),
872 node_kind,
873 kind: source.kind,
874 expression,
875 action,
876 modes: rule_modes,
877 lexical_priority,
878 });
879 }
880 let mut scanners = Vec::new();
881 for ((scanner, operations), consults) in resolved
882 .scanners
883 .iter()
884 .zip(&scanner_operations)
885 .zip(consults)
886 {
887 let owner = format!("scanner {}", scanner.name);
888 let operations = if scanner.tokens.is_empty() {
889 Vec::new()
890 } else {
891 compiler.statements(
892 operations,
893 "scanner",
894 &owner,
895 Some(scanner.tokens.as_slice()),
896 )?
897 };
898 scanners.push(Scanner {
899 operations,
900 consults,
901 });
902 }
903 let (embedded, selected) = compiler.into_embedded();
904
905 let index = context.programs.len();
906 let token_ranks = (settling.has(SettlingStep::Tokens)
907 || settling.has(SettlingStep::Precedence))
908 .then(|| token_ranks(&rules));
909 let ranked_silent = resolved
910 .precedences
911 .iter()
912 .flatten()
913 .filter_map(|entry| match entry {
914 PrecedenceEntry::Rule(name)
915 if rule_index
916 .get(name)
917 .is_some_and(|&at| matches!(rules[at].kind, RuleKind::Silent)) =>
918 {
919 Some(name.clone())
920 }
921 _ => None,
922 })
923 .collect();
924 let grammar = GrammarFacts::new(
925 &rules,
926 &resolved.conflicts,
927 settling.has(SettlingStep::Precedence),
928 );
929 let nesting_extras = nesting_extras(&trivia, &rules, &rule_index);
930 let source_definition = if context.capture_origins || !selected.is_empty() {
931 super::grammar_selection::selection_source_definition(source_grammar)
932 } else {
933 serde_json::Value::Null
934 };
935 context.programs.push(Program {
936 lexers: HashMap::new(),
937 default_lexer: lexical::default_lexer(source_grammar, &lexical_sources),
938 source_definition,
939 peg,
940 settling,
941 token_ranks,
942 start,
943 rules,
944 rule_index,
945 external,
946 scanners,
947 conflicts,
948 precedence_orders: resolved.precedences.clone(),
949 ranked_silent,
950 trivia,
951 nesting_extras,
952 expected_references,
953 grammar,
954 });
955 lexical::load_lexers(index, lexical_sources, context)?;
956 if index == 0
957 && let Some(name) = &context.root_name
958 {
959 context.languages.insert(name.clone(), index);
960 }
961 selection::load_embedded_grammar_sources(embedded, selected, context)?;
962 Ok(index)
963}
964
965fn expected_items<'a>(operations: &'a [Operation], items: &mut Vec<&'a GrammarExpr>) {
967 for operation in operations {
968 if operation.head == "expected"
969 && let Some(item) = operation.expression("item")
970 {
971 items.push(item);
972 }
973 for value in &operation.fields {
974 match value {
975 FieldValue::Operation(operation) => {
976 expected_items(std::slice::from_ref(operation), items);
977 }
978 FieldValue::Operations(block) | FieldValue::Block(Some(block)) => {
979 expected_items(block, items);
980 }
981 _ => {}
982 }
983 }
984 }
985}
986
987fn builds_node(operation: &Operation) -> bool {
988 if operation.head == "setAttribute" || operation.head == "buildNode" {
989 return true;
990 }
991 ["consequent", "alternative", "body"].iter().any(|key| {
992 operation
993 .operations(key)
994 .is_some_and(|block| block.iter().any(builds_node))
995 })
996}