Skip to main content

meta_language/global_concept_space/
parser.rs

1//! Archive-only grammar resolution delegates to the ordinary grammar runtime.
2
3use std::collections::BTreeMap;
4
5use super::links::read_validated_global_concept_archive;
6use super::{GlobalConceptOptions, GlobalConceptSource};
7use crate::global_concept_identity_rules::contains_global_concept_identity;
8use crate::grammar::feature_runtime::{
9    FeatureGrammarParser, FeatureParseOptions, GrammarParseError, GrammarRuntimeError,
10    ParseOutcome, ParseRejection, ParseWithGrammarError, SyntaxTree, compile_feature_grammar,
11};
12
13/// A parser whose grammar identity and resolver belong to its validated archive.
14#[derive(Debug)]
15pub struct GlobalConceptSpaceParser {
16    parser: FeatureGrammarParser,
17}
18
19fn require_global_concept_parser_options(
20    options: &FeatureParseOptions,
21) -> Result<(), GrammarRuntimeError> {
22    // Typed options express presence through Some; there is no resolver override.
23    let name = if options.global_concept_space.is_some() {
24        Some("globalConceptSpace")
25    } else if options.grammar_name.is_some() {
26        Some("grammarName")
27    } else {
28        None
29    };
30    if let Some(name) = name {
31        return Err(GrammarRuntimeError {
32            reason: "globalConceptSpace",
33            message: format!("the archived global concept space owns parser option {name}"),
34        });
35    }
36    Ok(())
37}
38
39const fn archive_error(message: String) -> GrammarRuntimeError {
40    GrammarRuntimeError {
41        reason: "globalConceptSpace",
42        message,
43    }
44}
45
46/// Validates a complete archive and compiles one exact archived source identity.
47///
48/// All imports and embeddings resolve from reconstructed archived grammars.
49/// `settings.records` configures archive validation; parser limits and decorators
50/// come from `options`. A supplied grammar name or concept space is refused.
51///
52/// # Errors
53/// Returns the existing archive or compilation error, or a `selection` error
54/// when `source_identifier` is not an exact archived source identifier.
55pub fn create_global_concept_space_parser(
56    source: &str,
57    source_identifier: &str,
58    settings: &GlobalConceptOptions,
59    mut options: FeatureParseOptions,
60) -> Result<GlobalConceptSpaceParser, GrammarRuntimeError> {
61    require_global_concept_parser_options(&options)?;
62    let archive = read_validated_global_concept_archive(source, settings).map_err(archive_error)?;
63    let identities = archive
64        .imported
65        .iter()
66        .map(|source| super::string(&source["id"]).map(str::to_owned))
67        .collect::<Result<Vec<_>, _>>()
68        .map_err(archive_error)?;
69    if !contains_global_concept_identity(&identities, source_identifier.to_owned()) {
70        return Err(GrammarRuntimeError {
71            reason: "selection",
72            message: "an archived grammar needs an exact existing source identifier".to_owned(),
73        });
74    }
75    let grammars = archive
76        .imported
77        .iter()
78        .map(|source| {
79            GlobalConceptSource::from_json(source).map(|source| (source.id, source.grammar))
80        })
81        .collect::<Result<BTreeMap<_, _>, _>>()
82        .map_err(archive_error)?;
83    let grammar = &grammars[source_identifier];
84    let resolve = |name: &str| grammars.get(name).cloned();
85    options.grammar_name = Some(source_identifier.to_owned());
86    options.global_concept_space = Some(archive.space);
87    let parser = compile_feature_grammar(grammar, Some(&resolve), options)?;
88    Ok(GlobalConceptSpaceParser { parser })
89}
90
91impl GlobalConceptSpaceParser {
92    /// Parses with the archive's identity, preserving ordinary CST and budgets.
93    ///
94    /// # Errors
95    /// Returns a runtime error for protected option overrides or an invalid start.
96    pub fn parse_tree(
97        &self,
98        source: &[u8],
99        options: &FeatureParseOptions,
100    ) -> Result<ParseOutcome, GrammarRuntimeError> {
101        require_global_concept_parser_options(options)?;
102        self.parser.parse_tree(source, options)
103    }
104
105    /// Parses into the concrete tree under the archive's identity.
106    ///
107    /// # Errors
108    /// Returns `Runtime` for a protected option override or runtime failure,
109    /// and `Parse` for an ordinary input rejection.
110    pub fn parse(
111        &self,
112        source: &[u8],
113        options: &FeatureParseOptions,
114    ) -> Result<SyntaxTree, ParseWithGrammarError> {
115        let outcome = self
116            .parse_tree(source, options)
117            .map_err(ParseWithGrammarError::Runtime)?;
118        if outcome.ok && outcome.source_planes.is_some() {
119            return Err(ParseWithGrammarError::Runtime(GrammarRuntimeError {
120                reason: "selection",
121                message: "a mapped grammar result needs parseTree to retain its sourcePlanes"
122                    .to_owned(),
123            }));
124        }
125        match (outcome.rejection, outcome.tree) {
126            (None, Some(tree)) => Ok(tree),
127            (rejection, _) => Err(ParseWithGrammarError::Parse(GrammarParseError {
128                rejection: Box::new(rejection.unwrap_or(ParseRejection {
129                    diagnostics: None,
130                    offset_semantics: None,
131                    reason: "syntax",
132                    offset: Some(0),
133                    line: Some(1),
134                    column: Some(1),
135                    expected: None,
136                    limit: None,
137                })),
138            })),
139        }
140    }
141}