nmd_core/compilation/compilation_rule/
reference_rule.rs1use std::fmt::Debug;
2use regex::Regex;
3use crate::compilable_text::compilable_text_part::{CompilableTextPart, CompilableTextPartType};
4use crate::compilable_text::CompilableText;
5use crate::{codex::modifier::standard_text_modifier::StandardTextModifier, compilation::compilation_configuration::{compilation_configuration_overlay::CompilationConfigurationOverLay, CompilationConfiguration}, output_format::OutputFormat};
6use super::CompilationRule;
7use crate::compilation::compilation_error::CompilationError;
8
9
10pub struct ReferenceRule {
11 search_pattern: String,
12 search_pattern_regex: Regex,
13}
14
15impl ReferenceRule {
16 pub fn new() -> Self {
17 Self {
18 search_pattern: StandardTextModifier::Reference.modifier_pattern(),
19 search_pattern_regex: StandardTextModifier::Reference.modifier_pattern_regex().clone(),
20 }
21 }
22}
23
24impl Debug for ReferenceRule {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 f.debug_struct("ReferenceRule").field("searching_pattern", &self.search_pattern).finish()
27 }
28}
29
30impl CompilationRule for ReferenceRule {
31
32 fn search_pattern(&self) -> &String {
33 &self.search_pattern
34 }
35
36 fn standard_compile(&self, compilable: &CompilableText, _format: &OutputFormat, compilation_configuration: &CompilationConfiguration, _compilation_configuration_overlay: CompilationConfigurationOverLay) -> Result<CompilableText, CompilationError> {
37
38 let mut compiled_parts = Vec::new();
39
40 for matc in self.search_pattern_regex.captures_iter(&compilable.compilable_content()) {
41
42 let reference_key = matc.get(1).unwrap().as_str();
43
44 if let Some(reference) = compilation_configuration.references().get(reference_key) {
45
46 let reference_part = CompilableTextPart::new(
47 reference.clone(),
48 CompilableTextPartType::Fixed
49 );
50
51 compiled_parts.push(reference_part);
52
53 } else {
54
55 log::error!("reference '{}' ('{}') not found: no replacement will be applied", reference_key, matc.get(0).unwrap().as_str());
56
57 if compilation_configuration.strict_reference_check() {
58 return Err(CompilationError::ElaborationErrorVerbose(format!("reference '{}' ('{}') not found: no replacement will be applied", reference_key, matc.get(0).unwrap().as_str())))
59 }
60 }
61
62 }
63
64 Ok(CompilableText::new(compiled_parts))
65 }
66
67 fn search_pattern_regex(&self) -> &Regex {
68 &self.search_pattern_regex
69 }
70}