1mod attributes;
13mod compile;
14mod executor;
15mod expectation_requests;
16mod field_range_source;
17mod forking;
18mod grammar_selection;
19mod joins;
20mod keyword_lexing;
21mod lexical_cache;
22mod lexical_cache_memory;
23mod lexical_election;
24pub(crate) mod lexical_kernel;
25mod lexical_plan;
26mod lexing;
27mod load;
28mod mapped_tree_validation;
29mod operations;
30mod ordering;
31mod parting;
32mod precedence;
33mod precedence_contexts;
34mod program;
35mod reducing;
36mod repetition;
37mod results;
38mod roots;
39mod rules;
40mod selection_source_mapping;
41mod separators;
42mod text;
43mod token_conflicts;
44mod token_ranks;
45mod tree;
46mod walk;
47
48use std::cell::{Cell, RefCell};
49use std::collections::HashSet;
50use std::fmt;
51use std::rc::Rc;
52
53pub use grammar_selection::{GrammarSelection, GrammarSelectionAlternative};
54pub use load::GrammarRuntimeError;
55pub use mapped_tree_validation::check_grammar_selection_mapped_tree;
56pub use operations::OperationValue;
57pub use tree::{Ambiguity, LeafText, SyntaxAttributes, SyntaxTree};
58
59use super::Grammar;
60use super::decorators::{decorate_grammar, decorate_syntax_tree};
61use crate::decorators::{DecoratorError, DecoratorLevel, DecoratorSet};
62use crate::translation::grammar_selection_rules;
63use executor::Executor;
64use operations::Abort;
65use program::{Compiled, SettlingStep};
66use results::{Expectations, KeywordLexing, Outcome, Shared, TokenOrder};
67
68const DEFAULT_MAX_DEPTH: usize = 1000;
70const DEFAULT_MEMO_LIMIT: usize = 1_000_000;
72const DEFAULT_MEMORY_LIMIT: usize = 2_000_000;
74const PARSE_STACK: usize = 256 * 1024 * 1024;
77
78#[derive(Clone, Debug, Default, PartialEq, Eq)]
81pub struct FeatureParseOptions {
82 pub grammar_name: Option<String>,
84 pub global_concept_space: Option<serde_json::Value>,
86 pub start_rule: Option<String>,
88 pub max_depth: Option<usize>,
90 pub step_limit: Option<usize>,
93 pub memo_limit: Option<usize>,
95 pub memory_limit: Option<usize>,
102 pub reject_ambiguity: Option<bool>,
104 pub accept_recovery: Option<bool>,
106 pub error_recovery: Option<bool>,
109 pub max_repairs: Option<usize>,
111 pub decorators: DecoratorSet,
116}
117
118impl FeatureParseOptions {
119 fn over(&self, base: &Self) -> Self {
120 Self {
121 grammar_name: self
122 .grammar_name
123 .clone()
124 .or_else(|| base.grammar_name.clone()),
125 global_concept_space: self
126 .global_concept_space
127 .clone()
128 .or_else(|| base.global_concept_space.clone()),
129 start_rule: self.start_rule.clone().or_else(|| base.start_rule.clone()),
130 max_depth: self.max_depth.or(base.max_depth),
131 step_limit: self.step_limit.or(base.step_limit),
132 memo_limit: self.memo_limit.or(base.memo_limit),
133 memory_limit: self.memory_limit.or(base.memory_limit),
134 reject_ambiguity: self.reject_ambiguity.or(base.reject_ambiguity),
135 accept_recovery: self.accept_recovery.or(base.accept_recovery),
136 error_recovery: self.error_recovery.or(base.error_recovery),
137 max_repairs: self.max_repairs.or(base.max_repairs),
138 decorators: if self.decorators.is_empty() {
139 base.decorators.clone()
140 } else {
141 self.decorators.clone()
142 },
143 }
144 }
145}
146
147#[derive(Clone, Debug, PartialEq, Eq)]
149pub struct ParseRejection {
150 pub diagnostics: Option<Vec<serde_json::Value>>,
152 pub offset_semantics: Option<String>,
154 pub reason: &'static str,
157 pub offset: Option<usize>,
159 pub line: Option<usize>,
161 pub column: Option<usize>,
163 pub expected: Option<Vec<String>>,
165 pub limit: Option<usize>,
167}
168
169impl ParseRejection {
170 const fn limited(reason: &'static str, limit: usize) -> Self {
171 Self {
172 diagnostics: None,
173 offset_semantics: None,
174 reason,
175 offset: None,
176 line: None,
177 column: None,
178 expected: None,
179 limit: Some(limit),
180 }
181 }
182
183 fn positioned(reason: &'static str, bytes: &[u8], offset: usize) -> Self {
184 let (line, column) = text::line_and_column(bytes, offset);
185 Self {
186 diagnostics: None,
187 offset_semantics: None,
188 reason,
189 offset: Some(offset),
190 line: Some(line),
191 column: Some(column),
192 expected: None,
193 limit: None,
194 }
195 }
196}
197
198impl fmt::Display for ParseRejection {
199 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
200 let place = match (self.line, self.column) {
201 (Some(line), Some(column)) => format!(" at line {line} column {column}"),
202 _ => String::new(),
203 };
204 let limit = self.limit.unwrap_or_default();
205 match self.reason {
206 "syntax" => {
207 let expected = self.expected.as_deref().unwrap_or_default();
208 let expected = if expected.is_empty() {
209 "nothing more".to_owned()
210 } else {
211 expected.join(", ")
212 };
213 write!(formatter, "syntax error{place}: expected {expected}")
214 }
215 "nestingDepth" => write!(formatter, "the input nests deeper than {limit} rules"),
216 "stepLimit" => write!(formatter, "the parse needed more than {limit} steps"),
217 "memoryBudget" => write!(formatter, "the parse needed more than {limit} memo cells"),
218 "selection" => write!(
219 formatter,
220 "a mapped grammar result needs parseTree to retain its sourcePlanes"
221 ),
222 "recovered" => write!(formatter, "the input needed error recovery{place}"),
223 "ambiguity" => write!(formatter, "the input is ambiguous{place}"),
224 reason => write!(formatter, "the input is rejected ({reason})"),
225 }
226 }
227}
228
229#[derive(Clone, Debug, PartialEq, Eq)]
232pub struct ParseOutcome {
233 pub ok: bool,
235 pub tree: Option<SyntaxTree>,
237 pub ambiguities: Vec<Ambiguity>,
239 pub rejection: Option<ParseRejection>,
241 pub source_planes: Option<Vec<serde_json::Value>>,
243}
244
245#[derive(Clone, Debug, PartialEq, Eq)]
247pub struct GrammarParseError {
248 pub rejection: Box<ParseRejection>,
250}
251
252impl fmt::Display for GrammarParseError {
253 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
254 self.rejection.fmt(formatter)
255 }
256}
257
258impl std::error::Error for GrammarParseError {}
259
260pub type GrammarResolver<'a> = &'a dyn Fn(&str) -> Option<Grammar>;
262
263#[derive(Debug)]
265pub struct FeatureGrammarParser {
266 compiled: Compiled,
267 options: FeatureParseOptions,
268}
269
270pub fn compile_feature_grammar(
280 grammar: &Grammar,
281 resolve_grammar: Option<GrammarResolver<'_>>,
282 options: FeatureParseOptions,
283) -> Result<FeatureGrammarParser, GrammarRuntimeError> {
284 let decorated = decorate_grammar(grammar, &options.decorators, DecoratorLevel::GrammarRule)
285 .map_err(decorator_error)?;
286 Ok(FeatureGrammarParser {
287 compiled: load::load(&decorated, resolve_grammar, options.grammar_name.as_deref())?,
288 options,
289 })
290}
291
292impl FeatureGrammarParser {
293 pub fn parse_tree(
301 &self,
302 source: &[u8],
303 options: &FeatureParseOptions,
304 ) -> Result<ParseOutcome, GrammarRuntimeError> {
305 let options = options.over(&self.options);
306 let program = &self.compiled.programs[self.compiled.main];
307 let start_name = options
308 .start_rule
309 .clone()
310 .or_else(|| program.start.clone())
311 .unwrap_or_default();
312 let Some(&start_rule) = program.rule_index.get(&start_name) else {
313 return Err(GrammarRuntimeError {
314 reason: "reference",
315 message: format!("undefined start rule {start_name}"),
316 });
317 };
318 let compiled = &self.compiled;
319 let mut outcome = std::thread::scope(|scope| {
320 std::thread::Builder::new()
321 .stack_size(PARSE_STACK)
322 .spawn_scoped(scope, || {
323 parse_program(compiled, start_rule, source, &options)
324 })
325 .map_or_else(
326 |_| parse_program(compiled, start_rule, source, &options),
327 |handle| {
328 handle
329 .join()
330 .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
331 },
332 )
333 })?;
334 if let Some(tree) = &outcome.tree {
335 outcome.tree = Some(
336 decorate_syntax_tree(tree, &options.decorators, source).map_err(decorator_error)?,
337 );
338 }
339 Ok(outcome)
340 }
341
342 pub fn parse(
349 &self,
350 source: &[u8],
351 options: &FeatureParseOptions,
352 ) -> Result<SyntaxTree, GrammarParseError> {
353 let outcome = self
354 .parse_tree(source, options)
355 .map_err(|_| GrammarParseError {
356 rejection: Box::new(ParseRejection::positioned("syntax", source, 0)),
357 })?;
358 if outcome.ok && outcome.source_planes.is_some() {
359 let mut rejection = ParseRejection::positioned("selection", source, 0);
360 rejection.diagnostics = Some(vec![
361 serde_json::json!({"reason":"selection","start":0,"end":source.len(),
362 "detail":"a mapped grammar result needs parseTree to retain its sourcePlanes"}),
363 ]);
364 return Err(GrammarParseError {
365 rejection: Box::new(rejection),
366 });
367 }
368 match (outcome.rejection, outcome.tree) {
369 (None, Some(tree)) => Ok(tree),
370 (rejection, _) => Err(GrammarParseError {
371 rejection: Box::new(
372 rejection.unwrap_or_else(|| ParseRejection::positioned("syntax", source, 0)),
373 ),
374 }),
375 }
376 }
377}
378
379#[derive(Clone, Debug, PartialEq, Eq)]
382pub enum ParseWithGrammarError {
383 Runtime(GrammarRuntimeError),
385 Parse(GrammarParseError),
387}
388
389impl fmt::Display for ParseWithGrammarError {
390 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
391 match self {
392 Self::Runtime(error) => error.fmt(formatter),
393 Self::Parse(error) => error.fmt(formatter),
394 }
395 }
396}
397
398impl std::error::Error for ParseWithGrammarError {}
399
400pub fn parse_with_grammar(
408 grammar: &Grammar,
409 source: &[u8],
410 options: &FeatureParseOptions,
411) -> Result<SyntaxTree, ParseWithGrammarError> {
412 compile_feature_grammar(grammar, None, options.clone())
413 .map_err(ParseWithGrammarError::Runtime)?
414 .parse(source, options)
415 .map_err(|error| {
416 if error.rejection.reason == "selection" {
417 ParseWithGrammarError::Runtime(GrammarRuntimeError {
418 reason: "selection",
419 message: error.to_string(),
420 })
421 } else {
422 ParseWithGrammarError::Parse(error)
423 }
424 })
425}
426
427fn decorator_error(error: DecoratorError) -> GrammarRuntimeError {
428 GrammarRuntimeError {
429 reason: "decorator",
430 message: error.message,
431 }
432}
433
434const DEFAULT_MAX_REPAIRS: usize = 32;
436
437fn repair_parse(
444 failed: Outcome,
445 max_repairs: usize,
446 attempt: impl Fn(Option<&HashSet<usize>>) -> Result<Outcome, Abort>,
447) -> Result<Outcome, Abort> {
448 let mut points = HashSet::new();
449 let mut outcome = failed;
450 while points.len() < max_repairs {
451 let Outcome::Failed {
452 farthest,
453 element_farthest,
454 ..
455 } = &outcome
456 else {
457 break;
458 };
459 if !points.insert(element_farthest.unwrap_or(*farthest)) {
460 break;
461 }
462 outcome = match attempt(Some(&points)) {
463 Err(Abort::StepLimit) => break,
464 attempted => attempted?,
465 };
466 if matches!(outcome, Outcome::Parsed(_)) {
467 return Ok(outcome);
468 }
469 }
470 Ok(match outcome {
471 Outcome::Failed {
472 partial: Some(partial),
473 ..
474 } => Outcome::Parsed(partial),
475 outcome => outcome,
476 })
477}
478
479fn parse_program(
480 compiled: &Compiled,
481 start_rule: usize,
482 bytes: &[u8],
483 options: &FeatureParseOptions,
484) -> Result<ParseOutcome, GrammarRuntimeError> {
485 let max_depth = options.max_depth.unwrap_or(DEFAULT_MAX_DEPTH);
486 let limit = options.step_limit.unwrap_or_else(|| {
488 (100_000 + 1000 * bytes.len())
489 * if options.error_recovery == Some(true) {
490 2
491 } else {
492 1
493 }
494 });
495 let selection_sources = Rc::new(RefCell::new(
496 selection_source_mapping::SourceRegistry::default(),
497 ));
498 let selection_mapping_failures = Rc::new(RefCell::new(Vec::new()));
499 let refused = |rejection, tree| {
500 Ok(ParseOutcome {
501 ok: false,
502 tree,
503 ambiguities: Vec::new(),
504 rejection: Some(rejection),
505 source_planes: selection_sources.borrow().definitions(),
506 })
507 };
508 let tokens = compiled.programs[compiled.main]
511 .token_ranks
512 .as_ref()
513 .filter(|_| {
514 compiled.programs[compiled.main]
515 .settling
516 .has(SettlingStep::Tokens)
517 })
518 .map(|ranks| TokenOrder {
519 ranks,
520 bytes,
521 orders: &compiled.programs[compiled.main].precedence_orders,
522 grammar: &compiled.programs[compiled.main].grammar,
523 trivia: &compiled.programs[compiled.main].trivia,
524 });
525 let keywords = tokens.map(|_| RefCell::new(KeywordLexing::default()));
526 let expectations = RefCell::new(Expectations::default());
527 let memory_limit = options.memory_limit.unwrap_or(DEFAULT_MEMORY_LIMIT);
529 let cells = Rc::new(Cell::new(0));
530 let lexical_caches = Rc::new(RefCell::new(Vec::new()));
531 let global_concept_space = options.global_concept_space.clone().map(Rc::new);
532 let selection_diagnostics = Rc::new(RefCell::new(Vec::new()));
533 let runtime_error = Rc::new(RefCell::new(None));
534 let last_steps = Cell::new(0);
535 let attempt = |points: Option<&HashSet<usize>>| loop {
540 let mut record = expectations.take();
541 record.restart();
542 let shared = Shared {
543 runtime_error: Rc::clone(&runtime_error),
544 global_concept_space: global_concept_space.clone(),
545 selection_diagnostics: Rc::clone(&selection_diagnostics),
546 active_embedded: Rc::new(RefCell::new(HashSet::new())),
547 selection_sources: Rc::clone(&selection_sources),
548 selection_mapping_failures: Rc::clone(&selection_mapping_failures),
549 steps: Rc::new(Cell::new(0)),
550 limit,
551 frames: Rc::new(Cell::new(0)),
552 memo_limit: options.memo_limit.unwrap_or(DEFAULT_MEMO_LIMIT),
553 cells: Rc::clone(&cells),
554 lexical_caches: Rc::clone(&lexical_caches),
555 memory_limit,
556 expectations: RefCell::new(record),
557 };
558 let outcome = {
559 let mut executor = Executor::new(
560 compiled,
561 compiled.main,
562 bytes,
563 0,
564 bytes.len(),
565 &shared,
566 max_depth,
567 );
568 executor.repair_points = points.cloned();
569 executor.keywords = keywords.as_ref();
570 let outcome = executor.run(start_rule);
571 last_steps.set(shared.steps.get());
572 outcome
573 };
574 let record = shared.expectations.into_inner();
575 let stale = record.stale;
576 expectations.replace(record);
577 if outcome.is_err() || !stale {
578 break outcome;
579 }
580 };
581 let recovery = options.error_recovery == Some(true);
582 let outcome = loop {
583 let outcome =
585 attempt(recovery.then(HashSet::new).as_ref()).and_then(|outcome| match outcome {
586 Outcome::Failed { .. } if recovery => repair_parse(
587 outcome,
588 options.max_repairs.unwrap_or(DEFAULT_MAX_REPAIRS),
589 attempt,
590 ),
591 outcome => Ok(outcome),
592 });
593 if let (Ok(Outcome::Parsed(root)), Some(keywords), Some(tokens)) =
594 (&outcome, &keywords, tokens)
595 && keywords.borrow_mut().conflicts(
596 root,
597 tokens,
598 &compiled.programs[compiled.main].rules,
599 )
600 {
601 continue;
602 }
603 break outcome;
604 };
605 let root = match outcome {
606 Err(Abort::Operation) => {
607 return Err(runtime_error
608 .borrow_mut()
609 .take()
610 .expect("operation abort retains its runtime error"));
611 }
612 Err(Abort::StepLimit) => {
613 return refused(ParseRejection::limited("stepLimit", limit), None);
614 }
615 Err(Abort::MemoryBudget) => {
616 return refused(ParseRejection::limited("memoryBudget", memory_limit), None);
617 }
618 Err(Abort::NestingTooDeep) => {
619 let tree = tree::error_tree(bytes, 0, bytes.len(), Some("nestingDepth"));
620 return refused(
621 ParseRejection::limited("nestingDepth", max_depth),
622 Some(tree),
623 );
624 }
625 Ok(Outcome::Failed {
626 farthest, expected, ..
627 }) => {
628 if let Some(rejection) =
629 grammar_selection::selection_rejection(&selection_diagnostics.borrow(), bytes)
630 {
631 return refused(rejection, None);
632 }
633 if let Some(mut rejection) =
634 grammar_selection::mapping_rejection(&selection_mapping_failures.borrow(), bytes)
635 {
636 rejection.expected = Some(expected);
637 return refused(rejection, None);
638 }
639 let mut rejection = ParseRejection::positioned("syntax", bytes, farthest);
640 rejection.expected = Some(expected);
641 return refused(rejection, None);
642 }
643 Ok(Outcome::Parsed(root)) => root,
644 };
645 let root = if let Some(language) = options
648 .grammar_name
649 .as_deref()
650 .filter(|name| !name.is_empty() && global_concept_space.is_some())
651 {
652 let shared = Shared {
653 runtime_error: Rc::clone(&runtime_error),
654 global_concept_space,
655 selection_diagnostics: Rc::clone(&selection_diagnostics),
656 active_embedded: Rc::new(RefCell::new(HashSet::new())),
657 selection_sources: Rc::clone(&selection_sources),
658 selection_mapping_failures: Rc::clone(&selection_mapping_failures),
659 steps: Rc::new(Cell::new(last_steps.get())),
660 limit,
661 frames: Rc::new(Cell::new(0)),
662 memo_limit: options.memo_limit.unwrap_or(DEFAULT_MEMO_LIMIT),
663 cells: Rc::clone(&cells),
664 lexical_caches: Rc::clone(&lexical_caches),
665 memory_limit,
666 expectations: RefCell::new(Expectations::default()),
667 };
668 let executor = Executor::new(
669 compiled,
670 compiled.main,
671 bytes,
672 0,
673 bytes.len(),
674 &shared,
675 max_depth,
676 );
677 match executor.qualify_grammar_root(root, language) {
678 Ok(root) => root,
679 Err(Abort::Operation) => {
680 return Err(runtime_error
681 .borrow_mut()
682 .take()
683 .expect("operation abort retains its runtime error"));
684 }
685 Err(Abort::StepLimit) => {
686 return refused(ParseRejection::limited("stepLimit", limit), None);
687 }
688 Err(Abort::MemoryBudget) => {
689 return refused(ParseRejection::limited("memoryBudget", memory_limit), None);
690 }
691 Err(Abort::NestingTooDeep) => {
692 return refused(
693 ParseRejection::limited("nestingDepth", max_depth),
694 Some(tree::error_tree(
695 bytes,
696 0,
697 bytes.len(),
698 Some("nestingDepth"),
699 )),
700 );
701 }
702 }
703 } else {
704 root
705 };
706 let source_planes = selection_sources.borrow().definitions();
707 let publication_issue = crate::translation::grammar_rule_composition_rules::read_grammar_composition_publication_issue(
708 source_planes.is_some(),
709 options.decorators.has(DecoratorLevel::Executor)
710 || options.decorators.has(DecoratorLevel::Recovery),
711 );
712 if !publication_issue.is_empty() {
713 return Err(decorator_error(DecoratorError::new(publication_issue)));
714 }
715 let tree = tree::public_tree(&root, bytes);
716 let mut ambiguities = Vec::new();
717 tree::collect_ambiguities(&root, compiled, compiled.main, &mut ambiguities);
718 let recovered = tree
719 .recovery_diagnostic()?
720 .filter(|_| options.accept_recovery != Some(true))
721 .map(|recovery| {
722 let offset = recovery["start"]
723 .as_u64()
724 .and_then(|offset| usize::try_from(offset).ok())
725 .unwrap_or_default();
726 let mut rejection = ParseRejection::positioned("recovered", bytes, offset);
727 if recovery.get("source").is_some() {
728 rejection.offset_semantics = Some("covering-source-spelling".to_owned());
729 rejection.diagnostics = Some(vec![recovery]);
730 }
731 rejection
732 });
733 let rejection = grammar_selection::selection_rejection(&selection_diagnostics.borrow(), bytes)
734 .or(recovered)
735 .or_else(|| {
736 ambiguities
737 .first()
738 .filter(|_| options.reject_ambiguity == Some(true))
739 .map(|first| ParseRejection::positioned("ambiguity", bytes, first.start))
740 });
741 Ok(ParseOutcome {
742 ok: rejection.is_none(),
743 tree: Some(tree),
744 ambiguities,
745 rejection,
746 source_planes,
747 })
748}