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#[non_exhaustive]
47#[derive(Debug, Clone, Copy, Default)]
48pub struct CompileOptions<'a> {
49 pub allow_unused: bool,
54 #[cfg(feature = "std")]
58 pub base_dir: Option<&'a std::path::Path>,
59 pub env: &'a [(&'a str, crate::Value)],
63 #[cfg(not(feature = "std"))]
65 _phantom: core::marker::PhantomData<&'a ()>,
66}
67
68#[cfg(feature = "std")]
69impl<'a> CompileOptions<'a> {
70 #[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 #[must_use]
81 pub fn allow_unused(mut self, allow: bool) -> Self {
82 self.allow_unused = allow;
83 self
84 }
85
86 #[must_use]
88 pub fn env(mut self, pairs: &'a [(&'a str, crate::Value)]) -> Self {
89 self.env = pairs;
90 self
91 }
92}
93
94pub struct Template {
100 body: String,
102 name: Option<String>,
104 description: Option<String>,
106 segments: Arc<[Segment]>,
108 declared_variables: Arc<[VarDecl]>,
110 #[cfg(feature = "std")]
112 base_dir: Option<PathBuf>,
113 inline_templates: Arc<HashMap<String, CompiledInlineTemplate>>,
115 source_hash: u64,
116 max_include_depth: usize,
117 has_defaults: bool,
119 consts: Arc<HashMap<String, crate::value::Value>>,
121 imported_consts: Arc<HashMap<String, crate::value::Value>>,
123 estimated_capacity: usize,
125 #[cfg(feature = "std")]
128 env_values: alloc::sync::Arc<[(String, Value)]>,
129 declared_names: Arc<HashSet<String>>,
131 #[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 #[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#[cfg(feature = "std")]
190pub(crate) struct CachedTemplateData {
191 pub segments: Arc<[Segment]>,
193 pub declared_variables: Arc<[VarDecl]>,
195 pub base_dir: Option<PathBuf>,
197 pub inline_templates: Arc<HashMap<String, CompiledInlineTemplate>>,
199 pub source_hash: u64,
201 pub consts: Arc<HashMap<String, crate::value::Value>>,
203 pub imported_consts: Arc<HashMap<String, crate::value::Value>>,
205 pub name: Option<String>,
207 pub description: Option<String>,
209}
210
211#[doc(hidden)]
215pub struct PrecompiledTemplateData<'a> {
216 pub segments: &'a [Segment],
218 pub declared_variables: &'a [VarDecl],
220 pub inline_templates: &'a [(&'a str, CompiledInlineTemplate)],
222 pub source_hash: u64,
224 pub consts: &'a [(&'a str, crate::value::Value)],
226 pub imported_consts: &'a [(&'a str, crate::value::Value)],
228 pub name: Option<&'a str>,
230 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 #[cfg(feature = "std")]
255 pub fn from_file(path: &Path) -> Result<Self, TemplateError> {
256 let mut source = std::fs::read_to_string(path)?;
257 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 pub fn from_source(source: &str) -> Result<Self, TemplateError> {
272 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 pub fn compile(
310 source: &str,
311 options: CompileOptions<'_>,
312 ) -> Result<(Self, Frontmatter), TemplateError> {
313 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 #[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 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 #[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 #[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 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 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_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 #[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 #[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 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_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 #[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 #[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 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 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 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 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 #[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 #[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 #[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 #[must_use]
695 pub fn body(&self) -> &str {
696 &self.body
697 }
698
699 #[must_use]
701 pub fn name(&self) -> Option<&str> {
702 self.name.as_deref()
703 }
704
705 #[must_use]
707 pub fn description(&self) -> Option<&str> {
708 self.description.as_deref()
709 }
710
711 pub fn set_max_include_depth(&mut self, depth: usize) {
713 self.max_include_depth = depth;
714 }
715
716 #[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 #[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 #[cfg(feature = "std")]
738 #[must_use]
739 pub fn base_dir(&self) -> Option<&Path> {
740 self.base_dir.as_deref()
741 }
742
743 #[must_use]
767 pub fn consts(&self) -> Arc<HashMap<String, Value>> {
768 self.consts.clone()
769 }
770
771 #[must_use]
774 pub fn consts_ref(&self) -> &HashMap<String, Value> {
775 &self.consts
776 }
777
778 #[must_use]
783 pub fn imported_consts(&self) -> Arc<HashMap<String, Value>> {
784 self.imported_consts.clone()
785 }
786
787 #[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 #[must_use]
805 pub fn source_hash(&self) -> u64 {
806 self.source_hash
807 }
808
809 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(¤t_names).copied().collect();
838 let extra: Vec<&str> = current_names.difference(&expected_names).copied().collect();
839
840 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
875impl 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#[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#[cfg(feature = "serde")]
913impl<'de> serde::Deserialize<'de> for Template {
914 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
915 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#[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;