1use super::ast::{BinOp, Expr, Node, PathSeg};
10use super::error::TemplateParseError;
11use super::parser::parse as parse_template;
12use crate::runtime_limits::RuntimeLimits;
13
14const TEMPLATE_LINT_AST_MAX_DEPTH: usize = RuntimeLimits::DEFAULT.max_template_ast_depth;
15
16pub fn parse(src: &str) -> Result<Vec<LintConstruct>, TemplateParseError> {
21 let nodes = parse_template(src).map_err(TemplateParseError::from)?;
22 let mut out = Vec::new();
23 walk_nodes(&nodes, &mut out, 0)?;
24 out.extend(filter_uses(src)?);
25 Ok(out)
26}
27
28#[derive(Debug, Clone)]
32pub enum LintConstruct {
33 IfChain { branches: Vec<IfBranch> },
38 Section {
42 name: String,
43 line: usize,
44 col: usize,
45 },
46 Filter {
52 name: String,
53 start: usize,
54 end: usize,
55 },
56}
57
58#[derive(Debug, Clone)]
59pub struct IfBranch {
60 pub line: usize,
61 pub col: usize,
62 pub condition: ConditionShape,
63}
64
65#[derive(Debug, Clone)]
77pub enum ConditionShape {
78 ProviderIdentity(IdentityField),
81 CapabilityFlag {
86 flag: String,
87 },
88 Other,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum IdentityField {
93 Provider,
94 Model,
95 Family,
96}
97
98impl IdentityField {
99 pub fn as_str(self) -> &'static str {
100 match self {
101 IdentityField::Provider => "provider",
102 IdentityField::Model => "model",
103 IdentityField::Family => "family",
104 }
105 }
106}
107
108fn walk_nodes(
109 nodes: &[Node],
110 out: &mut Vec<LintConstruct>,
111 depth: usize,
112) -> Result<(), TemplateParseError> {
113 for node in nodes {
114 walk_node(node, out, depth)?;
115 }
116 Ok(())
117}
118
119fn walk_node(
120 node: &Node,
121 out: &mut Vec<LintConstruct>,
122 depth: usize,
123) -> Result<(), TemplateParseError> {
124 if depth > TEMPLATE_LINT_AST_MAX_DEPTH {
125 return Err(lint_depth_error(node));
126 }
127
128 match node {
129 Node::Text(_) | Node::Expr { .. } | Node::LegacyBareInterp { .. } => {}
130 Node::If {
131 branches,
132 else_branch,
133 line: _,
134 col: _,
135 } => {
136 let mut summary = Vec::with_capacity(branches.len());
137 for branch in branches {
138 summary.push(IfBranch {
139 line: branch.line,
140 col: branch.col,
141 condition: classify_condition(&branch.cond),
142 });
143 walk_nodes(&branch.body, out, depth + 1)?;
144 }
145 out.push(LintConstruct::IfChain { branches: summary });
146 if let Some(else_body) = else_branch {
147 walk_nodes(else_body, out, depth + 1)?;
148 }
149 }
150 Node::For { body, empty, .. } => {
151 walk_nodes(body, out, depth + 1)?;
152 if let Some(empty) = empty {
153 walk_nodes(empty, out, depth + 1)?;
154 }
155 }
156 Node::Include { .. } => {
157 }
161 Node::Section {
162 name,
163 body,
164 line,
165 col,
166 ..
167 } => {
168 out.push(LintConstruct::Section {
169 name: name.clone(),
170 line: *line,
171 col: *col,
172 });
173 walk_nodes(body, out, depth + 1)?;
174 }
175 }
176 Ok(())
177}
178
179fn filter_uses(src: &str) -> Result<Vec<LintConstruct>, TemplateParseError> {
180 let tokens = super::lexer::tokenize(src).map_err(TemplateParseError::from)?;
181 let mut filters = Vec::new();
182 for token in tokens {
183 let super::lexer::Token::Directive { start, end, .. } = token else {
184 continue;
185 };
186 scan_directive_filters(src, start, end, &mut filters);
187 }
188 Ok(filters)
189}
190
191fn scan_directive_filters(src: &str, start: usize, end: usize, filters: &mut Vec<LintConstruct>) {
192 let bytes = src.as_bytes();
193 let mut quote = None;
194 let mut cursor = start;
195 while cursor < end {
196 let byte = bytes[cursor];
197 if let Some(delimiter) = quote {
198 if byte == b'\\' {
199 cursor = (cursor + 2).min(end);
200 continue;
201 }
202 if byte == delimiter {
203 quote = None;
204 }
205 cursor += 1;
206 continue;
207 }
208 if matches!(byte, b'"' | b'\'') {
209 quote = Some(byte);
210 cursor += 1;
211 continue;
212 }
213 if byte != b'|' {
214 cursor += 1;
215 continue;
216 }
217 if bytes.get(cursor + 1) == Some(&b'|') {
218 cursor += 2;
219 continue;
220 }
221
222 cursor += 1;
223 while cursor < end && bytes[cursor].is_ascii_whitespace() {
224 cursor += 1;
225 }
226 let name_start = cursor;
227 while cursor < end && (bytes[cursor].is_ascii_alphanumeric() || bytes[cursor] == b'_') {
228 cursor += 1;
229 }
230 if cursor > name_start {
231 filters.push(LintConstruct::Filter {
232 name: src[name_start..cursor].to_string(),
233 start: name_start,
234 end: cursor,
235 });
236 }
237 }
238}
239
240fn lint_depth_error(node: &Node) -> TemplateParseError {
241 let (line, col) = node_location(node).unwrap_or((1, 1));
242 TemplateParseError {
243 message: format!("template lint AST depth exceeded ({TEMPLATE_LINT_AST_MAX_DEPTH} levels)"),
244 line,
245 col,
246 }
247}
248
249fn node_location(node: &Node) -> Option<(usize, usize)> {
250 match node {
251 Node::Expr { line, col, .. }
252 | Node::If { line, col, .. }
253 | Node::For { line, col, .. }
254 | Node::Include { line, col, .. }
255 | Node::Section { line, col, .. } => Some((*line, *col)),
256 Node::Text(_) | Node::LegacyBareInterp { .. } => None,
257 }
258}
259
260fn classify_condition(expr: &Expr) -> ConditionShape {
262 if let Some(identity) = match_identity_compare(expr) {
263 return ConditionShape::ProviderIdentity(identity);
264 }
265 if let Some(capability) = match_capability_path(expr) {
266 return capability;
267 }
268 ConditionShape::Other
269}
270
271fn match_identity_compare(expr: &Expr) -> Option<IdentityField> {
274 let Expr::Binary(op, lhs, rhs) = expr else {
275 return None;
276 };
277 if !matches!(op, BinOp::Eq | BinOp::Neq) {
278 return None;
279 }
280 let path = match (lhs.as_ref(), rhs.as_ref()) {
281 (Expr::Path(p), Expr::Str(_)) | (Expr::Str(_), Expr::Path(p)) => p,
282 _ => return None,
283 };
284 if !path_starts_with_llm(path) {
285 return None;
286 }
287 match path.get(1) {
288 Some(PathSeg::Field(name) | PathSeg::Key(name)) if name == "provider" => {
289 Some(IdentityField::Provider)
290 }
291 Some(PathSeg::Field(name) | PathSeg::Key(name)) if name == "model" => {
292 Some(IdentityField::Model)
293 }
294 Some(PathSeg::Field(name) | PathSeg::Key(name)) if name == "family" => {
295 Some(IdentityField::Family)
296 }
297 _ => None,
298 }
299}
300
301fn match_capability_path(expr: &Expr) -> Option<ConditionShape> {
304 fn find_capability_path(expr: &Expr) -> Option<String> {
305 let mut stack = vec![expr];
306 while let Some(expr) = stack.pop() {
307 match expr {
308 Expr::Path(path) => {
309 if let Some(flag) = capability_flag_from_path(path) {
310 return Some(flag);
311 }
312 }
313 Expr::Unary(_, inner) => stack.push(inner),
314 Expr::Binary(_, lhs, rhs) => {
315 stack.push(rhs);
316 stack.push(lhs);
317 }
318 Expr::Filter(inner, _, _) => stack.push(inner),
319 _ => {}
320 }
321 }
322 None
323 }
324 let flag = find_capability_path(expr)?;
325 Some(ConditionShape::CapabilityFlag { flag })
326}
327
328fn capability_flag_from_path(path: &[PathSeg]) -> Option<String> {
329 if !path_starts_with_llm(path) {
330 return None;
331 }
332 let Some(PathSeg::Field(name) | PathSeg::Key(name)) = path.get(1) else {
333 return None;
334 };
335 if name != "capabilities" {
336 return None;
337 }
338 let Some(PathSeg::Field(flag) | PathSeg::Key(flag)) = path.get(2) else {
339 return None;
340 };
341 Some(flag.clone())
342}
343
344fn path_starts_with_llm(path: &[PathSeg]) -> bool {
345 matches!(
346 path.first(),
347 Some(PathSeg::Field(name)) if name == "llm",
348 )
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354
355 fn parse_ok(src: &str) -> Vec<LintConstruct> {
356 parse(src).expect("template should parse")
357 }
358
359 fn filters(src: &str) -> Vec<(String, usize, usize)> {
360 parse_ok(src)
361 .into_iter()
362 .filter_map(|construct| match construct {
363 LintConstruct::Filter { name, start, end } => Some((name, start, end)),
364 _ => None,
365 })
366 .collect()
367 }
368
369 #[test]
370 fn filter_uses_carry_exact_name_ranges() {
371 let source = "{{ name | uppr | default: \"| not_a_filter\" }}";
372 let found = filters(source);
373 assert_eq!(
374 found
375 .iter()
376 .map(|(name, _, _)| name.as_str())
377 .collect::<Vec<_>>(),
378 ["uppr", "default"]
379 );
380 for (name, start, end) in found {
381 assert_eq!(&source[start..end], name);
382 }
383 }
384
385 #[test]
386 fn logical_or_comments_and_raw_text_are_not_filters() {
387 let source = concat!(
388 "{{ if a || b }}x{{ end }}\n",
389 "{{# ignored | nope #}}\n",
390 "{{ raw }}{{ value | nope }}{{ endraw }}\n",
391 );
392 assert!(filters(source).is_empty());
393 }
394
395 fn first_if(constructs: &[LintConstruct]) -> &[IfBranch] {
396 match constructs
397 .iter()
398 .find(|c| matches!(c, LintConstruct::IfChain { .. }))
399 .expect("if chain present")
400 {
401 LintConstruct::IfChain { branches } => branches.as_slice(),
402 _ => unreachable!(),
403 }
404 }
405
406 #[test]
407 fn provider_identity_eq_detected() {
408 let constructs = parse_ok("{{ if llm.provider == \"anthropic\" }}x{{ else }}y{{ end }}");
409 let branches = first_if(&constructs);
410 assert_eq!(branches.len(), 1);
411 assert!(matches!(
412 branches[0].condition,
413 ConditionShape::ProviderIdentity(IdentityField::Provider)
414 ));
415 }
416
417 #[test]
418 fn model_identity_neq_detected() {
419 let constructs = parse_ok("{{ if llm.model != \"gpt-5\" }}x{{ end }}");
420 let branches = first_if(&constructs);
421 assert!(matches!(
422 branches[0].condition,
423 ConditionShape::ProviderIdentity(IdentityField::Model)
424 ));
425 }
426
427 #[test]
428 fn capability_flag_detected_in_negation_and_filter() {
429 let constructs = parse_ok(
430 "{{ if !llm.capabilities.native_tools }}x{{ end }}\
431 {{ if llm.capabilities.prefers_xml_scaffolding | default: false }}y{{ end }}",
432 );
433 let if_chains: Vec<_> = constructs
434 .iter()
435 .filter_map(|c| match c {
436 LintConstruct::IfChain { branches } => Some(branches.clone()),
437 _ => None,
438 })
439 .collect();
440 assert_eq!(if_chains.len(), 2);
441 assert!(matches!(
442 if_chains[0][0].condition,
443 ConditionShape::CapabilityFlag { ref flag, .. } if flag == "native_tools"
444 ));
445 assert!(matches!(
446 if_chains[1][0].condition,
447 ConditionShape::CapabilityFlag { ref flag, .. } if flag == "prefers_xml_scaffolding"
448 ));
449 }
450
451 #[test]
452 fn capability_flag_detection_handles_wide_binary_expression() {
453 let mut terms = (0..300).map(|idx| format!("flag{idx}")).collect::<Vec<_>>();
454 terms.push("llm.capabilities.native_tools".to_string());
455 let src = format!("{{{{ if {} }}}}x{{{{ end }}}}", terms.join(" or "));
456
457 let constructs = parse_ok(&src);
458 let branches = first_if(&constructs);
459
460 assert!(matches!(
461 branches[0].condition,
462 ConditionShape::CapabilityFlag { ref flag, .. } if flag == "native_tools"
463 ));
464 }
465
466 #[test]
467 fn parse_reports_template_control_depth_limit() {
468 let depth = RuntimeLimits::DEFAULT.max_template_ast_depth + 1;
469 let mut src = String::new();
470 for _ in 0..depth {
471 src.push_str("{{ if true }}");
472 }
473 src.push('x');
474 for _ in 0..depth {
475 src.push_str("{{ end }}");
476 }
477
478 let err = parse(&src).expect_err("depth limit");
479
480 assert!(err.message.contains("template nesting depth exceeded"));
481 assert!(err.message.contains(&format!(
482 "({} levels)",
483 RuntimeLimits::DEFAULT.max_template_ast_depth
484 )));
485 }
486
487 #[test]
488 fn parse_reports_template_expression_depth_limit() {
489 let depth = RuntimeLimits::DEFAULT.max_template_ast_depth + 1;
490 let condition = format!("{}llm.capabilities.native_tools", "!".repeat(depth));
491 let src = format!("{{{{ if {condition} }}}}x{{{{ end }}}}");
492
493 let err = parse(&src).expect_err("depth limit");
494
495 assert!(err.message.contains("template expression depth exceeded"));
496 assert!(err.message.contains(&format!(
497 "({} levels)",
498 RuntimeLimits::DEFAULT.max_template_ast_depth
499 )));
500 }
501
502 #[test]
503 fn elif_chain_lifts_per_branch_condition() {
504 let constructs = parse_ok(
505 "{{ if llm.provider == \"openai\" }}a\
506 {{ elif llm.capabilities.native_tools }}b\
507 {{ else }}c{{ end }}",
508 );
509 let branches = first_if(&constructs);
510 assert_eq!(branches.len(), 2);
511 assert!(matches!(
512 branches[0].condition,
513 ConditionShape::ProviderIdentity(IdentityField::Provider)
514 ));
515 assert!(matches!(
516 branches[1].condition,
517 ConditionShape::CapabilityFlag { ref flag, .. } if flag == "native_tools"
518 ));
519 }
520
521 #[test]
522 fn unrelated_condition_falls_through_to_other() {
523 let constructs = parse_ok("{{ if score > 0.5 }}a{{ end }}");
524 let branches = first_if(&constructs);
525 assert!(matches!(branches[0].condition, ConditionShape::Other));
526 }
527
528 #[test]
529 fn sections_listed_in_source_order() {
530 let constructs = parse_ok(
531 "{{ section \"task\" }}t{{ endsection }}\
532 {{ section \"output_format\" }}o{{ endsection }}",
533 );
534 let names: Vec<_> = constructs
535 .iter()
536 .filter_map(|c| match c {
537 LintConstruct::Section { name, .. } => Some(name.clone()),
538 _ => None,
539 })
540 .collect();
541 assert_eq!(names, vec!["task", "output_format"]);
542 }
543}