Skip to main content

md_tmpl_core/template/
mod.rs

1use alloc::{
2    string::{String, ToString},
3    sync::Arc,
4    vec::Vec,
5};
6#[cfg(feature = "std")]
7use std::path::{Path, PathBuf};
8
9use crate::{
10    compat::{HashMap, HashSet},
11    compiled::{self, CompiledInlineTemplate, Segment},
12    context::Context,
13    error::TemplateError,
14    frontmatter::{self, Frontmatter},
15    types::VarDecl,
16    value::Value,
17};
18
19pub(crate) mod analysis;
20mod render_methods;
21#[cfg(not(feature = "std"))]
22use self::analysis::hash_source_no_std;
23use self::analysis::{
24    check_bare_enum_access, check_internal_key_access, check_name_collisions,
25    check_static_enum_in_conditions, check_undeclared_variables, check_unused_params,
26    collect_enum_type_keys, inject_enum_type_constants,
27};
28
29/// Configuration for template compilation.
30///
31/// Collects all optional parameters that previously required separate
32/// constructor functions. Use with [`Template::compile`] or
33/// [`Template::compile_file`].
34///
35/// # Examples
36///
37/// ```
38/// use md_tmpl_core::CompileOptions;
39///
40/// // Default options (strict mode):
41/// let opts = CompileOptions::default();
42///
43/// // Allow unused declared parameters:
44/// let opts = CompileOptions::default().allow_unused(true);
45/// ```
46#[non_exhaustive]
47#[derive(Debug, Clone, Copy, Default)]
48pub struct CompileOptions<'a> {
49    /// When `true`, declared parameters that are never referenced in the
50    /// template body are allowed instead of producing an error.
51    ///
52    /// Equivalent to `allow_unused: true` in frontmatter.
53    pub allow_unused: bool,
54    /// Base directory for resolving `{% include %}` and `{% import %}` directives.
55    ///
56    /// When `None`, includes are not resolved (suitable for in-memory templates).
57    #[cfg(feature = "std")]
58    pub base_dir: Option<&'a std::path::Path>,
59    /// Compile-time environment variables (name-value pairs).
60    /// Values are typed — they must match the type declared in `env:` frontmatter.
61    /// String values for scalar types (int, bool, float) are auto-parsed.
62    pub env: &'a [(&'a str, crate::Value)],
63    // Lifetime anchor for no_std where base_dir doesn't exist.
64    #[cfg(not(feature = "std"))]
65    _phantom: core::marker::PhantomData<&'a ()>,
66}
67
68#[cfg(feature = "std")]
69impl<'a> CompileOptions<'a> {
70    /// Set the base directory for include resolution.
71    #[must_use]
72    pub fn base_dir(mut self, dir: &'a std::path::Path) -> Self {
73        self.base_dir = Some(dir);
74        self
75    }
76}
77
78impl<'a> CompileOptions<'a> {
79    /// Allow unused declared parameters.
80    #[must_use]
81    pub fn allow_unused(mut self, allow: bool) -> Self {
82        self.allow_unused = allow;
83        self
84    }
85
86    /// Set compile-time environment variables.
87    #[must_use]
88    pub fn env(mut self, pairs: &'a [(&'a str, crate::Value)]) -> Self {
89        self.env = pairs;
90        self
91    }
92}
93
94/// A parsed template ready for rendering.
95///
96/// Templates can be loaded from files or parsed from in-memory strings.
97/// Variable declarations from frontmatter are used for context validation
98/// before rendering.
99pub struct Template {
100    /// The template body text (after stripping frontmatter).
101    body: String,
102    /// Template name (from frontmatter).
103    name: Option<String>,
104    /// Template description (from frontmatter).
105    description: Option<String>,
106    /// Pre-compiled segment instructions (the fast render path).
107    segments: Arc<[Segment]>,
108    /// Declared variables from frontmatter.
109    declared_variables: Arc<[VarDecl]>,
110    /// Base directory for resolving includes (from file path).
111    #[cfg(feature = "std")]
112    base_dir: Option<PathBuf>,
113    /// Pre-compiled inline template definitions (`{% tmpl name %}...{% /tmpl %}`).
114    inline_templates: Arc<HashMap<String, CompiledInlineTemplate>>,
115    source_hash: u64,
116    max_include_depth: usize,
117    /// Pre-computed: true if any declared variable has a default value.
118    has_defaults: bool,
119    /// Constants defined in this template.
120    consts: Arc<HashMap<String, crate::value::Value>>,
121    /// Imported constants keyed by `stem.NAME`.
122    imported_consts: Arc<HashMap<String, crate::value::Value>>,
123    /// Pre-computed estimated output capacity (cached from segment tree walk).
124    estimated_capacity: usize,
125    /// Compile-time environment values, propagated to included files so their
126    /// `env:` frontmatter declarations can be resolved.
127    #[cfg(feature = "std")]
128    env_values: alloc::sync::Arc<[(String, Value)]>,
129    /// Pre-computed set of all declared variable names and constants.
130    declared_names: Arc<HashSet<String>>,
131    /// Cached `TypeId`s of Rust types that have passed validation.
132    ///
133    /// When `render::<T>()` is called, the first invocation runs full
134    /// `validate_context`. If it passes, `TypeId::of::<T>()` is stored
135    /// here so subsequent calls skip validation entirely.
136    #[cfg(feature = "std")]
137    checked_type_ids: std::sync::Mutex<Vec<core::any::TypeId>>,
138}
139
140impl core::fmt::Debug for Template {
141    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
142        f.debug_struct("Template")
143            .field("body", &self.body)
144            .field("name", &self.name)
145            .field("description", &self.description)
146            .field("segments", &self.segments)
147            .field("declared_variables", &self.declared_variables)
148            .field("source_hash", &self.source_hash)
149            .finish_non_exhaustive()
150    }
151}
152
153impl Clone for Template {
154    fn clone(&self) -> Self {
155        Self {
156            body: self.body.clone(),
157            name: self.name.clone(),
158            description: self.description.clone(),
159            segments: self.segments.clone(),
160            declared_variables: self.declared_variables.clone(),
161            #[cfg(feature = "std")]
162            base_dir: self.base_dir.clone(),
163            inline_templates: self.inline_templates.clone(),
164            source_hash: self.source_hash,
165            max_include_depth: self.max_include_depth,
166            has_defaults: self.has_defaults,
167            consts: self.consts.clone(),
168            imported_consts: self.imported_consts.clone(),
169            estimated_capacity: self.estimated_capacity,
170            #[cfg(feature = "std")]
171            env_values: self.env_values.clone(),
172            declared_names: self.declared_names.clone(),
173            // Clone inherits cached type IDs — the validation is
174            // shape-based, not instance-based.
175            #[cfg(feature = "std")]
176            checked_type_ids: std::sync::Mutex::new(
177                self.checked_type_ids
178                    .lock()
179                    .unwrap_or_else(std::sync::PoisonError::into_inner)
180                    .clone(),
181            ),
182        }
183    }
184}
185
186/// Pre-compiled template data used to reconstruct a [`Template`] from cache.
187///
188/// See [`Template::from_cached`].
189#[cfg(feature = "std")]
190pub(crate) struct CachedTemplateData {
191    /// Pre-compiled segment instructions.
192    pub segments: Arc<[Segment]>,
193    /// Declared variables from frontmatter.
194    pub declared_variables: Arc<[VarDecl]>,
195    /// Base directory for resolving includes.
196    pub base_dir: Option<PathBuf>,
197    /// Pre-compiled inline template definitions.
198    pub inline_templates: Arc<HashMap<String, CompiledInlineTemplate>>,
199    /// Content hash of the raw source.
200    pub source_hash: u64,
201    /// Constants defined in this template.
202    pub consts: Arc<HashMap<String, crate::value::Value>>,
203    /// Imported constants.
204    pub imported_consts: Arc<HashMap<String, crate::value::Value>>,
205    /// Template name.
206    pub name: Option<String>,
207    /// Template description.
208    pub description: Option<String>,
209}
210
211/// Pre-compiled template data for compile-time macro integration.
212///
213/// See [`Template::from_precompiled`].
214#[doc(hidden)]
215pub struct PrecompiledTemplateData<'a> {
216    /// Pre-compiled segment instructions.
217    pub segments: &'a [Segment],
218    /// Declared variables from frontmatter.
219    pub declared_variables: &'a [VarDecl],
220    /// Pre-compiled inline template definitions.
221    pub inline_templates: &'a [(&'a str, CompiledInlineTemplate)],
222    /// Content hash of the raw source.
223    pub source_hash: u64,
224    /// Constants defined in this template.
225    pub consts: &'a [(&'a str, crate::value::Value)],
226    /// Imported constants.
227    pub imported_consts: &'a [(&'a str, crate::value::Value)],
228    /// Template name.
229    pub name: Option<&'a str>,
230    /// Template description.
231    pub description: Option<&'a str>,
232}
233
234fn build_declared_names(
235    declarations: &[VarDecl],
236    consts: &HashMap<String, Value>,
237) -> Arc<HashSet<String>> {
238    let mut names = HashSet::with_capacity(declarations.len() + consts.len());
239    for d in declarations {
240        names.insert(d.name.clone());
241    }
242    for k in consts.keys() {
243        names.insert(k.clone());
244    }
245    Arc::new(names)
246}
247
248impl Template {
249    /// Load a template from a file, stripping YAML frontmatter.
250    ///
251    /// # Errors
252    ///
253    /// Returns [`TemplateError::Io`] if the file cannot be read.
254    #[cfg(feature = "std")]
255    pub fn from_file(path: &Path) -> Result<Self, TemplateError> {
256        let mut source = std::fs::read_to_string(path)?;
257        // Normalize CRLF → LF for cross-platform consistency.
258        if source.contains('\r') {
259            source = source.replace("\r\n", "\n");
260        }
261        let (tmpl, _fm) =
262            Self::compile_from_source(&source, Some(path.parent().unwrap_or(Path::new("."))))?;
263        Ok(tmpl)
264    }
265
266    /// Parse a template from an in-memory string (no include resolution).
267    ///
268    /// # Errors
269    ///
270    /// Returns [`TemplateError::Syntax`] if the body contains a syntax error.
271    pub fn from_source(source: &str) -> Result<Self, TemplateError> {
272        // Normalize CRLF → LF for cross-platform consistency.
273        let source = if source.contains('\r') {
274            alloc::borrow::Cow::Owned(source.replace("\r\n", "\n"))
275        } else {
276            alloc::borrow::Cow::Borrowed(source)
277        };
278        #[cfg(feature = "std")]
279        let (tmpl, _fm) = Self::compile_from_source(&source, None)?;
280        #[cfg(not(feature = "std"))]
281        let (tmpl, _fm) = Self::compile_from_source_no_std(&source)?;
282        Ok(tmpl)
283    }
284
285    /// Parse a template from source with compile options, returning both the
286    /// template and its frontmatter.
287    ///
288    /// This is the unified entry point that replaces the family of
289    /// `from_source_*` constructors.
290    ///
291    /// # Examples
292    ///
293    /// ```
294    /// use md_tmpl_core::{CompileOptions, Template};
295    ///
296    /// let (tmpl, fm) = Template::compile(
297    ///     r#"---
298    /// params: [name = str]
299    /// ---
300    /// Hello {{ name }}!"#,
301    ///     CompileOptions::default(),
302    /// )
303    /// .unwrap();
304    /// ```
305    ///
306    /// # Errors
307    ///
308    /// Returns [`TemplateError::Syntax`] if the body contains a syntax error.
309    pub fn compile(
310        source: &str,
311        options: CompileOptions<'_>,
312    ) -> Result<(Self, Frontmatter), TemplateError> {
313        // Normalize CRLF → LF so templates read on Windows produce identical
314        // output to Unix.  Uses `Cow` to avoid allocation when no `\r` present.
315        let source = if source.contains('\r') {
316            alloc::borrow::Cow::Owned(source.replace("\r\n", "\n"))
317        } else {
318            alloc::borrow::Cow::Borrowed(source)
319        };
320        #[cfg(feature = "std")]
321        return Self::compile_inner(&source, options.base_dir, options.allow_unused, options.env);
322        #[cfg(not(feature = "std"))]
323        return Self::compile_inner_no_std(&source, options.allow_unused, options.env);
324    }
325
326    /// Load a template from a file with compile options, returning both the
327    /// template and its frontmatter.
328    ///
329    /// The file's parent directory is used as the base directory for include
330    /// resolution unless overridden in `options`.
331    ///
332    /// # Examples
333    ///
334    /// ```no_run
335    /// use std::path::Path;
336    ///
337    /// use md_tmpl_core::{CompileOptions, Template};
338    ///
339    /// let (tmpl, fm) =
340    ///     Template::compile_file(Path::new("template.tmpl.md"), CompileOptions::default()).unwrap();
341    /// ```
342    ///
343    /// # Errors
344    ///
345    /// Returns [`TemplateError::Io`] if the file cannot be read.
346    #[cfg(feature = "std")]
347    pub fn compile_file(
348        path: &Path,
349        options: CompileOptions<'_>,
350    ) -> Result<(Self, Frontmatter), TemplateError> {
351        let mut source = std::fs::read_to_string(path)?;
352        // Normalize CRLF → LF for cross-platform consistency.
353        if source.contains('\r') {
354            source = source.replace("\r\n", "\n");
355        }
356        let base_dir = options.base_dir.or_else(|| path.parent());
357        Self::compile_inner(&source, base_dir, options.allow_unused, options.env)
358    }
359
360    /// Shared compilation entry point — honours `allow_unused` from frontmatter.
361    #[cfg(feature = "std")]
362    fn compile_from_source(
363        source: &str,
364        base_dir: Option<&Path>,
365    ) -> Result<(Self, Frontmatter), TemplateError> {
366        Self::compile_inner(source, base_dir, false, &[])
367    }
368
369    /// Core compilation: parse frontmatter → compile body → static analysis → build `Template`.
370    ///
371    /// When `force_allow_unused` is `true` the unused-params check is skipped
372    /// regardless of the frontmatter setting.
373    #[cfg(feature = "std")]
374    fn compile_inner(
375        source: &str,
376        base_dir: Option<&Path>,
377        force_allow_unused: bool,
378        env_values: &[(&str, Value)],
379    ) -> Result<(Self, Frontmatter), TemplateError> {
380        let source_hash = crate::cache::hash_source(source);
381        let (fm, body) = if let Some(dir) = base_dir {
382            frontmatter::parse_frontmatter_with_base_dir(source, dir, env_values)?
383        } else {
384            frontmatter::parse_frontmatter_with_env(source, env_values)?
385        };
386        let body = body.to_string();
387        let (segments, inline_templates) = compiled::compile(&body, &fm.type_aliases)?;
388
389        // --- Static analysis ---
390        run_static_analysis(&segments, &fm, &inline_templates, force_allow_unused)?;
391
392        let has_defaults = fm.declarations.iter().any(|d| d.default_value.is_some());
393        let mut consts: HashMap<String, Value> = fm
394            .consts
395            .iter()
396            .filter_map(|d| d.default_value.clone().map(|v| (d.name.clone(), v)))
397            .collect();
398        // Inject resolved env values as constants.
399        for d in &fm.env {
400            if let Some(ref v) = d.default_value {
401                consts.entry(d.name.clone()).or_insert_with(|| v.clone());
402            }
403        }
404        // Inject enum type aliases as namespace constants (e.g. Stage.Design).
405        inject_enum_type_constants(&fm.type_aliases, &mut consts);
406        let segments: Arc<[Segment]> = Arc::from(segments);
407        let estimated_capacity = compiled::render::estimate_output_capacity(&segments);
408        let env_values: alloc::sync::Arc<[(String, Value)]> = env_values
409            .iter()
410            .map(|(k, v)| (k.to_string(), v.clone()))
411            .collect();
412        let declared_names = build_declared_names(&fm.declarations, &consts);
413        let tmpl = Self {
414            body,
415            name: fm.name.clone(),
416            description: fm.description.clone(),
417            segments,
418            declared_variables: Arc::from(fm.declarations.clone()),
419            base_dir: base_dir.map(Path::to_path_buf),
420            inline_templates: Arc::new(inline_templates),
421            source_hash,
422            max_include_depth: crate::scope::MAX_INCLUDE_DEPTH,
423            has_defaults,
424            consts: Arc::new(consts),
425            imported_consts: Arc::new(fm.imported_consts.clone()),
426            estimated_capacity,
427            env_values,
428            declared_names,
429            checked_type_ids: std::sync::Mutex::new(Vec::new()),
430        };
431        Ok((tmpl, fm))
432    }
433
434    /// `no_std` compilation entry point (no base directory, no imports).
435    #[cfg(not(feature = "std"))]
436    fn compile_from_source_no_std(source: &str) -> Result<(Self, Frontmatter), TemplateError> {
437        Self::compile_inner_no_std(source, false, &[])
438    }
439
440    /// `no_std` core compilation.
441    #[cfg(not(feature = "std"))]
442    fn compile_inner_no_std(
443        source: &str,
444        force_allow_unused: bool,
445        env_values: &[(&str, Value)],
446    ) -> Result<(Self, Frontmatter), TemplateError> {
447        let source_hash = hash_source_no_std(source);
448        let (fm, body) = frontmatter::parse_frontmatter_with_env(source, env_values)?;
449        let body = body.to_string();
450        let (segments, inline_templates) = compiled::compile(&body, &fm.type_aliases)?;
451
452        run_static_analysis(&segments, &fm, &inline_templates, force_allow_unused)?;
453
454        let has_defaults = fm.declarations.iter().any(|d| d.default_value.is_some());
455        let mut consts: HashMap<String, Value> = fm
456            .consts
457            .iter()
458            .filter_map(|d| d.default_value.clone().map(|v| (d.name.clone(), v)))
459            .collect();
460        // Inject resolved env values as constants.
461        for d in &fm.env {
462            if let Some(ref v) = d.default_value {
463                consts.entry(d.name.clone()).or_insert_with(|| v.clone());
464            }
465        }
466        // Inject enum type aliases as namespace constants (e.g. Stage.Design).
467        inject_enum_type_constants(&fm.type_aliases, &mut consts);
468        let segments: Arc<[Segment]> = Arc::from(segments);
469        let estimated_capacity = compiled::render::estimate_output_capacity(&segments);
470        let declared_names = build_declared_names(&fm.declarations, &consts);
471        let tmpl = Self {
472            body,
473            name: fm.name.clone(),
474            description: fm.description.clone(),
475            segments,
476            declared_variables: Arc::from(fm.declarations.clone()),
477            inline_templates: Arc::new(inline_templates),
478            source_hash,
479            max_include_depth: crate::scope::MAX_INCLUDE_DEPTH,
480            has_defaults,
481            consts: Arc::new(consts),
482            imported_consts: Arc::new(fm.imported_consts.clone()),
483            estimated_capacity,
484            declared_names,
485        };
486        Ok((tmpl, fm))
487    }
488
489    /// Construct a `Template` from pre-compiled segments (used by [`TemplateCache`]).
490    ///
491    /// Skips parsing and compilation entirely — the caller is responsible for
492    /// providing correct, pre-compiled data.
493    ///
494    /// [`TemplateCache`]: crate::TemplateCache
495    #[cfg(feature = "std")]
496    pub(crate) fn from_cached(data: CachedTemplateData) -> Self {
497        let has_defaults = data
498            .declared_variables
499            .iter()
500            .any(|d| d.default_value.is_some());
501        let estimated_capacity = compiled::render::estimate_output_capacity(&data.segments);
502        let declared_names = build_declared_names(&data.declared_variables, &data.consts);
503        Self {
504            body: String::new(),
505            name: data.name,
506            description: data.description,
507            segments: data.segments,
508            declared_variables: data.declared_variables,
509            base_dir: data.base_dir,
510            inline_templates: data.inline_templates,
511            source_hash: data.source_hash,
512            max_include_depth: crate::scope::MAX_INCLUDE_DEPTH,
513            has_defaults,
514            consts: data.consts,
515            imported_consts: data.imported_consts,
516            estimated_capacity,
517            env_values: alloc::sync::Arc::from([]),
518            declared_names,
519            checked_type_ids: std::sync::Mutex::new(Vec::new()),
520        }
521    }
522
523    /// Construct a `Template` from pre-compiled static structures (used by compile-time macros).
524    #[doc(hidden)]
525    #[must_use]
526    pub fn from_precompiled(data: &PrecompiledTemplateData<'_>) -> Self {
527        let inline_map = data
528            .inline_templates
529            .iter()
530            .map(|(k, v)| (k.to_string(), v.clone()))
531            .collect();
532        let const_map = data
533            .consts
534            .iter()
535            .map(|(k, v)| (k.to_string(), v.clone()))
536            .collect();
537        let imported_const_map = data
538            .imported_consts
539            .iter()
540            .map(|(k, v)| (k.to_string(), v.clone()))
541            .collect();
542        let has_defaults = data
543            .declared_variables
544            .iter()
545            .any(|d| d.default_value.is_some());
546        let segments: Arc<[Segment]> = Arc::from(data.segments);
547        let estimated_capacity = compiled::render::estimate_output_capacity(&segments);
548        let declared_names = build_declared_names(data.declared_variables, &const_map);
549        Self {
550            body: String::new(),
551            name: data.name.map(String::from),
552            description: data.description.map(String::from),
553            segments,
554            declared_variables: Arc::from(data.declared_variables),
555            #[cfg(feature = "std")]
556            base_dir: None,
557            inline_templates: Arc::new(inline_map),
558            source_hash: data.source_hash,
559            max_include_depth: crate::scope::MAX_INCLUDE_DEPTH,
560            has_defaults,
561            consts: Arc::new(const_map),
562            imported_consts: Arc::new(imported_const_map),
563            estimated_capacity,
564            #[cfg(feature = "std")]
565            env_values: alloc::sync::Arc::from([]),
566            declared_names,
567            #[cfg(feature = "std")]
568            checked_type_ids: std::sync::Mutex::new(Vec::new()),
569        }
570    }
571
572    /// Validate context: check presence, types, AND no extra variables.
573    ///
574    /// By default the engine is strict: passing undeclared parameters is
575    /// an error. Set `allow_extra` to `true` to suppress the extra-params
576    /// check (useful when forwarding a shared context to multiple templates).
577    ///
578    /// # Errors
579    ///
580    /// Returns [`TemplateError::MissingParams`] if any declared variable
581    /// is absent, [`TemplateError::TypeMismatch`] if a value has the
582    /// wrong type, or [`TemplateError::ExtraParams`] if undeclared keys
583    /// are present (and `allow_extra` is false).
584    fn validate_context(&self, ctx: &Context, allow_extra: bool) -> Result<(), TemplateError> {
585        let mut missing = Vec::new();
586        let mut mismatch: Option<(String, crate::types::TypeCheckError)> = None;
587        for decl in self.declared_variables.iter() {
588            match ctx.get(&decl.name) {
589                None => {
590                    // Skip params with defaults — they'll be injected.
591                    if decl.default_value.is_none() {
592                        missing.push(decl.name.as_str());
593                    }
594                }
595                Some(value) => {
596                    if mismatch.is_none()
597                        && let Err(e) = decl.var_type.check(value)
598                    {
599                        mismatch = Some((decl.name.clone(), e));
600                    }
601                }
602            }
603        }
604        // Report missing params first (most fundamental).
605        if !missing.is_empty() {
606            return Err(TemplateError::MissingParams(
607                missing.into_iter().map(String::from).collect(),
608            ));
609        }
610        if let Some((name, check_err)) = mismatch {
611            let detail = if check_err.path.is_empty() {
612                String::new()
613            } else {
614                format!(" (at .{})", check_err.path)
615            };
616            return Err(TemplateError::TypeMismatch {
617                name: format!("{name}{detail}"),
618                expected: check_err.expected,
619                actual: check_err.actual,
620                actual_value: check_err.actual_value,
621            });
622        }
623        // Reject extra (undeclared) parameters unless explicitly allowed.
624        if !allow_extra
625            && ctx
626                .values
627                .keys()
628                .any(|k| !self.declared_names.contains(k.as_str()))
629        {
630            let extra: Vec<String> = ctx
631                .values
632                .keys()
633                .filter(|k| !self.declared_names.contains(k.as_str()))
634                .cloned()
635                .collect();
636            return Err(TemplateError::ExtraParams(extra));
637        }
638        Ok(())
639    }
640
641    /// Returns default values for all params that have them.
642    #[must_use]
643    pub fn defaults(&self) -> HashMap<String, crate::value::Value> {
644        self.declared_variables
645            .iter()
646            .filter_map(|d| {
647                d.default_value
648                    .as_ref()
649                    .map(|v| (d.name.clone(), v.clone()))
650            })
651            .collect()
652    }
653
654    /// Returns the default value for a single parameter, if it has one.
655    #[must_use]
656    pub fn default(&self, name: &str) -> Option<&crate::value::Value> {
657        self.declared_variables
658            .iter()
659            .find(|d| d.name == name)
660            .and_then(|d| d.default_value.as_ref())
661    }
662
663    /// Returns a [`Context`] pre-filled with all default values.
664    ///
665    /// Use this as a starting point, then override only the params you need:
666    /// ```
667    /// # use md_tmpl_core::{Template, Context};
668    /// let tmpl = Template::from_source(
669    ///     r#"---
670    /// params:
671    ///   - name = str
672    ///   - count = int := 5
673    /// ---
674    /// {{ name }} ({{ count }})"#,
675    /// )
676    /// .unwrap();
677    /// let mut ctx = tmpl.defaults_context();
678    /// ctx.set("name", "Alice"); // count already has default 5
679    /// assert_eq!(tmpl.render_ctx(&ctx).unwrap(), "Alice (5)");
680    /// ```
681    #[must_use]
682    pub fn defaults_context(&self) -> Context {
683        let defaults = self.defaults();
684        let mut ctx = Context::with_capacity(defaults.len());
685        for (k, v) in defaults {
686            ctx.set(k, v);
687        }
688        ctx
689    }
690
691    /// Return the raw template body text (after frontmatter stripping).
692    ///
693    /// Useful for compile-time validation and macro integration.
694    #[must_use]
695    pub fn body(&self) -> &str {
696        &self.body
697    }
698
699    /// Returns the template's name, if defined in frontmatter.
700    #[must_use]
701    pub fn name(&self) -> Option<&str> {
702        self.name.as_deref()
703    }
704
705    /// Returns the template's description, if defined in frontmatter.
706    #[must_use]
707    pub fn description(&self) -> Option<&str> {
708        self.description.as_deref()
709    }
710
711    /// Set the maximum include depth for rendering this template.
712    pub fn set_max_include_depth(&mut self, depth: usize) {
713        self.max_include_depth = depth;
714    }
715
716    /// Set the maximum include depth for rendering this template (builder style).
717    #[must_use]
718    pub fn with_max_include_depth(mut self, depth: usize) -> Self {
719        self.max_include_depth = depth;
720        self
721    }
722
723    /// Return the declared variables from frontmatter.
724    ///
725    /// Used by generated param structs to validate that a reloaded template
726    /// still matches the compile-time variable declarations.
727    #[must_use]
728    pub fn declarations(&self) -> &[VarDecl] {
729        &self.declared_variables
730    }
731
732    pub(crate) fn segments(&self) -> &[crate::compiled::Segment] {
733        &self.segments
734    }
735
736    /// Returns the base directory used for resolving filesystem `{% include %}` paths.
737    #[cfg(feature = "std")]
738    #[must_use]
739    pub fn base_dir(&self) -> Option<&Path> {
740        self.base_dir.as_deref()
741    }
742
743    /// Returns the constants defined in this template's frontmatter.
744    ///
745    /// Constants are defined with `consts:` in frontmatter and are automatically
746    /// available during rendering without being passed in the context.
747    ///
748    /// # Examples
749    ///
750    /// ```
751    /// use md_tmpl_core::Template;
752    ///
753    /// let tmpl = Template::from_source(
754    ///     r#"---
755    /// consts:
756    ///   - MAX = int := 100
757    ///
758    /// params: []
759    /// ---
760    /// {{ MAX }}"#,
761    /// )
762    /// .unwrap();
763    /// let consts = tmpl.consts();
764    /// assert_eq!(consts.get("MAX").unwrap().as_int(), Some(100));
765    /// ```
766    #[must_use]
767    pub fn consts(&self) -> Arc<HashMap<String, Value>> {
768        self.consts.clone()
769    }
770
771    /// Returns a borrowed reference to the constants defined in this
772    /// template's frontmatter, avoiding the [`Arc`] clone of [`consts`](Self::consts).
773    #[must_use]
774    pub fn consts_ref(&self) -> &HashMap<String, Value> {
775        &self.consts
776    }
777
778    /// Returns the imported constants (from `{% import %}` directives).
779    ///
780    /// These are constants imported from other template files and are
781    /// automatically available during rendering alongside regular constants.
782    #[must_use]
783    pub fn imported_consts(&self) -> Arc<HashMap<String, Value>> {
784        self.imported_consts.clone()
785    }
786
787    /// Returns a borrowed reference to the imported constants, avoiding
788    /// the [`Arc`] clone of [`imported_consts`](Self::imported_consts).
789    #[must_use]
790    pub fn imported_consts_ref(&self) -> &HashMap<String, Value> {
791        &self.imported_consts
792    }
793
794    pub(crate) fn inline_templates(&self) -> &HashMap<String, CompiledInlineTemplate> {
795        &self.inline_templates
796    }
797
798    /// Content hash of the raw source — use to detect unchanged files on
799    /// hot-reload without re-parsing.
800    ///
801    /// Same source → same hash.  Different source → (very likely) different
802    /// hash.  This is a fast non-cryptographic hash, not suitable for
803    /// security purposes.
804    #[must_use]
805    pub fn source_hash(&self) -> u64 {
806        self.source_hash
807    }
808
809    /// Validate that a (possibly reloaded) template's variable declarations
810    /// match an expected set.
811    ///
812    /// Call this after re-loading a template from disk to ensure that
813    /// nobody (e.g. an autonomous agent editing markdown files at runtime)
814    /// has modified the `params:` block in the frontmatter.
815    ///
816    /// The template body may be changed freely — only the variable
817    /// declarations must remain stable.
818    ///
819    /// # Errors
820    ///
821    /// Returns [`TemplateError::DeclarationsMutated`] with a human-readable
822    /// diff if the declarations don't match.
823    pub fn validate_declarations(&self, expected: &[VarDecl]) -> Result<(), TemplateError> {
824        let current: HashMap<&str, &crate::types::VarType> = self
825            .declared_variables
826            .iter()
827            .map(|d| (d.name.as_str(), &d.var_type))
828            .collect();
829        let expected_map: HashMap<&str, &crate::types::VarType> = expected
830            .iter()
831            .map(|d| (d.name.as_str(), &d.var_type))
832            .collect();
833
834        let current_names: HashSet<&str> = current.keys().copied().collect();
835        let expected_names: HashSet<&str> = expected_map.keys().copied().collect();
836
837        let missing: Vec<&str> = expected_names.difference(&current_names).copied().collect();
838        let extra: Vec<&str> = current_names.difference(&expected_names).copied().collect();
839
840        // Check for type changes on variables that exist in both.
841        let retyped: Vec<String> = current_names
842            .intersection(&expected_names)
843            .filter_map(|name| {
844                let cur_type = current[name];
845                let exp_type = expected_map[name];
846                if cur_type == exp_type {
847                    None
848                } else {
849                    Some(format!("{name}: {exp_type} → {cur_type}"))
850                }
851            })
852            .collect();
853
854        if missing.is_empty() && extra.is_empty() && retyped.is_empty() {
855            return Ok(());
856        }
857
858        let mut parts = Vec::new();
859        if !missing.is_empty() {
860            parts.push(format!("removed: {}", missing.join(", ")));
861        }
862        if !extra.is_empty() {
863            parts.push(format!("added: {}", extra.join(", ")));
864        }
865        if !retyped.is_empty() {
866            parts.push(format!("retyped: {}", retyped.join(", ")));
867        }
868
869        Err(TemplateError::DeclarationsMutated {
870            details: parts.join("; "),
871        })
872    }
873}
874
875// ---------------------------------------------------------------------------
876// Trait impls for embedding Template in macro-generated structs
877// ---------------------------------------------------------------------------
878
879/// Two templates are considered equal if they were compiled from the same
880/// source (compared via non-cryptographic 64-bit hash).
881///
882/// **Note:** This is an approximate comparison — different sources that
883/// produce the same hash would incorrectly compare as equal.  Do not use
884/// `Template` as a `HashMap` key or rely on `Eq` for deduplication in
885/// security-sensitive contexts.  For exact source comparison, compare
886/// [`body()`](Self::body) and [`declarations()`](Self::declarations).
887impl PartialEq for Template {
888    fn eq(&self, other: &Self) -> bool {
889        self.source_hash == other.source_hash
890    }
891}
892
893impl Eq for Template {}
894
895/// Serialize a [`Template`] as a source-hash identifier.
896///
897/// Templates embedded in macro-generated parameter structs need `Serialize`
898/// to satisfy derive bounds, even when the struct is never actually
899/// serialized.  The hash lets debug/logging code produce something readable.
900#[cfg(feature = "serde")]
901impl serde::Serialize for Template {
902    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
903        serializer.serialize_str(&format!("template:{:016x}", self.source_hash))
904    }
905}
906
907/// Deserialize always fails — [`Template`] must be constructed from source.
908///
909/// This impl exists solely to satisfy derive bounds on macro-generated
910/// parameter structs.  Actual deserialization of a compiled template is not
911/// meaningful.
912#[cfg(feature = "serde")]
913impl<'de> serde::Deserialize<'de> for Template {
914    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
915        // NOLINT: serde's IgnoredAny pattern — the value is intentionally discarded to consume input
916        let _ = <serde::de::IgnoredAny as serde::Deserialize>::deserialize(deserializer)?;
917        Err(serde::de::Error::custom(
918            "Template cannot be deserialized; construct from source with \
919             Template::from_source() or Template::from_file()",
920        ))
921    }
922}
923
924fn run_static_analysis(
925    segments: &[Segment],
926    fm: &Frontmatter,
927    inline_templates: &HashMap<String, compiled::CompiledInlineTemplate>,
928    force_allow_unused: bool,
929) -> Result<(), TemplateError> {
930    let referenced = compiled::collect_referenced_params(segments);
931    let case_labels = compiled::collect_unquoted_case_labels(segments);
932    check_undeclared_variables(&referenced, fm, inline_templates)?;
933    check_unused_params(
934        &fm.declarations,
935        &referenced,
936        &case_labels,
937        force_allow_unused || fm.allow_unused,
938    )?;
939    check_name_collisions(fm, inline_templates, segments)?;
940    let enum_keys = collect_enum_type_keys(fm);
941    check_bare_enum_access(segments, &enum_keys)?;
942    check_static_enum_in_conditions(segments, &fm.type_aliases)?;
943    check_internal_key_access(segments)?;
944    let label_errors =
945        compiled::validate_match_labels(segments, &fm.declarations, &fm.type_aliases);
946    if !label_errors.is_empty() {
947        return Err(TemplateError::Syntax(label_errors.join("; ").into()));
948    }
949    Ok(())
950}
951
952/// Load a named template from a directory.
953///
954/// Looks for `<name>.tmpl.md` in `dir`.
955///
956/// # Errors
957///
958/// Returns [`TemplateError::Io`] if the file is not found or cannot be read.
959#[cfg(feature = "std")]
960pub fn load_template(dir: &Path, name: &str) -> Result<Template, TemplateError> {
961    let path = dir.join(format!("{name}.tmpl.md"));
962    Template::from_file(&path)
963}
964
965#[cfg(all(test, feature = "std"))]
966mod adversarial_tests;
967#[cfg(all(test, feature = "std"))]
968mod collision_and_scope_tests;
969#[cfg(all(test, feature = "std"))]
970mod const_tests;
971#[cfg(all(test, feature = "std"))]
972mod error_diagnostic_tests;
973#[cfg(all(test, feature = "std"))]
974mod higher_order_tests;
975#[cfg(all(test, feature = "std"))]
976mod inline_edge_tests;
977#[cfg(all(test, feature = "std"))]
978mod render_integration_tests;
979#[cfg(all(test, feature = "std"))]
980mod shared_tests;
981#[cfg(all(test, feature = "std"))]
982mod tests;
983
984#[cfg(all(test, feature = "std"))]
985mod doc_example_tests;