1use crate::ast::*;
27use crate::error::{DiagCode, Diagnostic};
28use crate::span::Span;
29
30#[derive(Debug, Clone, PartialEq)]
34pub struct PolicyViolation {
35 pub policy: String,
36 pub span: Span,
37 pub message: String,
38 pub suggested_fix: Option<String>,
39}
40
41impl PolicyViolation {
42 pub fn new(policy: &str, span: Span, message: &str) -> Self {
44 Self {
45 policy: policy.to_string(),
46 span,
47 message: message.to_string(),
48 suggested_fix: None,
49 }
50 }
51
52 pub fn with_fix(mut self, fix: &str) -> Self {
54 self.suggested_fix = Some(fix.to_string());
55 self
56 }
57
58 pub fn to_diagnostic(&self) -> Diagnostic {
60 Diagnostic::new(DiagCode::E400, self.span, &self.message)
61 }
62}
63
64#[derive(Debug, Clone, PartialEq)]
68pub enum QueryPattern {
69 Wildcard,
71 For { no_take: bool },
73 While { unbounded: bool },
75 Call { name: Option<String> },
77 Effect { class: Option<EffectClass> },
79 Hook { path: Option<String> },
81 Function { effect: Option<EffectClass> },
83 Require { id: Option<String> },
85 Import { path: Option<String> },
87 Return,
89 Yield,
91 Transaction,
93 Literal { kind: Option<String> },
95 Binary { op: Option<BinOp> },
97 Triple,
99 Reified,
101 Match,
103 If,
105}
106
107pub fn parse_query(src: &str) -> Result<QueryPattern, String> {
120 let src = src.trim();
121 if src == "_" || src == "*" {
122 return Ok(QueryPattern::Wildcard);
123 }
124 if !src.starts_with('(') || !src.ends_with(')') {
125 return Err(format!(
126 "query must be an S-expression: (head :key val ...) or _"
127 ));
128 }
129 let inner = &src[1..src.len() - 1];
130 let parts: Vec<&str> = inner.split_whitespace().collect();
131 if parts.is_empty() {
132 return Err("empty query".into());
133 }
134 let head = parts[0];
135 let kwargs = parse_kwargs(&parts[1..]);
136 match head {
137 "for" => Ok(QueryPattern::For {
138 no_take: kwargs.has("no-take"),
139 }),
140 "while" => Ok(QueryPattern::While {
141 unbounded: kwargs.has("unbounded"),
142 }),
143 "call" => Ok(QueryPattern::Call {
144 name: kwargs.get_string("name"),
145 }),
146 "effect" => Ok(QueryPattern::Effect {
147 class: kwargs
148 .get_string("class")
149 .map(|s| parse_effect_class(&s))
150 .transpose()?,
151 }),
152 "hook" => Ok(QueryPattern::Hook {
153 path: kwargs.get_string("path"),
154 }),
155 "function" => Ok(QueryPattern::Function {
156 effect: kwargs
157 .get_string("effect")
158 .map(|s| parse_effect_class(&s))
159 .transpose()?,
160 }),
161 "require" => Ok(QueryPattern::Require {
162 id: kwargs.get_string("id"),
163 }),
164 "import" => Ok(QueryPattern::Import {
165 path: kwargs.get_string("path"),
166 }),
167 "return" => Ok(QueryPattern::Return),
168 "yield" => Ok(QueryPattern::Yield),
169 "transaction" => Ok(QueryPattern::Transaction),
170 "literal" => Ok(QueryPattern::Literal {
171 kind: kwargs.get_string("kind"),
172 }),
173 "binary" => Ok(QueryPattern::Binary {
174 op: kwargs
175 .get_string("op")
176 .map(|s| parse_binop_str(&s))
177 .transpose()?,
178 }),
179 "triple" => Ok(QueryPattern::Triple),
180 "reified" => Ok(QueryPattern::Reified),
181 "match" => Ok(QueryPattern::Match),
182 "if" => Ok(QueryPattern::If),
183 _ => Err(format!("unknown query head: {head}")),
184 }
185}
186
187struct Kwargs {
188 map: std::collections::HashMap<String, String>,
189 flags: std::collections::HashSet<String>,
190}
191
192impl Kwargs {
193 fn has(&self, key: &str) -> bool {
194 self.flags.contains(key)
195 }
196 fn get_string(&self, key: &str) -> Option<String> {
197 self.map.get(key).cloned()
198 }
199}
200
201fn parse_kwargs(parts: &[&str]) -> Kwargs {
202 let mut map = std::collections::HashMap::new();
203 let mut flags = std::collections::HashSet::new();
204 let mut i = 0;
205 while i < parts.len() {
206 let part = parts[i];
207 if let Some(key) = part.strip_prefix(':') {
208 if i + 1 < parts.len() && !parts[i + 1].starts_with(':') {
209 let val = parts[i + 1].trim_matches('"');
210 map.insert(key.to_string(), val.to_string());
211 i += 2;
212 } else {
213 flags.insert(key.to_string());
214 i += 1;
215 }
216 } else {
217 i += 1;
218 }
219 }
220 Kwargs { map, flags }
221}
222
223fn parse_effect_class(s: &str) -> Result<EffectClass, String> {
224 match s {
225 "Pure" => Ok(EffectClass::Pure),
226 "Hot" => Ok(EffectClass::Hot),
227 "Cold" => Ok(EffectClass::Cold),
228 "Async" => Ok(EffectClass::Async),
229 "External" => Ok(EffectClass::External),
230 _ => Err(format!("unknown effect class: {s}")),
231 }
232}
233
234fn parse_binop_str(s: &str) -> Result<BinOp, String> {
235 match s {
236 "Or" | "or" => Ok(BinOp::Or),
237 "And" | "and" => Ok(BinOp::And),
238 "Eq" | "eq" => Ok(BinOp::Eq),
239 "Ne" | "ne" => Ok(BinOp::Ne),
240 "Lt" | "lt" => Ok(BinOp::Lt),
241 "Le" | "le" => Ok(BinOp::Le),
242 "Gt" | "gt" => Ok(BinOp::Gt),
243 "Ge" | "ge" => Ok(BinOp::Ge),
244 "Add" | "add" | "+" => Ok(BinOp::Add),
245 "Sub" | "sub" | "-" => Ok(BinOp::Sub),
246 "Mul" | "mul" | "*" => Ok(BinOp::Mul),
247 "Div" | "div" | "/" => Ok(BinOp::Div),
248 "Rem" | "rem" | "%" => Ok(BinOp::Rem),
249 _ => Err(format!("unknown binop: {s}")),
250 }
251}
252
253#[derive(Debug, Clone)]
257pub struct Policy {
258 pub name: String,
259 pub pattern: QueryPattern,
260 pub message: String,
261 pub suggested_fix: Option<String>,
262}
263
264impl Policy {
265 pub fn new(name: &str, pattern: QueryPattern, message: &str) -> Self {
267 Self {
268 name: name.to_string(),
269 pattern,
270 message: message.to_string(),
271 suggested_fix: None,
272 }
273 }
274
275 pub fn with_fix(mut self, fix: &str) -> Self {
277 self.suggested_fix = Some(fix.to_string());
278 self
279 }
280}
281
282pub fn builtin_policies() -> Vec<Policy> {
284 vec![
285 Policy::new(
286 "mandatory-take",
287 QueryPattern::For { no_take: true },
288 "for-loop over a graph query must have a take: limit or budget(steps: N)",
289 )
290 .with_fix("add `take: 100` or `budget(steps: N)` to the for-loop"),
291 Policy::new(
292 "tick-no-external",
293 QueryPattern::Hook {
294 path: Some("tick".to_string()),
295 },
296 "on tick hooks must not perform external effects",
297 ),
298 Policy::new(
299 "unbounded-while",
300 QueryPattern::While { unbounded: true },
301 "while-loop requires a budget unless the condition is statically finite",
302 )
303 .with_fix("add `budget(steps: N)` to the while-loop"),
304 ]
305}
306
307pub fn run_policies(program: &Program, policies: &[Policy]) -> Vec<PolicyViolation> {
311 let mut violations = Vec::new();
312 for policy in policies {
313 let mut found = query_program(program, &policy.pattern);
314 for v in &mut found {
315 v.policy = policy.name.clone();
316 if v.message.is_empty() {
317 v.message = policy.message.clone();
318 }
319 if v.suggested_fix.is_none() {
320 v.suggested_fix = policy.suggested_fix.clone();
321 }
322 }
323 violations.extend(found);
324 }
325 violations
326}
327
328pub fn query_program(program: &Program, pattern: &QueryPattern) -> Vec<PolicyViolation> {
330 let mut results = Vec::new();
331 for imp in &program.imports {
333 if matches!(pattern, QueryPattern::Import { path: Some(ref p) } if p == &imp.path) {
334 results.push(PolicyViolation::new("import", imp.span, ""));
335 }
336 }
337 for cap in &program.requires {
339 if matches!(pattern, QueryPattern::Require { id: Some(ref id) } if id == &cap.id) {
340 results.push(PolicyViolation::new("require", cap.span, ""));
341 }
342 }
343 for item in &program.items {
345 query_item(item, pattern, &mut results);
346 }
347 results
348}
349
350fn query_item(item: &Item, pattern: &QueryPattern, results: &mut Vec<PolicyViolation>) {
351 match item {
352 Item::Function(f) => {
353 if matches!(pattern, QueryPattern::Function { effect: Some(ref ec) } if f.effect.as_ref() == Some(ec))
354 || matches!(pattern, QueryPattern::Function { effect: None })
355 {
356 results.push(PolicyViolation::new("function", f.span, ""));
357 }
358 query_block(&f.body, pattern, results);
359 }
360 Item::Hook(h) => {
361 let path_str = h.path.join(":");
362 if matches!(pattern, QueryPattern::Hook { path: Some(ref p) } if p == &path_str)
363 || matches!(pattern, QueryPattern::Hook { path: None })
364 {
365 results.push(PolicyViolation::new("hook", Span::new(0, 0), ""));
366 }
367 query_block(&h.body, pattern, results);
368 }
369 Item::Const(c) => {
370 query_expr(&c.value, pattern, results);
371 }
372 Item::Statement(s) => {
373 query_stmt(s, pattern, results);
374 }
375 Item::Enum(_) => {
376 }
378 Item::Field(_) => {
379 }
381 Item::Material(m) => {
382 for prop in &m.properties {
383 query_expr(&prop.value, pattern, results);
384 }
385 }
386 Item::Law(l) => {
387 query_expr(&l.condition, pattern, results);
388 query_expr(&l.consequence, pattern, results);
389 }
390 Item::Cell(c) => {
391 query_expr(&c.expr, pattern, results);
392 if let Some(w) = &c.when {
393 query_expr(w, pattern, results);
394 }
395 }
396 Item::Present(p) => {
397 for prop in &p.properties {
398 query_expr(&prop.value, pattern, results);
399 }
400 }
401 Item::Bind(b) => {
402 query_expr(&b.left, pattern, results);
403 query_expr(&b.right, pattern, results);
404 if let Some((lo, hi)) = &b.clamp {
405 query_expr(lo, pattern, results);
406 query_expr(hi, pattern, results);
407 }
408 }
409 }
410}
411
412fn query_block(block: &Block, pattern: &QueryPattern, results: &mut Vec<PolicyViolation>) {
413 for s in &block.stmts {
414 query_stmt(s, pattern, results);
415 }
416}
417
418fn query_stmt(stmt: &Stmt, pattern: &QueryPattern, results: &mut Vec<PolicyViolation>) {
419 match stmt {
420 Stmt::For {
421 span, iter, body, ..
422 } => {
423 if let QueryPattern::For { no_take: true } = pattern {
426 if !expr_has_take(iter) && !stmt_has_budget(stmt) {
427 results.push(PolicyViolation::new("for", *span, ""));
428 }
429 }
430 if matches!(pattern, QueryPattern::For { no_take: false }) {
431 results.push(PolicyViolation::new("for", *span, ""));
432 }
433 query_expr(iter, pattern, results);
434 query_block(body, pattern, results);
435 }
436 Stmt::While {
437 span, cond, body, ..
438 } => {
439 if let QueryPattern::While { unbounded: true } = pattern {
440 if !stmt_has_budget(stmt) {
441 results.push(PolicyViolation::new("while", *span, ""));
442 }
443 }
444 if matches!(pattern, QueryPattern::While { unbounded: false }) {
445 results.push(PolicyViolation::new("while", *span, ""));
446 }
447 query_expr(cond, pattern, results);
448 query_block(body, pattern, results);
449 }
450 Stmt::If {
451 cond,
452 then_block,
453 else_block,
454 ..
455 } => {
456 if matches!(pattern, QueryPattern::If) {
457 results.push(PolicyViolation::new("if", Span::new(0, 0), ""));
458 }
459 query_expr(cond, pattern, results);
460 query_block(then_block, pattern, results);
461 if let Some(els) = else_block {
462 query_stmt(els, pattern, results);
463 }
464 }
465 Stmt::Match {
466 scrutinee, arms, ..
467 } => {
468 if matches!(pattern, QueryPattern::Match) {
469 results.push(PolicyViolation::new("match", Span::new(0, 0), ""));
470 }
471 query_expr(scrutinee, pattern, results);
472 for arm in arms {
473 match &arm.body {
474 ArmBody::Block(b) => query_block(b, pattern, results),
475 ArmBody::Expr(e) => query_expr(e, pattern, results),
476 }
477 }
478 }
479 Stmt::Return { value, .. } => {
480 if matches!(pattern, QueryPattern::Return) {
481 results.push(PolicyViolation::new("return", Span::new(0, 0), ""));
482 }
483 if let Some(v) = value {
484 query_expr(v, pattern, results);
485 }
486 }
487 Stmt::Yield { value, .. } => {
488 if matches!(pattern, QueryPattern::Yield) {
489 results.push(PolicyViolation::new("yield", Span::new(0, 0), ""));
490 }
491 if let Some(v) = value {
492 query_expr(v, pattern, results);
493 }
494 }
495 Stmt::Transaction { args, body, .. } => {
496 if matches!(pattern, QueryPattern::Transaction) {
497 results.push(PolicyViolation::new("transaction", Span::new(0, 0), ""));
498 }
499 for arg in args {
500 query_expr(&arg.value, pattern, results);
501 }
502 query_block(body, pattern, results);
503 }
504 Stmt::Effect { expr, .. } => {
505 if matches!(pattern, QueryPattern::Effect { class: None }) {
506 results.push(PolicyViolation::new("effect", Span::new(0, 0), ""));
507 }
508 query_expr(expr, pattern, results);
509 }
510 Stmt::Assign { target, value, .. } => {
511 query_expr(target, pattern, results);
512 query_expr(value, pattern, results);
513 }
514 Stmt::Let { value, .. } => {
515 if let Some(v) = value {
516 query_expr(v, pattern, results);
517 }
518 }
519 Stmt::LetPat { value, .. } => {
520 query_expr(value, pattern, results);
521 }
522 Stmt::Expr { expr, .. } => query_expr(expr, pattern, results),
523 Stmt::Block(b) => query_block(b, pattern, results),
524 }
525}
526
527fn query_expr(expr: &Expr, pattern: &QueryPattern, results: &mut Vec<PolicyViolation>) {
528 match &expr.kind {
529 ExprKind::Call { callee, args } => {
530 if let QueryPattern::Call { name: Some(ref n) } = pattern {
532 if let Some(call_name) = callee.ident_name() {
533 if call_name == n {
534 results.push(PolicyViolation::new("call", expr.span, ""));
535 }
536 }
537 }
538 if matches!(pattern, QueryPattern::Call { name: None }) {
539 results.push(PolicyViolation::new("call", expr.span, ""));
540 }
541 query_expr(callee, pattern, results);
542 for arg in args {
543 match arg {
544 Arg::Pos(e) => query_expr(e, pattern, results),
545 Arg::Named(na) => query_expr(&na.value, pattern, results),
546 }
547 }
548 }
549 ExprKind::Binary { op, left, right } => {
550 if matches!(pattern, QueryPattern::Binary { op: Some(ref o) } if o == op)
551 || matches!(pattern, QueryPattern::Binary { op: None })
552 {
553 results.push(PolicyViolation::new("binary", expr.span, ""));
554 }
555 query_expr(left, pattern, results);
556 query_expr(right, pattern, results);
557 }
558 ExprKind::Unary { expr: inner, .. } => query_expr(inner, pattern, results),
559 ExprKind::Await(e) => query_expr(e, pattern, results),
560 ExprKind::Member { recv, .. } => query_expr(recv, pattern, results),
561 ExprKind::Index { recv, index } => {
562 query_expr(recv, pattern, results);
563 query_expr(index, pattern, results);
564 }
565 ExprKind::Try(e) => query_expr(e, pattern, results),
566 ExprKind::IfElse {
567 cond,
568 then_value,
569 else_value,
570 } => {
571 query_expr(cond, pattern, results);
572 query_expr(then_value, pattern, results);
573 query_expr(else_value, pattern, results);
574 }
575 ExprKind::List(es) => {
576 for e in es {
577 query_expr(e, pattern, results);
578 }
579 }
580 ExprKind::Record(args) => {
581 for arg in args {
582 query_expr(&arg.value, pattern, results);
583 }
584 }
585 ExprKind::Triple {
586 subject,
587 predicate,
588 object,
589 } => {
590 if matches!(pattern, QueryPattern::Triple) {
591 results.push(PolicyViolation::new("triple", expr.span, ""));
592 }
593 query_expr(subject, pattern, results);
594 query_expr(predicate, pattern, results);
595 query_expr(object, pattern, results);
596 }
597 ExprKind::Reified {
598 subject,
599 predicate,
600 object,
601 reifier,
602 } => {
603 if matches!(pattern, QueryPattern::Reified) {
604 results.push(PolicyViolation::new("reified", expr.span, ""));
605 }
606 query_expr(subject, pattern, results);
607 query_expr(predicate, pattern, results);
608 query_expr(object, pattern, results);
609 query_expr(reifier, pattern, results);
610 }
611 ExprKind::Literal(lit) => {
612 if matches!(pattern, QueryPattern::Literal { kind: None }) {
613 results.push(PolicyViolation::new("literal", expr.span, ""));
614 }
615 if let QueryPattern::Literal { kind: Some(ref k) } = pattern {
616 let matches = match (k.as_str(), lit) {
617 ("Null", Literal::Null) => true,
618 ("Bool", Literal::Bool(_)) => true,
619 ("Int", Literal::Int(_)) => true,
620 ("UInt", Literal::UInt(_)) => true,
621 ("Float", Literal::Float(_)) => true,
622 ("String", Literal::String(_)) => true,
623 _ => false,
624 };
625 if matches {
626 results.push(PolicyViolation::new("literal", expr.span, ""));
627 }
628 }
629 }
630 _ => {}
631 }
632}
633
634fn expr_has_take(expr: &Expr) -> bool {
638 match &expr.kind {
639 ExprKind::Call { callee, .. } => {
640 callee.ident_name() == Some("take") || callee.ident_name() == Some("limit")
641 }
642 ExprKind::Member { recv, .. } => expr_has_take(recv),
643 _ => false,
644 }
645}
646
647fn stmt_has_budget(stmt: &Stmt) -> bool {
649 match stmt {
650 Stmt::For { .. } => false, Stmt::While { .. } => false,
652 _ => false,
653 }
654}
655
656pub fn function_has_budget(f: &FunctionDecl) -> bool {
658 !f.budget.is_empty()
659}
660
661pub fn hook_has_budget(h: &HookDecl) -> bool {
663 !h.budget.is_empty()
664}
665
666pub fn check_policies(program: &Program) -> Vec<PolicyViolation> {
671 let policies = builtin_policies();
672 run_policies(program, &policies)
673}
674
675pub fn check_custom_policies(
677 program: &Program,
678 policy_specs: &[(&str, &str)],
679) -> Vec<PolicyViolation> {
680 let policies: Vec<Policy> = policy_specs
681 .iter()
682 .filter_map(|(name, query)| match parse_query(query) {
683 Ok(pattern) => Some(Policy::new(name, pattern, "")),
684 Err(_) => None,
685 })
686 .collect();
687 run_policies(program, &policies)
688}
689
690#[cfg(test)]
693mod tests {
694 use super::*;
695 use crate::parse::parse_program;
696
697 #[test]
698 fn parse_query_wildcard() {
699 assert_eq!(parse_query("_").unwrap(), QueryPattern::Wildcard);
700 assert_eq!(parse_query("*").unwrap(), QueryPattern::Wildcard);
701 }
702
703 #[test]
704 fn parse_query_for_no_take() {
705 let q = parse_query("(for :no-take)").unwrap();
706 assert_eq!(q, QueryPattern::For { no_take: true });
707 }
708
709 #[test]
710 fn parse_query_call_named() {
711 let q = parse_query(r#"(call :name "foo")"#).unwrap();
712 assert_eq!(
713 q,
714 QueryPattern::Call {
715 name: Some("foo".to_string())
716 }
717 );
718 }
719
720 #[test]
721 fn parse_query_hook_path() {
722 let q = parse_query(r#"(hook :path "tick")"#).unwrap();
723 assert_eq!(
724 q,
725 QueryPattern::Hook {
726 path: Some("tick".to_string())
727 }
728 );
729 }
730
731 #[test]
732 fn parse_query_effect_class() {
733 let q = parse_query("(effect :class External)").unwrap();
734 assert_eq!(
735 q,
736 QueryPattern::Effect {
737 class: Some(EffectClass::External)
738 }
739 );
740 }
741
742 #[test]
743 fn parse_query_binary_op() {
744 let q = parse_query("(binary :op Add)").unwrap();
745 assert_eq!(
746 q,
747 QueryPattern::Binary {
748 op: Some(BinOp::Add)
749 }
750 );
751 }
752
753 #[test]
754 fn parse_query_unknown_head() {
755 assert!(parse_query("(unknown)").is_err());
756 }
757
758 #[test]
759 fn builtin_policies_count() {
760 let policies = builtin_policies();
761 assert!(policies.len() >= 3);
762 }
763
764 #[test]
765 fn check_policies_clean_program() {
766 let src = r#"effect fn go() {
767 let x = 42;
768 return x;
769}"#;
770 let prog = parse_program(src).unwrap();
771 let violations = check_policies(&prog);
772 assert!(
773 violations.is_empty(),
774 "clean program should have no violations: {violations:?}"
775 );
776 }
777
778 #[test]
779 fn check_policies_for_loop_without_take() {
780 let src = r#"effect fn go() {
783 for item in graph.query() {
784 let x = item;
785 }
786}"#;
787 let prog = parse_program(src).unwrap();
788 let violations = check_policies(&prog);
789 assert!(
791 violations.iter().any(|v| v.policy == "mandatory-take"),
792 "expected mandatory-take violation, got: {violations:?}"
793 );
794 }
795
796 #[test]
797 fn check_policies_for_loop_with_take() {
798 let src = r#"effect fn go() {
800 for item in take(graph.query(), 100) {
801 let x = item;
802 }
803}"#;
804 let prog = parse_program(src).unwrap();
805 let violations = check_policies(&prog);
806 assert!(
807 !violations.iter().any(|v| v.policy == "mandatory-take"),
808 "for-loop with take() should not trigger mandatory-take: {violations:?}"
809 );
810 }
811
812 #[test]
813 fn query_call_pattern() {
814 let src = r#"effect fn go() {
815 foo(42);
816 bar(1, 2);
817}"#;
818 let prog = parse_program(src).unwrap();
819 let pattern = parse_query(r#"(call :name "foo")"#).unwrap();
820 let results = query_program(&prog, &pattern);
821 assert!(!results.is_empty(), "should find call to foo");
822 }
823
824 #[test]
825 fn query_hook_pattern() {
826 let src = r#"on tick(t: f32) {
827 return;
828}"#;
829 let prog = parse_program(src).unwrap();
830 let pattern = parse_query(r#"(hook :path "tick")"#).unwrap();
831 let results = query_program(&prog, &pattern);
832 assert!(!results.is_empty(), "should find tick hook");
833 }
834
835 #[test]
836 fn query_triple_pattern() {
837 let src = r#"effect fn go() {
838 <<(ex:s ex:p ex:o)>>;
839}"#;
840 let prog = parse_program(src).unwrap();
841 let pattern = parse_query("(triple)").unwrap();
842 let results = query_program(&prog, &pattern);
843 assert!(!results.is_empty(), "should find triple expression");
844 }
845
846 #[test]
847 fn query_literal_pattern() {
848 let src = r#"const x = 42;"#;
849 let prog = parse_program(src).unwrap();
850 let pattern = parse_query(r#"(literal :kind "Int")"#).unwrap();
851 let results = query_program(&prog, &pattern);
852 assert!(!results.is_empty(), "should find Int literal");
853 }
854
855 #[test]
856 fn custom_policy_forbidden_call() {
857 let src = r#"effect fn go() {
858 dangerous_fn();
859}"#;
860 let prog = parse_program(src).unwrap();
861 let violations = check_custom_policies(
862 &prog,
863 &[("forbidden-call", r#"(call :name "dangerous_fn")"#)],
864 );
865 assert!(!violations.is_empty(), "should find forbidden call");
866 assert_eq!(violations[0].policy, "forbidden-call");
867 }
868
869 #[test]
870 fn custom_policy_no_match() {
871 let src = r#"effect fn go() {
872 safe_fn();
873}"#;
874 let prog = parse_program(src).unwrap();
875 let violations = check_custom_policies(
876 &prog,
877 &[("forbidden-call", r#"(call :name "dangerous_fn")"#)],
878 );
879 assert!(violations.is_empty(), "should not find any violations");
880 }
881
882 #[test]
883 fn policy_violation_to_diagnostic() {
884 let v = PolicyViolation::new("test", Span::new(0, 10), "something wrong");
885 let d = v.to_diagnostic();
886 assert_eq!(d.code, DiagCode::E400);
887 }
888
889 #[test]
890 fn function_has_budget_check() {
891 let src = r#"effect fn go() budget(steps: 100) {
892 return;
893}"#;
894 let prog = parse_program(src).unwrap();
895 if let Item::Function(f) = &prog.items[0] {
896 assert!(function_has_budget(f));
897 }
898 }
899
900 #[test]
901 fn function_no_budget_check() {
902 let src = r#"effect fn go() {
903 return;
904}"#;
905 let prog = parse_program(src).unwrap();
906 if let Item::Function(f) = &prog.items[0] {
907 assert!(!function_has_budget(f));
908 }
909 }
910}