md-tmpl 0.5.0

Lightweight template engine for .tmpl.md prompt files with typed frontmatter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! YAML-style frontmatter parsing for `.tmpl.md` files.
//!
//! Extracts template metadata (name, description, typed variable declarations)
//! from the `---`-delimited block at the start of a template source string.
//!
//! ## Frontmatter v2 format
//!
//! Uses `=` for name-type pairs, `<>` for type parameters, `:=` for defaults:
//!
//! ```text
//! ---
//! name: my_template
//! params:
//!   - name = str
//!   - count = int := 42
//!   - tasks = list(title = str, priority = int)
//! ---
//! ```

mod imports;
mod params;
mod type_aliases;
mod validation;

use alloc::{
    string::{String, ToString},
    vec::Vec,
};
#[cfg(feature = "std")]
use std::path::PathBuf;

pub use imports::*;
pub use params::parse_type_annotation;
pub(crate) use params::*;
pub(crate) use type_aliases::*;
pub(crate) use validation::*;

use crate::{
    compat::HashMap,
    consts::{
        FM_ALLOW_UNUSED_PREFIX, FM_CONSTS_PREFIX, FM_DELIMITER, FM_DELIMITER_NEWLINE,
        FM_DESC_PREFIX, FM_IMPORTS_PREFIX, FM_NAME_PREFIX, FM_PARAMS_PREFIX, FM_TYPES_PREFIX,
    },
    error::TemplateError,
    frontmatter::params::parse_declarations,
    types::{VarDecl, VarType},
};

/// A template import declaration: `[stem](path.tmpl.md)`.
#[derive(Debug, Clone)]
pub struct Import {
    /// Short alias used as namespace prefix, e.g. `other`.
    pub stem: String,
    /// Relative path to the imported template file.
    #[cfg(feature = "std")]
    pub path: PathBuf,
    /// Relative path as a string (always available).
    #[cfg(not(feature = "std"))]
    pub path: alloc::string::String,
}

/// Resolved namespace from an imported template.
#[derive(Debug, Clone, Default)]
pub struct ImportedNamespace {
    /// Type aliases exported by the imported template.
    pub type_aliases: HashMap<String, VarType>,
    /// Parameter types (for cross-template type references).
    pub param_types: HashMap<String, VarType>,
    /// Constants exported by the imported template.
    pub consts: HashMap<String, crate::value::Value>,
}

/// Parsed YAML frontmatter from a `.tmpl.md` file.
#[derive(Debug, Clone, Default)]
pub struct Frontmatter {
    /// Template name (matches SKILL.md `name:` convention).
    pub name: Option<String>,
    /// Description of the template's purpose.
    pub description: Option<String>,
    /// List of expected variable declarations (name + type + optional default).
    pub declarations: Vec<VarDecl>,
    /// Convenience: parameter names only (derived from `declarations`).
    pub params: Vec<String>,
    /// Whether the params: block was present in frontmatter.
    pub has_params: bool,
    /// Allow declared parameters that are never referenced in the body.
    ///
    /// Set via `allow_unused: true` in frontmatter. Useful for
    /// dynamically-loaded templates where params may be conditionally used.
    pub allow_unused: bool,
    /// Type aliases defined via `types:` in frontmatter.
    ///
    /// Maps alias names (e.g. `Priority`) to their resolved [`VarType`].
    pub type_aliases: HashMap<String, VarType>,
    /// Import declarations defined via `imports:` in frontmatter.
    pub imports: Vec<Import>,
    /// Constants defined via `consts:` in frontmatter.
    pub consts: Vec<VarDecl>,
    /// Resolved constants from imports, keyed by `stem.NAME`.
    pub imported_consts: HashMap<String, crate::value::Value>,
    /// Keys in `imported_consts` that are enum type namespace dicts
    /// (injected from imported enum type aliases). Used by the bare-enum-access
    /// check to distinguish enum namespaces from struct constants.
    pub imported_enum_type_keys: Vec<String>,
}

/// Strip YAML frontmatter delimited by `---` and return only the body text.
///
/// # Errors
///
/// Returns [`TemplateError::Syntax`] if the frontmatter block is missing or invalid.
pub fn strip_frontmatter(source: &str) -> Result<&str, TemplateError> {
    parse_frontmatter(source).map(|(_, body)| body)
}

/// Parse YAML frontmatter delimited by `---` lines.
///
/// Returns the parsed [`Frontmatter`] and a string slice pointing to the
/// template body after the closing `---`.
///
/// # Errors
///
/// Returns [`TemplateError::Syntax`] if the frontmatter block is
/// missing, unclosed, or contains invalid declarations.
pub fn parse_frontmatter(source: &str) -> Result<(Frontmatter, &str), TemplateError> {
    parse_frontmatter_impl(
        source,
        #[cfg(feature = "std")]
        None,
        None,
        false,
    )
}

/// Parse YAML frontmatter with cross-template import resolution.
///
/// Like [`parse_frontmatter`], but additionally resolves `imports:` entries
/// by reading referenced template files from disk relative to `base_dir`.
/// This allows params to reference imported types (e.g. `types.Severity`).
///
/// # Errors
///
/// Returns [`TemplateError::Syntax`] if the frontmatter block is invalid,
/// an imported file cannot be read, or imported types cannot be resolved.
#[cfg(feature = "std")]
pub fn parse_frontmatter_with_base_dir<'a>(
    source: &'a str,
    base_dir: &std::path::Path,
) -> Result<(Frontmatter, &'a str), TemplateError> {
    parse_frontmatter_impl(source, Some(base_dir), None, false)
}

/// Parse YAML frontmatter with access to a parent template's type aliases.
///
/// Used for inline template definitions (`{% tmpl %}`) that can reference
/// type aliases from the enclosing template.
pub fn parse_frontmatter_with_parent_scope<'a>(
    source: &'a str,
    parent_type_aliases: &HashMap<String, VarType>,
) -> Result<(Frontmatter, &'a str), TemplateError> {
    parse_frontmatter_impl(
        source,
        #[cfg(feature = "std")]
        None,
        Some(parent_type_aliases),
        true,
    )
}

fn extract_yaml_logical_lines(
    source: &str,
    allow_missing_fm: bool,
) -> Result<(Vec<String>, &str), TemplateError> {
    let trimmed = source.trim_start();
    if !trimmed.starts_with(FM_DELIMITER) {
        if allow_missing_fm {
            return Ok((Vec::new(), source));
        }
        return Err(TemplateError::syntax(
            crate::consts::ERR_MISSING_FM.to_string(),
        ));
    }

    let after_first = trimmed[FM_DELIMITER.len()..].trim_start_matches(['\r', '\n']);
    let Some(end) = after_first.find(FM_DELIMITER_NEWLINE) else {
        return Err(TemplateError::syntax(
            crate::consts::ERR_UNCLOSED_FM.to_string(),
        ));
    };

    let yaml_block = &after_first[..end];
    let after_close = end + FM_DELIMITER_NEWLINE.len();
    let body_start = if after_first[after_close..].starts_with('\n') {
        after_close + 1
    } else if after_first[after_close..].starts_with("\r\n") {
        after_close + 2
    } else {
        after_close
    };
    let body = &after_first[body_start..];

    let mut in_block_list = false;
    let mut had_blank_line = true;
    for line in yaml_block.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            had_blank_line = true;
            continue;
        }
        let starts_with_section = line.starts_with(FM_NAME_PREFIX)
            || line.starts_with(FM_DESC_PREFIX)
            || line.starts_with(FM_TYPES_PREFIX)
            || line.starts_with(FM_IMPORTS_PREFIX)
            || line.starts_with(FM_PARAMS_PREFIX)
            || line.starts_with(FM_CONSTS_PREFIX)
            || line.starts_with(FM_ALLOW_UNUSED_PREFIX);

        if starts_with_section {
            if in_block_list && !had_blank_line {
                return Err(TemplateError::syntax(format!(
                    "A blank line is required after a block list before '{trimmed}' so raw markdown renders correctly"
                )));
            }
            in_block_list = false;
        } else if trimmed.starts_with('-') {
            in_block_list = true;
        }
        had_blank_line = false;
    }

    Ok((join_continuation_lines(yaml_block), body))
}

type FmResolutionResult = Result<
    (
        HashMap<String, VarType>,
        HashMap<String, ImportedNamespace>,
        HashMap<String, crate::value::Value>,
    ),
    TemplateError,
>;

fn resolve_fm_consts_and_imports(
    fm: &mut Frontmatter,
    consts_raw: Option<&str>,
    parent_type_aliases: Option<&HashMap<String, VarType>>,
    #[cfg(feature = "std")] base_dir: Option<&std::path::Path>,
) -> FmResolutionResult {
    let mut merged_aliases = if let Some(parent_aliases) = parent_type_aliases {
        parent_aliases.clone()
    } else {
        HashMap::new()
    };
    for (k, v) in &fm.type_aliases {
        merged_aliases.insert(k.clone(), v.clone());
    }

    let mut prelim_consts = HashMap::new();
    let empty_imports = HashMap::new();
    let empty_consts = HashMap::new();
    if let Some(raw) = consts_raw {
        if let Ok(decls) =
            parse_declarations(raw, &merged_aliases, &empty_imports, true, &empty_consts)
        {
            prelim_consts = build_available_consts(&decls, &HashMap::new());
        }
    }

    #[cfg(feature = "std")]
    let resolved_imports = if let Some(dir) = base_dir {
        if fm.imports.is_empty() {
            HashMap::new()
        } else {
            let mut visited = std::collections::HashSet::new();
            resolve_imports_with_consts(&mut fm.imports, dir, &mut visited, &prelim_consts)?
        }
    } else {
        if !fm.imports.is_empty() {
            interpolate_imports(&mut fm.imports, &prelim_consts)?;
        }
        HashMap::new()
    };

    #[cfg(not(feature = "std"))]
    let resolved_imports = {
        if !fm.imports.is_empty() {
            interpolate_imports(&mut fm.imports, &prelim_consts)?;
        }
        HashMap::new()
    };

    #[cfg(feature = "std")]
    inject_imported_consts(fm, &resolved_imports);

    if let Some(raw) = consts_raw {
        fm.consts =
            parse_declarations(raw, &merged_aliases, &resolved_imports, true, &empty_consts)?;
    }

    let available_consts = build_available_consts(&fm.consts, &fm.imported_consts);
    Ok((merged_aliases, resolved_imports, available_consts))
}

fn parse_frontmatter_impl<'a>(
    source: &'a str,
    #[cfg(feature = "std")] base_dir: Option<&std::path::Path>,
    parent_type_aliases: Option<&HashMap<String, VarType>>,
    allow_missing_fm: bool,
) -> Result<(Frontmatter, &'a str), TemplateError> {
    let (logical_lines, body) = extract_yaml_logical_lines(source, allow_missing_fm)?;
    if logical_lines.is_empty()
        && allow_missing_fm
        && !source.trim_start().starts_with(FM_DELIMITER)
    {
        return Ok((Frontmatter::default(), body));
    }

    let mut fm = Frontmatter::default();
    let mut params_raw: Option<String> = None;
    let mut consts_raw: Option<String> = None;

    for line in &logical_lines {
        let line = line.trim();
        if let Some(rest) = line.strip_prefix(FM_NAME_PREFIX) {
            fm.name = Some(rest.trim().to_string());
        } else if let Some(rest) = line.strip_prefix(FM_DESC_PREFIX) {
            fm.description = Some(rest.trim().to_string());
        } else if let Some(rest) = line.strip_prefix(FM_TYPES_PREFIX) {
            fm.type_aliases = parse_types_value(rest)?;
        } else if let Some(rest) = line.strip_prefix(FM_IMPORTS_PREFIX) {
            fm.imports = parse_imports_value(rest)?;
        } else if let Some(rest) = line.strip_prefix(FM_PARAMS_PREFIX) {
            params_raw = Some(rest.to_string());
        } else if let Some(rest) = line.strip_prefix(FM_CONSTS_PREFIX) {
            consts_raw = Some(rest.to_string());
        } else if let Some(rest) = line.strip_prefix(FM_ALLOW_UNUSED_PREFIX) {
            fm.allow_unused = rest.trim() == crate::consts::LIT_TRUE;
        }
    }

    let (merged_aliases, resolved_imports, available_consts) = resolve_fm_consts_and_imports(
        &mut fm,
        consts_raw.as_deref(),
        parent_type_aliases,
        #[cfg(feature = "std")]
        base_dir,
    )?;

    if let Some(raw) = params_raw {
        let decls = parse_declarations(
            &raw,
            &merged_aliases,
            &resolved_imports,
            false,
            &available_consts,
        )?;
        fm.params = decls.iter().map(|d| d.name.clone()).collect();
        fm.declarations = decls;
        fm.has_params = true;
    }

    validate_collision_rules(&fm)?;
    add_implicit_param_types(&mut fm);

    Ok((fm, body))
}

/// Inject imported constants and enum type namespace dicts into `fm`.
///
/// For each import namespace, copies over user-defined constants and
/// synthesizes enum type namespace dicts so that `{{ lib.EnumType.Variant }}`
/// expressions work.
#[cfg(feature = "std")]
fn inject_imported_consts(
    fm: &mut Frontmatter,
    resolved_imports: &HashMap<String, ImportedNamespace>,
) {
    for (stem, ns) in resolved_imports {
        for (name, val) in &ns.consts {
            fm.imported_consts
                .insert(format!("{stem}.{name}"), val.clone());
        }
        // Inject enum type aliases from the imported namespace as constants,
        // enabling `{{ lib.EnumType.Variant }}` expressions.
        for (type_name, var_type) in &ns.type_aliases {
            let VarType::Enum(variants) = var_type else {
                continue;
            };
            let key = format!("{stem}.{type_name}");
            // Don't overwrite a user-defined constant with the same name.
            if fm.imported_consts.contains_key(&key) {
                continue;
            }
            let mut variant_map = HashMap::new();
            let mut variant_names = Vec::with_capacity(variants.len());
            for variant in variants {
                variant_names.push(crate::value::Value::Str(variant.name.clone()));
                if variant.fields.is_empty() {
                    variant_map.insert(
                        variant.name.clone(),
                        crate::value::Value::Str(variant.name.clone()),
                    );
                } else {
                    let mut partial = HashMap::new();
                    partial.insert(
                        crate::consts::ENUM_TAG_KEY.into(),
                        crate::value::Value::Str(variant.name.clone()),
                    );
                    variant_map.insert(
                        variant.name.clone(),
                        crate::value::Value::Struct(alloc::sync::Arc::new(partial)),
                    );
                }
            }
            variant_map.insert(
                crate::consts::ENUM_VARIANTS_KEY.into(),
                crate::value::Value::List(alloc::sync::Arc::new(variant_names)),
            );
            fm.imported_consts.insert(
                key.clone(),
                crate::value::Value::Struct(alloc::sync::Arc::new(variant_map)),
            );
            fm.imported_enum_type_keys.push(key);
        }
    }
}

/// Build a lookup map of available constants for use as param default values.
///
/// Merges local constants (from `consts:` declarations) with imported constants
/// (from `imports:`) into a single flat map. Local consts are keyed by their
/// bare name (e.g. `MAX`), imported consts are already keyed by `stem.NAME`
/// (e.g. `lib.LIMIT`).
fn build_available_consts(
    consts: &[crate::types::VarDecl],
    imported_consts: &HashMap<String, crate::value::Value>,
) -> HashMap<String, crate::value::Value> {
    let mut available = HashMap::with_capacity(consts.len() + imported_consts.len());
    // Add local consts.
    for d in consts {
        if let Some(ref v) = d.default_value {
            available.insert(d.name.clone(), v.clone());
        }
    }
    // Add imported consts (stem.NAME keys).
    for (k, v) in imported_consts {
        available.insert(k.clone(), v.clone());
    }
    available
}

#[cfg(test)]
mod tests;