1use crate::authored_template::render_authored_json;
2use crate::budget::{BudgetKind, BudgetTracker};
3use crate::conditions::{ConditionModel, Satisfiability};
4use crate::consts::*;
5use crate::defect::{DefectPhase, ParseDefect};
6use crate::graph::ReferenceGraph;
7use crate::ir::*;
8use crate::is_custom_resource_type;
9use crate::json_value::JsonValue;
10use crate::regions::*;
11use crate::resolved_value::*;
12use crate::resolver::*;
13use crate::sam;
14use crate::span::SpanProvider;
15use log::{debug, info, warn};
16use serde::Serialize;
17use std::cmp::Reverse;
18use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet};
19use std::sync::Arc;
20use std::sync::Mutex;
21use std::sync::OnceLock;
22use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
23
24#[derive(Debug, Clone, Serialize, Default)]
26#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
27#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
28#[serde(rename_all = "camelCase")]
29pub struct PathValuePair {
30 pub path: String,
32 pub value: String,
33}
34
35#[derive(Debug, Clone, Serialize, Default)]
37#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
38#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
39#[serde(rename_all = "camelCase")]
40pub struct ConditionalNullEntry {
41 pub path: String,
43 pub condition: String,
45 pub null_in_true_branch: bool,
47}
48
49#[derive(Debug, Clone, Serialize, Default)]
51#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
52#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
53#[serde(rename_all = "camelCase")]
54pub struct ResourceDiagnostics {
55 pub find_in_map_refs: Vec<String>,
57 pub simple_subs: Vec<PathValuePair>,
59 pub redundant_subs: Vec<String>,
61 pub empty_joins: Vec<String>,
63 pub condition_refs: Vec<String>,
65 pub hardcoded_partition_arns: Vec<String>,
67 pub conditionally_null_props: Vec<ConditionalNullEntry>,
68 pub foreach_expansions: Vec<ForEachExpansion>,
69 pub unsubstituted_variables: Vec<PathValuePair>,
71 pub unused_sub_keys: Vec<PathValuePair>,
73 pub raw_pseudo_params: Vec<PathValuePair>,
75 pub secretsmanager_ref_paths: Vec<String>,
77 pub invalid_refs: Vec<PathValuePair>,
79}
80
81#[derive(Debug, Clone, Serialize)]
83#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
84#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
85#[serde(rename_all = "camelCase")]
86pub struct ResolvedResource {
87 pub logical_id: String,
88 pub resource_type: String,
89 #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
90 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
91 pub condition: Option<String>,
92 pub depends_on: Vec<String>,
93 #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
94 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
95 pub deletion_policy: Option<ResolvedValue>,
96 #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
97 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
98 pub update_replace_policy: Option<ResolvedValue>,
99 #[cfg_attr(feature = "wasm-bindings", tsify(optional, type = "JsonValue"))]
100 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
101 pub update_policy: Option<JsonValue>,
102 #[cfg_attr(feature = "wasm-bindings", tsify(optional, type = "JsonValue"))]
103 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
104 pub creation_policy: Option<JsonValue>,
105 #[cfg_attr(feature = "wasm-bindings", tsify(optional, type = "JsonValue"))]
106 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
107 pub metadata: Option<JsonValue>,
108 #[cfg_attr(feature = "wasm-bindings", tsify(type = "Record<string, ResolvedValue>"))]
109 pub properties: HashMap<String, ResolvedValue>,
110 pub properties_dynamic: bool,
114 pub diagnostics: ResourceDiagnostics,
115}
116
117#[derive(Debug, Clone, Default, PartialEq, Eq)]
120pub struct LifecycleAttributeStatus {
121 pub may_be_present: bool,
123 pub invalid_value: Option<String>,
125}
126
127struct PrimaryIdentifierScenario {
128 identity_tuple: Vec<String>,
129 display_tuple: Vec<String>,
130 assumptions: Vec<(String, bool)>,
131}
132
133type PrimaryIdentifierComparisonOrder = (usize, usize, usize, usize);
140
141struct IdentityGroupPairCursor {
147 resources: Vec<(usize, Vec<usize>)>,
150 left_resource: usize,
151 right_resource: usize,
152 left_scenario: usize,
153 right_scenario: usize,
154}
155
156impl IdentityGroupPairCursor {
157 fn new(candidates: &[(usize, usize)]) -> Option<Self> {
162 let mut resources: Vec<(usize, Vec<usize>)> = Vec::new();
163 for &(resource_index, scenario_index) in candidates {
164 match resources.last_mut() {
165 Some((last_resource_index, scenario_indices)) if *last_resource_index == resource_index => {
166 scenario_indices.push(scenario_index);
167 }
168 _ => resources.push((resource_index, vec![scenario_index])),
169 }
170 }
171 if resources.len() < 2 {
172 return None;
173 }
174 Some(Self { resources, left_resource: 0, right_resource: 1, left_scenario: 0, right_scenario: 0 })
175 }
176}
177
178impl Iterator for IdentityGroupPairCursor {
179 type Item = PrimaryIdentifierComparisonOrder;
180
181 fn next(&mut self) -> Option<Self::Item> {
182 while self.left_resource + 1 < self.resources.len() {
183 if self.right_resource >= self.resources.len() {
184 self.left_resource += 1;
185 self.right_resource = self.left_resource + 1;
186 self.left_scenario = 0;
187 self.right_scenario = 0;
188 continue;
189 }
190 if self.left_scenario >= self.resources[self.left_resource].1.len() {
191 self.right_resource += 1;
192 self.left_scenario = 0;
193 self.right_scenario = 0;
194 continue;
195 }
196 if self.right_scenario >= self.resources[self.right_resource].1.len() {
197 self.left_scenario += 1;
198 self.right_scenario = 0;
199 continue;
200 }
201 let comparison = (
202 self.resources[self.left_resource].0,
203 self.resources[self.right_resource].0,
204 self.resources[self.left_resource].1[self.left_scenario],
205 self.resources[self.right_resource].1[self.right_scenario],
206 );
207 self.right_scenario += 1;
208 return Some(comparison);
209 }
210 None
211 }
212}
213
214#[derive(Debug, Clone, Serialize)]
216#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
217#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
218#[serde(rename_all = "camelCase")]
219pub struct ForEachExpansion {
220 pub property_path: String,
222 pub identifier: String,
224 pub collection_source: String,
226}
227
228#[derive(Debug, Clone, Serialize)]
230#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
231#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
232#[serde(rename_all = "camelCase")]
233pub struct ResolvedOutput {
234 pub value: ResolvedValue,
235 #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
236 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
237 pub description: Option<String>,
238 #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
239 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
240 pub condition: Option<String>,
241 #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
242 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
243 pub export_name: Option<ResolvedValue>,
244}
245
246#[derive(Debug, Clone, Serialize)]
247#[serde(rename_all = "camelCase")]
248pub struct TemplateRule {
249 pub name: String,
250 pub condition: Option<serde_json::Value>,
251 #[serde(skip)]
252 pub condition_node: crate::ir::NodeRef,
253 pub assertions: Vec<RuleAssertion>,
254}
255
256#[derive(Debug, Clone, Serialize)]
257#[serde(rename_all = "camelCase")]
258pub struct RuleAssertion {
259 pub assert: serde_json::Value,
260 #[serde(skip)]
261 pub assert_node: crate::ir::NodeRef,
262 pub description: Option<String>,
263}
264
265pub struct SemanticModel {
266 pub arena: Arena,
267 root: NodeRef,
269 authored_template: OnceLock<serde_json::Value>,
272 pub span_index: SourceSpanIndex,
273 pub format_version: Option<String>,
274 pub description: Option<String>,
275 pub transforms: Vec<String>,
276 pub raw_top_level_keys: Vec<String>,
277 pub template_metadata: Option<serde_json::Value>,
278 pub rules: Option<serde_json::Value>,
279 pub parsed_rules: Vec<TemplateRule>,
280 pub parameters: HashMap<String, ParameterInfo>,
281 pub mappings: MappingData,
282 pub conditions: ConditionModel,
283 pub resources: HashMap<String, ResolvedResource>,
284 pub outputs: HashMap<String, ResolvedOutput>,
285 pub graph: ReferenceGraph,
286 pub resources_by_type: HashMap<String, Vec<String>>,
287 pub diagnostics: Vec<ParseDefect>,
288 pub output_empty_joins: Vec<String>,
289 pub sam_globals: HashMap<String, HashMap<String, serde_json::Value>>,
290 pub sam_implicit_resources: HashSet<String>,
291 pub globals_param_refs: Vec<String>,
292 pub is_cdk: bool,
293 pub fn_if_conditions: Vec<String>,
294 pub find_in_map_names: HashSet<String>,
297 pub params_referenced_in_definitions: HashSet<String>,
300 pub has_dynamic_findinmap_name: bool,
304 pub resolution_sources: HashMap<(String, String), String>,
305 intrinsic_source_paths: HashMap<String, HashSet<String>>,
311 value_nodes: HashMap<(String, String), NodeRef>,
314 lifecycle_attribute_nodes: HashMap<(String, String), NodeRef>,
317 lifecycle_attribute_status_cache: Mutex<HashMap<(String, String), LifecycleAttributeStatus>>,
318 invalid_resource_conditions: HashSet<String>,
321 invalid_inline_conditions: HashSet<String>,
325 resolve_memo: Mutex<HashMap<(String, String), Option<ResolvedValue>>>,
326 raw_scenario_memo: Mutex<HashMap<(String, String), Vec<(ResolvedValue, HashMap<String, bool>)>>>,
327 properties_scenario_cache: Mutex<HashMap<String, Arc<Vec<(ResolvedValue, HashMap<String, bool>)>>>>,
328 scenario_memo: Mutex<HashMap<(String, String), Arc<Vec<(serde_json::Value, HashMap<String, bool>)>>>>,
329 lifecycle_policy_scenario_cache: Mutex<HashMap<(String, String), Vec<(serde_json::Value, HashMap<String, bool>)>>>,
330 scenario_combinations_used: AtomicU64,
335 budget_tracker: Arc<BudgetTracker>,
338 scenario_expansion_lock: Mutex<()>,
343 scenario_expansion_curtailed: AtomicBool,
347}
348
349#[derive(Debug, Clone, Default, Serialize, serde::Deserialize)]
352#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
353#[cfg_attr(feature = "wasm-bindings", tsify(from_wasm_abi))]
354#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
355#[serde(rename_all = "camelCase")]
356pub struct PseudoParameterOverrides {
357 #[serde(default, skip_serializing_if = "Option::is_none")]
358 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
359 pub account_id: Option<String>,
360 #[serde(default, skip_serializing_if = "Option::is_none")]
361 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
362 pub notification_arns: Option<String>,
363 #[serde(default, skip_serializing_if = "Option::is_none")]
364 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
365 pub partition: Option<String>,
366 #[serde(default, skip_serializing_if = "Option::is_none")]
367 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
368 pub region: Option<String>,
369 #[serde(default, skip_serializing_if = "Option::is_none")]
370 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
371 pub stack_id: Option<String>,
372 #[serde(default, skip_serializing_if = "Option::is_none")]
373 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
374 pub stack_name: Option<String>,
375 #[serde(default, skip_serializing_if = "Option::is_none")]
376 #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
377 pub url_suffix: Option<String>,
378}
379
380fn is_account_id_shaped(value: &str) -> bool {
381 value.len() == 12 && value.bytes().all(|b| b.is_ascii_digit())
382}
383
384fn is_partition_shaped(value: &str) -> bool {
385 value.starts_with("aws")
386}
387
388impl PseudoParameterOverrides {
389 pub fn region(&self) -> &str {
390 self.region.as_deref().unwrap_or(DEFAULT_REGION)
391 }
392
393 pub fn get(&self, name: &str) -> Option<String> {
394 match name {
395 PSEUDO_ACCOUNT_ID => Some(self.account_id.clone().unwrap_or_else(|| DEFAULT_ACCOUNT_ID.into())),
396 PSEUDO_NOTIFICATION_ARNS => Some(self.notification_arns.clone().unwrap_or_else(|| {
397 let r = self.region();
398 let p = self.partition.as_deref().unwrap_or_else(|| partition_for_region(r));
399 format!("arn:{}:sns:{}:{}:notification", p, r, DEFAULT_ACCOUNT_ID)
400 })),
401 PSEUDO_PARTITION => {
402 Some(self.partition.clone().unwrap_or_else(|| partition_for_region(self.region()).into()))
403 }
404 PSEUDO_REGION => Some(self.region().to_string()),
405 PSEUDO_STACK_ID => Some(self.stack_id.clone().unwrap_or_else(|| {
406 let r = self.region();
407 let p = self.partition.as_deref().unwrap_or_else(|| partition_for_region(r));
408 format!(
409 "arn:{}:cloudformation:{}:{}:stack/{}/51af3dc0-da77-11e4-872e-1234567db123",
410 p, r, DEFAULT_ACCOUNT_ID, DEFAULT_STACK_NAME
411 )
412 })),
413 PSEUDO_STACK_NAME => Some(self.stack_name.clone().unwrap_or_else(|| DEFAULT_STACK_NAME.into())),
414 PSEUDO_URL_SUFFIX => {
415 Some(self.url_suffix.clone().unwrap_or_else(|| url_suffix_for_region(self.region()).into()))
416 }
417 _ => None,
418 }
419 }
420
421 #[must_use]
422 pub fn invalid_overrides(&self) -> Vec<String> {
423 let mut problems = Vec::new();
424 if let Some(account_id) = self.account_id.as_deref()
425 && !is_account_id_shaped(account_id)
426 {
427 problems.push(format!("{PSEUDO_ACCOUNT_ID} override '{account_id}' is not a 12-digit AWS account ID"));
428 }
429 if let Some(partition) = self.partition.as_deref()
430 && !is_partition_shaped(partition)
431 {
432 problems.push(format!(
433 "{PSEUDO_PARTITION} override '{partition}' is not a valid partition \
434 (expected an 'aws'-family value such as aws, aws-cn, or aws-us-gov)"
435 ));
436 }
437 problems
438 }
439
440 pub fn fixed_value(&self, name: &str) -> Option<String> {
453 match name {
454 PSEUDO_ACCOUNT_ID => self.account_id.clone(),
455 PSEUDO_NOTIFICATION_ARNS => self.notification_arns.clone(),
456 PSEUDO_PARTITION => self.partition.clone(),
457 PSEUDO_REGION => self.region.clone(),
458 PSEUDO_STACK_ID => self.stack_id.clone(),
459 PSEUDO_STACK_NAME => self.stack_name.clone(),
460 PSEUDO_URL_SUFFIX => self.url_suffix.clone(),
461 _ => None,
462 }
463 }
464}
465
466#[derive(Default)]
467pub struct ParseConfig {
468 pub parameters: HashMap<String, String>,
469 pub pseudo_parameters: PseudoParameterOverrides,
470}
471
472#[must_use]
473pub struct ParseResult {
474 pub model: SemanticModel,
475 pub model_build_ms: f64,
477}
478
479impl SemanticModel {
480 pub fn from_bytes(bytes: &[u8]) -> Result<Self, ParseError> {
481 Self::parse(bytes, Default::default()).map(|r| r.model)
482 }
483
484 pub fn parse(bytes: &[u8], config: ParseConfig) -> Result<ParseResult, ParseError> {
485 if bytes.len() > MAX_TEMPLATE_SIZE_BYTES {
486 return Err(ParseError {
487 message: format!("Template exceeds maximum size of {}MB", MAX_TEMPLATE_SIZE_BYTES / (1024 * 1024)),
488 line: None,
489 column: None,
490 });
491 }
492
493 let total_start = web_time::Instant::now();
494
495 info!("Phase 1: Parsing IR ({} bytes)", bytes.len());
496 let mut ir = crate::parser::parse(bytes)?;
497 let foreach_diagnostics = crate::transform_expansion::expand_language_extensions(&mut ir);
498 let condition_shape_diagnostics =
499 crate::parser::condition_shape::validate_condition_bodies(&ir.arena, ir.conditions, &ir.span_index);
500 let (parameters, parameter_diagnostics) = extract_parameters(&ir);
501 let params_referenced_in_definitions = collect_parameter_definition_refs(&ir, ¶meters);
506 let (mappings, mapping_diagnostics) = extract_mappings(&ir);
507
508 let budget_tracker = Arc::new(BudgetTracker::new());
511
512 let mut conditions = ConditionModel::from_ir_with_tracker(
513 &ir,
514 ¶meters,
515 &config.pseudo_parameters,
516 &mappings,
517 Arc::clone(&budget_tracker),
518 );
519
520 let resource_ids: Vec<String> = if ir.resources != NULL_REF {
521 ir.arena
522 .as_map(ir.resources)
523 .map(|entries| entries.iter().map(|(k, _)| k.clone()).collect())
524 .unwrap_or_default()
525 } else {
526 vec![]
527 };
528 let output_count =
529 if ir.outputs != NULL_REF { ir.arena.as_map(ir.outputs).map(|e| e.len()).unwrap_or(0) } else { 0 };
530 info!("Phase 2: Resolving {} resources, {} outputs", resource_ids.len(), output_count);
531
532 let mut resolver = Resolver::new(
533 &ir.arena,
534 ¶meters,
535 &mappings,
536 resource_ids.iter().cloned().collect(),
537 &config.parameters,
538 &config.pseudo_parameters,
539 );
540 let mut resources = HashMap::new();
541 let mut lifecycle_attribute_nodes = HashMap::new();
542 let mut invalid_resource_conditions = HashSet::new();
543 if ir.resources != NULL_REF
544 && let Some(entries) = ir.arena.as_map(ir.resources)
545 {
546 for (rname, rnode) in entries {
549 if let Some(props) = ir.arena.as_map(*rnode) {
550 for (key, val) in props {
551 if key == KEY_PROPERTIES
552 && let Some(prop_entries) = ir.arena.as_map(*val)
553 && let Some((_, subs_ref)) =
554 prop_entries.iter().find(|(k, _)| k == "DefinitionSubstitutions")
555 && let Some(subs) = ir.arena.as_map(*subs_ref)
556 {
557 resolver
558 .def_subs_resources
559 .entry(rname.clone())
560 .or_default()
561 .extend(subs.iter().map(|(k, _)| k.clone()));
562 }
563 }
564 }
565 }
566 for (name, node_ref) in entries.iter().cloned() {
567 if let Some(resource_entries) = ir.arena.as_map(node_ref) {
568 for attribute in
569 [KEY_CREATION_POLICY, KEY_UPDATE_POLICY, KEY_DELETION_POLICY, KEY_UPDATE_REPLACE_POLICY]
570 {
571 if let Some((_, value_ref)) = resource_entries.iter().find(|(key, _)| key == attribute) {
572 lifecycle_attribute_nodes.insert((name.clone(), attribute.to_string()), *value_ref);
573 }
574 }
575 }
576 if invalid_resource_condition_ref(&ir.arena, node_ref).is_some() {
577 invalid_resource_conditions.insert(name.clone());
578 }
579 if name != FN_TRANSFORM && !name.starts_with(FN_FOR_EACH_KEY_PREFIX) {
583 let has_sam_transform = ir.transforms.iter().any(|t| t == TRANSFORM_SERVERLESS);
584 let shape_defects =
585 validate_resource_shape(&ir.arena, &name, node_ref, has_sam_transform, &ir.span_index);
586 resolver.diagnostics.extend(shape_defects);
587 }
588 resolver.set_current_resource(&name);
589 let resolved = resolve_resource(&ir.arena, &name, node_ref, &mut resolver);
590 resources.insert(name.clone(), resolved);
591 }
592 }
593 for (name, res) in &resources {
594 debug!(
595 "Resolved '{}' ({}): {} properties, {} edges, condition={:?}",
596 name,
597 res.resource_type,
598 res.properties.len(),
599 resolver.edges.iter().filter(|e| e.source_resource == *name).count(),
600 res.condition
601 );
602 }
603
604 let mut outputs = HashMap::new();
605 if ir.outputs != NULL_REF
606 && let Some(entries) = ir.arena.as_map(ir.outputs)
607 {
608 for (name, node_ref) in entries.iter().cloned() {
609 resolver.set_current_resource(&format!("{}{}", OUTPUT_PSEUDO_RESOURCE_PREFIX, name));
610 resolver.set_current_path(&format!("Outputs/{}/Value", name));
611 let resolved = resolve_output(&ir.arena, node_ref, &mut resolver);
612 outputs.insert(name.clone(), resolved);
613 }
614 }
615
616 if ir.rules != NULL_REF
621 && let Some(rule_entries) = ir.arena.as_map(ir.rules)
622 {
623 for (rule_name, rule_node) in rule_entries.iter().cloned() {
624 resolver.set_current_resource(&format!("{}{}", RULE_PSEUDO_RESOURCE_PREFIX, rule_name));
625 let cond_ref = ir.arena.map_get(rule_node, KEY_RULE_CONDITION);
626 if let Some(cond_ref) = cond_ref {
627 resolver.set_current_path(&format!("Rules/{}/{}", rule_name, KEY_RULE_CONDITION));
628 resolver.resolve_node(cond_ref);
629 }
630 let assertions_ref = ir.arena.map_get(rule_node, KEY_ASSERTIONS);
631 if let Some(assertions_ref) = assertions_ref
632 && let Some(assertion_items) = ir.arena.as_list(assertions_ref)
633 {
634 for (idx, item_ref) in assertion_items.to_vec().iter().enumerate() {
635 if let Some(assert_ref) = ir.arena.map_get(*item_ref, KEY_ASSERT) {
636 resolver.set_current_path(&format!(
637 "Rules/{}/{}/{}/{}",
638 rule_name, KEY_ASSERTIONS, idx, KEY_ASSERT
639 ));
640 resolver.resolve_node(assert_ref);
641 }
642 }
643 }
644 }
645 }
646
647 info!("Phase 3: Building reference graph from {} resolver edges", resolver.edges.len());
648
649 let invalid_inline_conditions = resolver.inline_conditions.iter().map(|(name, _)| name.clone()).collect();
653 conditions.register_inline_batch(resolver.inline_conditions.drain(..));
654
655 let mut find_in_map_names: std::collections::HashSet<String> = std::collections::HashSet::new();
661 let mut has_dynamic_findinmap_name = false;
662 for idx in 0..ir.arena.len() {
663 if let Node::Intrinsic(IntrinsicFn::FindInMap(map_name_ref, _, _, _)) = ir.arena.node(idx as NodeRef) {
664 match ir.arena.as_str(*map_name_ref) {
665 Some(name) => {
666 find_in_map_names.insert(name.to_string());
667 }
668 None => has_dynamic_findinmap_name = true,
669 }
670 }
671 }
672
673 let resolution_sources = resolver.resolution_sources();
674 let value_nodes = resolver.value_nodes();
675 let resolver_depth_exceeded = resolver.depth_exceeded;
676 let resolver_enum_expansion_exceeded = resolver.enum_expansion_exceeded;
677 let mut all_edges = resolver.edges;
678 for (id, res) in &resources {
679 for dep in &res.depends_on {
680 all_edges.push(ResolverEdge {
681 source_resource: id.clone(),
682 source_path: KEY_DEPENDS_ON.to_string(),
683 target: dep.clone(),
684 kind: RefKind::DependsOn,
685 span: UNKNOWN_SPAN,
686 condition_context: None,
687 });
688 }
689 }
690 let graph = ReferenceGraph::build(all_edges, &resource_ids);
691
692 let intrinsic_source_paths = build_intrinsic_source_paths(&resolution_sources, &graph);
693
694 let mut resources_by_type: HashMap<String, Vec<String>> = HashMap::new();
695 for (id, res) in &resources {
696 resources_by_type.entry(res.resource_type.clone()).or_default().push(id.clone());
697 }
698 for ids in resources_by_type.values_mut() {
704 ids.sort_by_key(|id| {
705 let key = format!("Resources/{}", id);
706 ir.span_index.get(key.as_str()).map(|s| (s.start_line, s.start_column)).unwrap_or((u32::MAX, u32::MAX))
707 });
708 }
709
710 let mut diagnostics = ir.diagnostics;
711 diagnostics.extend(foreach_diagnostics);
712 diagnostics.extend(condition_shape_diagnostics);
713 diagnostics.extend(mapping_diagnostics);
714 diagnostics.extend(parameter_diagnostics);
715
716 diagnostics.extend(crate::nesting::validate_intrinsic_nesting(&ir.arena));
717 diagnostics.extend(crate::intrinsic_arg_shapes::validate_intrinsic_arg_shapes(&ir.arena, &ir.transforms));
718 diagnostics.extend(crate::lang_ext_shapes::validate_lang_ext_parameter_shapes(&ir.arena, &ir.transforms));
719 diagnostics.extend(crate::language_extensions::validate_language_extensions(&ir.arena, &ir.transforms));
720 let lifecycle_resource_conditions: HashMap<String, String> = resources
721 .iter()
722 .filter_map(|(resource_id, resource)| {
723 resource.condition.as_ref().map(|condition| (resource_id.clone(), condition.clone()))
724 })
725 .collect();
726 diagnostics.extend(crate::language_extensions::validate_lifecycle_intrinsics(
727 &ir.arena,
728 &conditions,
729 &lifecycle_attribute_nodes,
730 &lifecycle_resource_conditions,
731 ));
732 diagnostics.extend(crate::dynamic_ref::validate_dynamic_references(&ir.arena, ir.resources));
733
734 let mut fn_if_conditions: Vec<String> = Vec::new();
735 for idx in 0..ir.arena.len() {
736 match ir.arena.node(idx as NodeRef) {
737 Node::Intrinsic(IntrinsicFn::If(cond_name, _, _)) => {
738 fn_if_conditions.push(cond_name.clone());
739 let in_conditions_body =
744 ir.arena.get(idx as NodeRef).path.split('/').next() == Some(SECTION_CONDITIONS);
745 if !in_conditions_body && !conditions.conditions.contains_key(cond_name) {
746 let condition_path = format!("{}/{}/0", ir.arena.get(idx as NodeRef).path, FN_IF);
753 diagnostics.push(crate::make_parse_defect_at(
754 "E1028",
755 format!("Fn::If condition '{}' does not exist in Conditions section", cond_name),
756 ir.span_index
757 .get(&condition_path)
758 .copied()
759 .unwrap_or_else(|| ir.arena.span(idx as NodeRef)),
760 &condition_path,
761 ));
762 }
763 }
764 Node::Map(entries) if entries.len() == 1 && entries[0].0 == FN_IF => {
771 if let Some(first) = ir.arena.as_list(entries[0].1).and_then(|items| items.first())
772 && let Some(cond_name) = ir.arena.as_str(*first)
773 {
774 fn_if_conditions.push(cond_name.to_string());
775 let in_conditions_body =
781 ir.arena.get(idx as NodeRef).path.split('/').next() == Some(SECTION_CONDITIONS);
782 if !in_conditions_body && !conditions.conditions.contains_key(cond_name) {
783 diagnostics.push(crate::make_parse_defect_at(
784 "E1028",
785 format!("Fn::If condition '{}' does not exist in Conditions section", cond_name),
786 ir.arena.span(*first),
787 &ir.arena.get(*first).path,
788 ));
789 }
790 }
791 }
792 _ => {}
793 }
794 }
795 fn_if_conditions.sort();
796 fn_if_conditions.dedup();
797 let mut output_empty_joins: Vec<String> = Vec::new();
798 for (key, joins) in &resolver.empty_joins {
799 if key.starts_with(OUTPUT_PSEUDO_RESOURCE_PREFIX) || key == OUTPUTS_PSEUDO_RESOURCE {
800 output_empty_joins.extend(joins.iter().cloned());
801 }
802 }
803
804 {
811 let mut output_raw_pseudo: Vec<(String, String)> = Vec::new();
812 for (key, entries) in &resolver.raw_pseudo_params {
813 if key.starts_with(OUTPUT_PSEUDO_RESOURCE_PREFIX) || key == OUTPUTS_PSEUDO_RESOURCE {
814 for (path, value) in entries {
815 output_raw_pseudo.push((path.clone(), value.clone()));
816 }
817 }
818 }
819 output_raw_pseudo.sort();
820 for (path, value) in output_raw_pseudo {
821 diagnostics.push(crate::make_parse_defect(
822 "W1054",
823 format!(
824 "Found a string '{}' that appears to be a pseudo parameter reference; use 'Ref: {}' instead",
825 value, value
826 ),
827 ir.span_index.get(&path).copied().unwrap_or(UNKNOWN_SPAN),
828 ));
829 }
830 }
831
832 {
837 let mut param_names: Vec<&String> = parameters.keys().collect();
838 param_names.sort();
839 for pname in param_names {
840 if let Some(default) = ¶meters[pname].default
841 && PSEUDO_PARAMETERS.contains(&default.as_str())
842 {
843 diagnostics.push(crate::make_parse_defect(
844 "W1054",
845 format!("Found a string '{}' that appears to be a pseudo parameter reference; use 'Ref: {}' instead", default, default),
846 ir.span_index.get(&format!("Parameters/{}/Default", pname)).copied().unwrap_or(UNKNOWN_SPAN),
847 ));
848 }
849 }
850 }
851
852 for idx in 0..ir.arena.len() {
858 let spanned = ir.arena.get(idx as NodeRef);
859 let Node::String(s) = &spanned.node else {
860 continue;
861 };
862 let section = spanned.path.split('/').next().unwrap_or("");
863 let is_ref_target = spanned.path.rsplit('/').next() == Some(FN_REF);
868 if (section == SECTION_MAPPINGS || section == SECTION_CONDITIONS)
869 && !is_ref_target
870 && PSEUDO_PARAMETERS.contains(&s.as_str())
871 {
872 diagnostics.push(crate::make_parse_defect(
873 "W1054",
874 format!(
875 "Found a string '{}' that appears to be a pseudo parameter reference; use 'Ref: {}' instead",
876 s, s
877 ),
878 spanned.span,
879 ));
880 }
881 }
882
883 {
888 let mut output_unsubstituted: Vec<(String, String)> = Vec::new();
889 for (key, entries) in &resolver.unsubstituted_variables {
890 if key.starts_with(OUTPUT_PSEUDO_RESOURCE_PREFIX) || key == OUTPUTS_PSEUDO_RESOURCE {
891 for (path, variable) in entries {
892 output_unsubstituted.push((path.clone(), variable.clone()));
893 }
894 }
895 }
896 output_unsubstituted.sort();
897 for (path, variable) in output_unsubstituted {
898 diagnostics.push(crate::make_parse_defect(
899 "E1029",
900 format!("Found an embedded parameter '{}' outside of an 'Fn::Sub' at {}", variable, path),
901 ir.span_index.get(&path).copied().unwrap_or(UNKNOWN_SPAN),
902 ));
903 }
904 }
905
906 diagnostics.extend(resolver.diagnostics);
907 let is_sam = ir.transforms.iter().any(|t| t == TRANSFORM_SERVERLESS);
913 for d in graph.cycle_diagnostics(&ir.span_index) {
914 if is_sam && sam::cycle_involves_sam_diagnostic(&d, &resources) {
915 continue;
916 }
917 diagnostics.push(d);
918 }
919 for (cond_name, always_val) in conditions.tautological_equals() {
920 let result_str = if always_val { "True" } else { "False" };
921 diagnostics.push(crate::make_parse_defect_at(
922 "W8003",
923 format!("Fn::Equals in condition '{}' will always return {}", cond_name, result_str),
924 ir.span_index.get(&format!("Conditions/{}", cond_name)).copied().unwrap_or(UNKNOWN_SPAN),
925 &format!("Conditions/{}", cond_name),
926 ));
927 }
928 {
935 let mut resource_ids_sorted: Vec<&String> = resources.keys().collect();
936 resource_ids_sorted.sort();
937 for rid in resource_ids_sorted {
938 if let Some(cond) = &resources[rid].condition
939 && !conditions.conditions.contains_key(cond)
940 {
941 diagnostics.push(crate::make_parse_defect_for_resource(
942 "E8002",
943 format!("Condition '{}' referenced by resource '{}' is not defined", cond, rid),
944 ir.span_index.get(&format!("Resources/{}", rid)).copied().unwrap_or(UNKNOWN_SPAN),
945 rid,
946 ));
947 }
948 }
949 let mut output_names_sorted: Vec<&String> = outputs.keys().collect();
950 output_names_sorted.sort();
951 for oname in output_names_sorted {
952 if let Some(cond) = &outputs[oname].condition
953 && !conditions.conditions.contains_key(cond)
954 {
955 diagnostics.push(crate::make_parse_defect_for_resource(
956 "E6005",
957 format!("Condition '{}' referenced by output '{}' is not defined", cond, oname),
958 ir.span_index.get(&format!("Outputs/{}", oname)).copied().unwrap_or(UNKNOWN_SPAN),
959 oname,
960 ));
961 }
962 }
963 }
964 for (owner, undefined_ref) in conditions.undefined_condition_refs() {
965 if owner.starts_with("__") || undefined_ref.starts_with("__") {
968 continue;
969 }
970 diagnostics.push(crate::make_parse_defect(
971 "E8007",
972 format!("Condition '{}' references undefined condition '{}'", owner, undefined_ref),
973 ir.span_index.get(&format!("Conditions/{}", owner)).copied().unwrap_or(UNKNOWN_SPAN),
974 ));
975 }
976 for cycle in conditions.detect_cycles() {
977 let cycle_desc = cycle.join(" -> ");
978 let first = &cycle[0];
979 diagnostics.push(crate::make_parse_defect(
980 "E9106",
981 format!("Circular dependency in conditions: {}", cycle_desc),
982 ir.span_index.get(&format!("Conditions/{}", first)).copied().unwrap_or(UNKNOWN_SPAN),
983 ));
984 }
985 for (first, other) in conditions.detect_equivalent_conditions() {
986 diagnostics.push(crate::make_parse_defect(
987 "W9053",
988 format!("Condition '{}' is equivalent to condition '{}' - consider consolidating", other, first),
989 ir.span_index.get(&format!("Conditions/{}", other)).copied().unwrap_or(UNKNOWN_SPAN),
990 ));
991 }
992 let model_build_ms = total_start.elapsed().as_secs_f64() * 1000.0;
998
999 if !diagnostics.is_empty() {
1000 warn!("{} parse-time diagnostics", diagnostics.len());
1001 }
1002 let total_props: usize = resources.values().map(|r| r.properties.len()).sum();
1003 info!(
1004 "Semantic model: {} resources ({} types, {} total properties), {} outputs, {} edges, {} conditions, {} diagnostics",
1005 resources.len(),
1006 resources_by_type.len(),
1007 total_props,
1008 outputs.len(),
1009 graph.edges.len(),
1010 conditions.conditions.len(),
1011 diagnostics.len()
1012 );
1013
1014 let template_metadata =
1015 if ir.template_metadata != NULL_REF { Some(node_to_json(&ir.arena, ir.template_metadata)) } else { None };
1016 let rules = if ir.rules != NULL_REF { Some(node_to_json(&ir.arena, ir.rules)) } else { None };
1017 let parsed_rules = parse_rules(&rules, &ir.arena, ir.rules);
1018 let rule_implications: Vec<(String, crate::ir::NodeRef, Vec<crate::ir::NodeRef>)> = parsed_rules
1019 .iter()
1020 .map(|r| {
1021 let assertion_nodes: Vec<crate::ir::NodeRef> = r.assertions.iter().map(|a| a.assert_node).collect();
1022 (r.name.clone(), r.condition_node, assertion_nodes)
1023 })
1024 .collect();
1025 if !rule_implications.is_empty() {
1026 conditions.register_rule_implications(&ir.arena, &rule_implications);
1027 }
1028 let rule_diagnostics = crate::rules::validate_rules(&rules, &ir.arena, ir.rules);
1029 diagnostics.extend(rule_diagnostics);
1030 let sam_globals = sam::extract_sam_globals(&ir.arena, ir.globals);
1031 if !sam_globals.is_empty() {
1032 sam::apply_sam_globals(&mut resources, &sam_globals, &mut ir.span_index);
1033 }
1034 let sam_implicit_resources =
1035 if is_sam { sam::collect_sam_implicit_resources(&resources) } else { HashSet::new() };
1036 let globals_param_refs =
1037 if is_sam { sam::collect_globals_param_refs(&ir.arena, ir.globals) } else { Vec::new() };
1038 if is_sam {
1039 let parameter_names: HashSet<String> = parameters.keys().cloned().collect();
1040 diagnostics.extend(sam::collect_transform_errors(
1041 &ir.arena,
1042 ir.resources,
1043 ir.globals,
1044 &resources,
1045 ¶meter_names,
1046 &ir.span_index,
1047 ));
1048 }
1049 let is_cdk = resources_by_type.contains_key(CDK_METADATA_TYPE);
1050
1051 if resolver_depth_exceeded {
1052 budget_tracker.record(BudgetKind::ResolverDepth);
1053 }
1054 if resolver_enum_expansion_exceeded {
1055 budget_tracker.record(BudgetKind::EnumExpansion);
1056 }
1057 {
1064 let has_module_or_foreach = resources.values().any(|r| r.resource_type.ends_with("::MODULE"))
1065 || resources.keys().any(|k| k.contains("Fn::ForEach"));
1066 if !has_module_or_foreach {
1067 let mut output_invalid_refs: Vec<(String, String, String)> = Vec::new();
1068 for (key, entries) in &resolver.invalid_refs {
1069 if let Some(output_name) = key.strip_prefix(OUTPUT_PSEUDO_RESOURCE_PREFIX) {
1070 for (path, target) in entries {
1071 if sam_implicit_resources.contains(target) {
1072 continue;
1073 }
1074 output_invalid_refs.push((output_name.to_string(), path.clone(), target.clone()));
1075 }
1076 }
1077 }
1078 output_invalid_refs.sort();
1079 for (output_name, path, target) in &output_invalid_refs {
1080 let mut defect =
1081 ParseDefect::new(
1082 "F6101",
1083 format!(
1084 "Ref '{}' does not reference a valid resource, parameter, or pseudo-parameter",
1085 target,
1086 ),
1087 )
1088 .location(ir.span_index.get(path).copied().unwrap_or(UNKNOWN_SPAN))
1089 .phase(DefectPhase::Parse);
1090 defect = defect.property_path(format!("Outputs.{}.Value.Ref", output_name));
1091 diagnostics.push(defect);
1092 }
1093 }
1094 }
1095
1096 Ok(ParseResult {
1097 model: SemanticModel {
1098 arena: ir.arena,
1099 root: ir.root,
1100 authored_template: OnceLock::new(),
1101 span_index: ir.span_index,
1102 format_version: ir.format_version,
1103 description: ir.description,
1104 transforms: ir.transforms,
1105 raw_top_level_keys: ir.raw_top_level_keys,
1106 template_metadata,
1107 rules,
1108 parsed_rules,
1109 parameters,
1110 mappings,
1111 conditions,
1112 resources,
1113 outputs,
1114 graph,
1115 resources_by_type,
1116 diagnostics,
1117 output_empty_joins,
1118 sam_globals,
1119 sam_implicit_resources,
1120 globals_param_refs,
1121 is_cdk,
1122 fn_if_conditions,
1123 find_in_map_names,
1124 params_referenced_in_definitions,
1125 has_dynamic_findinmap_name,
1126 resolution_sources,
1127 intrinsic_source_paths,
1128 value_nodes,
1129 lifecycle_attribute_nodes,
1130 lifecycle_attribute_status_cache: Mutex::new(HashMap::new()),
1131 invalid_resource_conditions,
1132 invalid_inline_conditions,
1133 resolve_memo: Mutex::new(HashMap::new()),
1134 raw_scenario_memo: Mutex::new(HashMap::new()),
1135 properties_scenario_cache: Mutex::new(HashMap::new()),
1136 scenario_memo: Mutex::new(HashMap::new()),
1137 lifecycle_policy_scenario_cache: Mutex::new(HashMap::new()),
1138 scenario_combinations_used: AtomicU64::new(0),
1139 budget_tracker,
1140 scenario_expansion_lock: Mutex::new(()),
1141 scenario_expansion_curtailed: AtomicBool::new(false),
1142 },
1143 model_build_ms,
1144 })
1145 }
1146
1147 pub fn resource(&self, id: &str) -> Option<&ResolvedResource> {
1148 self.resources.get(id)
1149 }
1150
1151 pub fn authored_template_json(&self) -> &serde_json::Value {
1156 self.authored_template.get_or_init(|| render_authored_json(&self.arena, self.root))
1157 }
1158
1159 #[must_use]
1165 pub fn lifecycle_attribute_status(&self, resource_id: &str, attribute: &str) -> LifecycleAttributeStatus {
1166 if !matches!(
1167 attribute,
1168 KEY_CREATION_POLICY | KEY_UPDATE_POLICY | KEY_DELETION_POLICY | KEY_UPDATE_REPLACE_POLICY
1169 ) {
1170 return LifecycleAttributeStatus::default();
1171 }
1172 let cache_key = (resource_id.to_string(), attribute.to_string());
1173 let mut cache = self.lifecycle_attribute_status_cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1174 if let Some(status) = cache.get(&cache_key) {
1175 return status.clone();
1176 }
1177
1178 let mut status = LifecycleAttributeStatus::default();
1179 if let Some(node) = self.lifecycle_attribute_nodes.get(&cache_key) {
1180 let mut assumptions = self
1181 .resources
1182 .get(resource_id)
1183 .and_then(|resource| resource.condition.as_ref())
1184 .map(|condition| vec![(condition.clone(), true)])
1185 .unwrap_or_default();
1186 collect_lifecycle_attribute_status(
1187 &self.arena,
1188 *node,
1189 &self.conditions,
1190 attribute == KEY_UPDATE_POLICY,
1191 &mut assumptions,
1192 &mut status,
1193 );
1194 }
1195 cache.insert(cache_key, status.clone());
1196 status
1197 }
1198
1199 #[must_use]
1203 pub fn lifecycle_policy_scenarios(
1204 &self,
1205 resource_id: &str,
1206 attribute: &str,
1207 ) -> Vec<(serde_json::Value, HashMap<String, bool>)> {
1208 let cache_key = (resource_id.to_string(), attribute.to_string());
1209 let mut cache = self.lifecycle_policy_scenario_cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1210 if let Some(scenarios) = cache.get(&cache_key) {
1211 return scenarios.clone();
1212 }
1213
1214 let scenarios = if !self.resource_condition_is_valid(resource_id) {
1215 Vec::new()
1216 } else {
1217 let resolved = match attribute {
1218 KEY_DELETION_POLICY => self.resources.get(resource_id).and_then(|r| r.deletion_policy.as_ref()),
1219 KEY_UPDATE_REPLACE_POLICY => {
1220 self.resources.get(resource_id).and_then(|r| r.update_replace_policy.as_ref())
1221 }
1222 _ => None,
1223 };
1224 match resolved {
1225 None => Vec::new(),
1226 Some(value) => {
1227 let initial_assumptions: HashMap<String, bool> = self
1228 .resources
1229 .get(resource_id)
1230 .and_then(|resource| resource.condition.as_ref())
1231 .map(|condition| [(condition.clone(), true)].into_iter().collect())
1232 .unwrap_or_default();
1233 let assumptions: Vec<_> =
1234 initial_assumptions.iter().map(|(name, value)| (name.clone(), *value)).collect();
1235 if !assumptions.is_empty() && !self.conditions.is_satisfiable(&assumptions) {
1236 Vec::new()
1237 } else {
1238 self.collect_scenarios_with_budget_from(
1239 value,
1240 &initial_assumptions,
1241 MAX_SCENARIO_COMBINATIONS,
1242 MAX_TOTAL_SCENARIO_COMBINATIONS,
1243 )
1244 .0
1245 .into_iter()
1246 .filter_map(|(value, conditions)| {
1247 let assumptions: Vec<_> =
1248 conditions.iter().map(|(name, value)| (name.clone(), *value)).collect();
1249 if !assumptions.is_empty() && !self.conditions.is_satisfiable(&assumptions) {
1250 return None;
1251 }
1252 let value = match value {
1253 ResolvedValue::Reference { .. }
1254 | ResolvedValue::Dynamic { .. }
1255 | ResolvedValue::TypedDynamic { .. } => return None,
1256 other => crate::serialization::resolved_value_to_json(&other),
1257 };
1258 Some((value, conditions))
1259 })
1260 .collect()
1261 }
1262 }
1263 }
1264 };
1265 cache.insert(cache_key, scenarios.clone());
1266 scenarios
1267 }
1268
1269 pub fn resources_of_type(&self, type_name: &str) -> &[String] {
1270 self.resources_by_type.get(type_name).map(|v| v.as_slice()).unwrap_or(&[])
1271 }
1272
1273 #[must_use]
1274 pub fn resource_condition_is_valid(&self, resource_id: &str) -> bool {
1275 !self.invalid_resource_conditions.contains(resource_id)
1276 }
1277
1278 #[must_use]
1282 pub fn primary_identifier_conflicts(
1283 &self,
1284 resource_type: &str,
1285 identifier_properties: &[String],
1286 ) -> Vec<(Vec<String>, BTreeSet<String>)> {
1287 let mut per_resource = Vec::new();
1288 for resource_id in self.resources_of_type(resource_type) {
1289 let scenarios = self.primary_identifier_scenarios(resource_id, identifier_properties);
1290 if !scenarios.is_empty() {
1291 per_resource.push((resource_id, scenarios));
1292 }
1293 }
1294
1295 let first_identity = per_resource
1301 .first()
1302 .and_then(|(_, scenarios)| scenarios.first())
1303 .map(|scenario| scenario.identity_tuple.as_slice());
1304 let has_one_identity = first_identity.is_some_and(|identity| {
1305 per_resource
1306 .iter()
1307 .flat_map(|(_, scenarios)| scenarios)
1308 .all(|scenario| scenario.identity_tuple.as_slice() == identity)
1309 });
1310 if has_one_identity {
1311 let mut conflicts: BTreeMap<Vec<String>, (Vec<String>, BTreeSet<String>)> = BTreeMap::new();
1312 for left_index in 0..per_resource.len() {
1313 for right_index in (left_index + 1)..per_resource.len() {
1314 let (left_resource, left_scenarios) = &per_resource[left_index];
1315 let (right_resource, right_scenarios) = &per_resource[right_index];
1316 for left in left_scenarios {
1317 for right in right_scenarios {
1318 let mut assumptions = left.assumptions.clone();
1319 assumptions.extend(right.assumptions.iter().cloned());
1320 if assumptions.is_empty() || self.conditions.is_satisfiable(&assumptions) {
1321 let (_, resources) = conflicts
1322 .entry(left.identity_tuple.clone())
1323 .or_insert_with(|| (left.display_tuple.clone(), BTreeSet::new()));
1324 resources.insert((*left_resource).clone());
1325 resources.insert((*right_resource).clone());
1326 }
1327 }
1328 }
1329 }
1330 }
1331 return conflicts.into_values().collect();
1332 }
1333
1334 let mut candidates_by_identity: HashMap<&[String], Vec<(usize, usize)>> = HashMap::new();
1340 for (resource_index, (_, scenarios)) in per_resource.iter().enumerate() {
1341 for (scenario_index, scenario) in scenarios.iter().enumerate() {
1342 candidates_by_identity
1343 .entry(scenario.identity_tuple.as_slice())
1344 .or_default()
1345 .push((resource_index, scenario_index));
1346 }
1347 }
1348 let mut cursors: Vec<IdentityGroupPairCursor> = candidates_by_identity
1349 .into_values()
1350 .filter_map(|candidates| IdentityGroupPairCursor::new(&candidates))
1351 .collect();
1352
1353 let mut conflicts: BTreeMap<Vec<String>, (Vec<String>, BTreeSet<String>)> = BTreeMap::new();
1354 {
1355 let mut record_conflict = |comparison: PrimaryIdentifierComparisonOrder| {
1356 let (left_resource_index, right_resource_index, left_scenario_index, right_scenario_index) = comparison;
1357 let (left_resource, left_scenarios) = &per_resource[left_resource_index];
1358 let (right_resource, right_scenarios) = &per_resource[right_resource_index];
1359 let left = &left_scenarios[left_scenario_index];
1360 let right = &right_scenarios[right_scenario_index];
1361 let mut assumptions = left.assumptions.clone();
1362 assumptions.extend(right.assumptions.iter().cloned());
1363 if assumptions.is_empty() || self.conditions.is_satisfiable(&assumptions) {
1364 let (_, resources) = conflicts
1365 .entry(left.identity_tuple.clone())
1366 .or_insert_with(|| (left.display_tuple.clone(), BTreeSet::new()));
1367 resources.insert((*left_resource).clone());
1368 resources.insert((*right_resource).clone());
1369 }
1370 };
1371
1372 if cursors.len() <= 1 {
1379 if let Some(cursor) = cursors.pop() {
1380 for comparison in cursor {
1381 record_conflict(comparison);
1382 }
1383 }
1384 } else {
1385 let mut frontier = BinaryHeap::with_capacity(cursors.len());
1386 for (cursor_index, cursor) in cursors.iter_mut().enumerate() {
1387 if let Some(comparison) = cursor.next() {
1388 frontier.push(Reverse((comparison, cursor_index)));
1389 }
1390 }
1391 while let Some(Reverse((comparison, cursor_index))) = frontier.pop() {
1392 record_conflict(comparison);
1393 if let Some(next_comparison) = cursors[cursor_index].next() {
1394 frontier.push(Reverse((next_comparison, cursor_index)));
1395 }
1396 }
1397 }
1398 }
1399 conflicts.into_values().collect()
1400 }
1401
1402 fn primary_identifier_scenarios(
1403 &self,
1404 resource_id: &str,
1405 identifier_properties: &[String],
1406 ) -> Vec<PrimaryIdentifierScenario> {
1407 if !self.resource_condition_is_valid(resource_id) {
1408 return Vec::new();
1409 }
1410 let base_assumptions = self
1411 .resources
1412 .get(resource_id)
1413 .and_then(|resource| resource.condition.as_deref())
1414 .map(|condition| vec![(condition.to_string(), true)])
1415 .unwrap_or_default();
1416 let mut scenarios = vec![PrimaryIdentifierScenario {
1417 identity_tuple: Vec::with_capacity(identifier_properties.len()),
1418 display_tuple: Vec::with_capacity(identifier_properties.len()),
1419 assumptions: base_assumptions,
1420 }];
1421
1422 for property in identifier_properties {
1423 let path = format!("Properties.{property}");
1424 let property_scenarios = self.resolve_scenarios_json(resource_id, &path);
1425 let expression_identity =
1426 self.value_identity(resource_id, &path).filter(|identity| identity.starts_with("expr:"));
1427 let effective_scenarios: Vec<(String, String, HashMap<String, bool>)> = if property_scenarios.is_empty()
1428 || (expression_identity.is_some()
1429 && property_scenarios.iter().all(|(_, conditions)| conditions.is_empty()))
1430 {
1431 expression_identity
1432 .map(|identity| {
1433 let display = identity.strip_prefix("expr:").unwrap_or(&identity).to_string();
1434 vec![(identity, display, HashMap::new())]
1435 })
1436 .unwrap_or_default()
1437 } else {
1438 property_scenarios
1439 .into_iter()
1440 .filter_map(|(value, conditions)| {
1441 if value.is_null() {
1442 return None;
1443 }
1444 let display = value.as_str().map(ToOwned::to_owned).unwrap_or_else(|| value.to_string());
1445 let identity = format!("value:{}", crate::value_identity::concrete_value_fingerprint(&value));
1446 Some((identity, display, conditions))
1447 })
1448 .collect()
1449 };
1450 let mut next = Vec::new();
1451 for existing in &scenarios {
1452 for (identity, display, conditions) in &effective_scenarios {
1453 let mut assumptions = existing.assumptions.clone();
1454 let mut consistent = true;
1455 for (condition, truth) in conditions {
1456 if let Some((_, prior)) = assumptions.iter().find(|(name, _)| name == condition) {
1457 if prior != truth {
1458 consistent = false;
1459 break;
1460 }
1461 } else {
1462 assumptions.push((condition.clone(), *truth));
1463 }
1464 }
1465 if consistent {
1466 let mut identity_tuple = existing.identity_tuple.clone();
1467 identity_tuple.push(identity.clone());
1468 let mut display_tuple = existing.display_tuple.clone();
1469 display_tuple.push(display.clone());
1470 next.push(PrimaryIdentifierScenario { identity_tuple, display_tuple, assumptions });
1471 }
1472 }
1473 }
1474 scenarios = next;
1475 if scenarios.is_empty() {
1476 break;
1477 }
1478 }
1479
1480 scenarios.retain(|scenario| {
1481 scenario.identity_tuple.len() == identifier_properties.len()
1482 && (scenario.assumptions.is_empty() || self.conditions.is_satisfiable(&scenario.assumptions))
1483 });
1484 scenarios
1485 }
1486
1487 #[must_use]
1488 pub fn condition_is_valid_for_reachability(&self, condition: &str) -> bool {
1489 !self.invalid_inline_conditions.contains(condition)
1490 }
1491
1492 #[must_use]
1493 pub fn resolve(&self, resource_id: &str, path: &str) -> Option<&ResolvedValue> {
1494 let resource = self.resources.get(resource_id)?;
1495 resource.properties.get(path.strip_prefix("Properties.").unwrap_or(path))
1496 }
1497
1498 #[must_use]
1499 pub fn resolve_deep(&self, resource_id: &str, path: &str) -> Option<ResolvedValue> {
1500 let memo_key = (resource_id.to_string(), path.to_string());
1501 if let Some(memoized) = self.resolve_memo.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get(&memo_key)
1502 {
1503 return memoized.clone();
1504 }
1505 let resource = self.resources.get(resource_id)?;
1506 let prop_path = path.strip_prefix("Properties.").unwrap_or(path);
1507 let mut segments = prop_path.splitn(2, '.');
1508 let top_key = segments.next()?;
1509 let resolved = resource.properties.get(top_key)?;
1510 let result = match segments.next() {
1511 Some(r) if !r.is_empty() => resolved_value_at_path(resolved, r),
1512 _ => Some(resolved.clone()),
1513 };
1514 self.resolve_memo.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(memo_key, result.clone());
1515 result
1516 }
1517
1518 #[must_use]
1519 pub fn is_from_parameter(&self, resource_id: &str, path: &str) -> bool {
1520 self.parameter_name_at(resource_id, path).is_some()
1521 }
1522
1523 pub(crate) fn authored_sub_template_at(&self, resource_id: &str, path: &str) -> Option<&str> {
1524 let resource_id = resource_id.to_string();
1525 let mut current = path;
1526 loop {
1527 if let Some(node) = self.value_nodes.get(&(resource_id.clone(), current.to_string()))
1528 && let Node::Intrinsic(IntrinsicFn::Sub(template, _)) = self.arena.node(*node)
1529 {
1530 return Some(template.as_str());
1531 }
1532 let (parent, _) = current.rsplit_once('.')?;
1533 current = parent;
1534 }
1535 }
1536
1537 #[must_use]
1543 pub fn parameter_name_at(&self, resource_id: &str, path: &str) -> Option<&str> {
1544 let source = self.resolution_sources.get(&(resource_id.to_string(), path.to_string()))?;
1545 parameter_name_from_source(source)
1546 }
1547
1548 #[must_use]
1558 pub fn value_identity(&self, resource_id: &str, path: &str) -> Option<String> {
1559 let resolved = self.resolve_deep(resource_id, path).or_else(|| self.resolve(resource_id, path).cloned())?;
1560 self.resolved_value_identity(resource_id, path, &resolved)
1561 }
1562
1563 pub(crate) fn resolved_value_identity(
1567 &self,
1568 resource_id: &str,
1569 path: &str,
1570 resolved: &ResolvedValue,
1571 ) -> Option<String> {
1572 let reference_prefix = format!("{path}.");
1573 let depends_on_reference = self
1574 .graph
1575 .outgoing_edges(resource_id)
1576 .any(|edge| edge.source_path == path || edge.source_path.starts_with(&reference_prefix));
1577 let as_json = crate::serialization::resolved_value_to_json(resolved);
1578 if !depends_on_reference && !json_contains_markers(&as_json) {
1579 let fingerprint = crate::value_identity::concrete_value_fingerprint(&as_json);
1580 return Some(format!("value:{fingerprint}"));
1581 }
1582 let node = *self.value_nodes.get(&(resource_id.to_string(), path.to_string()))?;
1583 let (result, depth_exhausted) = crate::value_identity::expression_fingerprint_signaled(&self.arena, node);
1584 if depth_exhausted {
1585 self.budget_tracker.record(BudgetKind::ExpressionFingerprintDepth);
1586 }
1587 result.map(|fingerprint| format!("expr:{fingerprint}"))
1588 }
1589
1590 #[must_use]
1594 pub fn is_from_intrinsic(&self, resource_id: &str, path: &str) -> bool {
1595 if self.path_from_intrinsic(resource_id, path) {
1596 return true;
1597 }
1598 let properties_prefix = format!("{}.", KEY_PROPERTIES);
1604 if let Some(rest) = path.strip_prefix(&properties_prefix) {
1605 for branch in ["1", "2"] {
1606 let branch_path = format!("{}.{}.{}.{}", KEY_PROPERTIES, FN_IF, branch, rest);
1607 if self.path_from_intrinsic(resource_id, &branch_path) {
1608 return true;
1609 }
1610 }
1611 }
1612 false
1613 }
1614
1615 #[must_use]
1616 pub fn substituted_paths_under(&self, resource_id: &str, base_path: &str) -> HashSet<String> {
1617 let prefix = format!("{}.", base_path);
1618 let relative_path = |path: &str| {
1619 if path == base_path { Some(String::new()) } else { path.strip_prefix(&prefix).map(String::from) }
1620 };
1621 let mut paths: HashSet<String> =
1622 self.graph.outgoing_edges(resource_id).filter_map(|edge| relative_path(&edge.source_path)).collect();
1623 paths.extend(self.resolution_sources.iter().filter_map(|((source_resource, source_path), _)| {
1624 (source_resource == resource_id).then(|| relative_path(source_path)).flatten()
1625 }));
1626 paths
1627 }
1628
1629 fn path_from_intrinsic(&self, resource_id: &str, path: &str) -> bool {
1630 let Some(intrinsic_paths) = self.intrinsic_source_paths.get(resource_id) else {
1631 return false;
1632 };
1633 let mut ancestor = path;
1639 loop {
1640 if intrinsic_paths.contains(ancestor) {
1641 return true;
1642 }
1643 match ancestor.rfind('.') {
1644 Some(dot) => ancestor = &ancestor[..dot],
1645 None => return false,
1646 }
1647 }
1648 }
1649
1650 #[must_use]
1655 pub fn scenario_budget_exhausted(&self) -> bool {
1656 self.scenario_combinations_used.load(Ordering::Relaxed) >= MAX_TOTAL_SCENARIO_COMBINATIONS
1657 }
1658
1659 pub fn record_budget_exhaustion(&self, kind: BudgetKind) {
1661 self.budget_tracker.record(kind);
1662 }
1663
1664 pub fn exhausted_budget_kinds(&self) -> BTreeSet<BudgetKind> {
1666 self.budget_tracker.exhausted_kinds()
1667 }
1668
1669 pub fn budget_analysis_incomplete(&self) -> bool {
1671 self.budget_tracker.analysis_incomplete()
1672 }
1673
1674 #[must_use]
1676 pub fn scenario_combinations_used(&self) -> u64 {
1677 self.scenario_combinations_used.load(Ordering::Relaxed)
1678 }
1679
1680 #[must_use]
1685 pub fn scenario_expansion_curtailed(&self) -> bool {
1686 self.scenario_expansion_curtailed.load(Ordering::Relaxed)
1687 }
1688
1689 fn collect_scenarios_with_budget_status(
1690 &self,
1691 value: &ResolvedValue,
1692 per_value_limit: usize,
1693 total_limit: u64,
1694 ) -> (Vec<(ResolvedValue, HashMap<String, bool>)>, bool) {
1695 self.collect_scenarios_with_budget_from(value, &HashMap::new(), per_value_limit, total_limit)
1696 }
1697
1698 fn collect_scenarios_with_budget_from(
1699 &self,
1700 value: &ResolvedValue,
1701 assumptions: &HashMap<String, bool>,
1702 per_value_limit: usize,
1703 total_limit: u64,
1704 ) -> (Vec<(ResolvedValue, HashMap<String, bool>)>, bool) {
1705 let _expansion_guard = self.scenario_expansion_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1706 let used = self.scenario_combinations_used.load(Ordering::Relaxed);
1707 if used >= total_limit {
1708 self.scenario_expansion_curtailed.store(true, Ordering::Relaxed);
1709 if total_limit == MAX_TOTAL_SCENARIO_COMBINATIONS {
1710 self.budget_tracker.record(BudgetKind::ScenarioCombinationsTotal);
1711 }
1712 return (Vec::new(), true);
1713 }
1714
1715 let remaining = total_limit - used;
1716 let remaining_limit = usize::try_from(remaining).unwrap_or(usize::MAX);
1717 let effective_limit = per_value_limit.min(remaining_limit);
1718 let mut scenarios = Vec::new();
1719 let was_curtailed = collect_scenarios(value, assumptions, effective_limit, &mut scenarios);
1720 if was_curtailed {
1721 self.scenario_expansion_curtailed.store(true, Ordering::Relaxed);
1722 if per_value_limit == MAX_SCENARIO_COMBINATIONS && per_value_limit <= remaining_limit {
1723 self.budget_tracker.record(BudgetKind::ScenarioCombinationsPerValue);
1724 }
1725 if total_limit == MAX_TOTAL_SCENARIO_COMBINATIONS && remaining_limit <= per_value_limit {
1726 self.budget_tracker.record(BudgetKind::ScenarioCombinationsTotal);
1727 }
1728 }
1729 self.scenario_combinations_used.store(used + scenarios.len() as u64, Ordering::Relaxed);
1730 (scenarios, was_curtailed)
1731 }
1732
1733 fn collect_scenarios_with_budget(
1734 &self,
1735 value: &ResolvedValue,
1736 per_value_limit: usize,
1737 total_limit: u64,
1738 ) -> Vec<(ResolvedValue, HashMap<String, bool>)> {
1739 self.collect_scenarios_with_budget_status(value, per_value_limit, total_limit).0
1740 }
1741
1742 #[cfg(test)]
1746 pub(crate) fn add_scenario_combinations_for_test(&self, count: u64) {
1747 let _expansion_guard = self.scenario_expansion_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1748 self.scenario_combinations_used.fetch_add(count, Ordering::Relaxed);
1749 }
1750
1751 #[cfg(test)]
1754 fn set_scenario_expansion_curtailed_for_test(&self) {
1755 self.scenario_expansion_curtailed.store(true, Ordering::Relaxed);
1756 }
1757
1758 fn resolved_properties_value(&self, resource_id: &str) -> Option<ResolvedValue> {
1759 let resource = self.resources.get(resource_id)?;
1760 if resource.properties_dynamic {
1761 return None;
1762 }
1763 if resource.properties.len() == 1
1764 && let Some(conditional) = resource.properties.get(FN_IF)
1765 {
1766 return Some(conditional.clone());
1767 }
1768 let mut entries: Vec<MapEntry> = resource
1769 .properties
1770 .iter()
1771 .map(|(key, value)| MapEntry { key: key.clone(), value: value.clone() })
1772 .collect();
1773 entries.sort_by(|left, right| left.key.cmp(&right.key));
1774 Some(ResolvedValue::Map { entries })
1775 }
1776
1777 pub fn resolve_properties_scenarios_shared(
1782 &self,
1783 resource_id: &str,
1784 ) -> Arc<Vec<(ResolvedValue, HashMap<String, bool>)>> {
1785 let mut cache = self.properties_scenario_cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1786 if let Some(scenarios) = cache.get(resource_id) {
1787 return Arc::clone(scenarios);
1788 }
1789 let scenarios = match self.resolved_properties_value(resource_id) {
1790 Some(properties) => self.collect_scenarios_with_budget(
1791 &properties,
1792 MAX_SCENARIO_COMBINATIONS,
1793 MAX_TOTAL_SCENARIO_COMBINATIONS,
1794 ),
1795 None => Vec::new(),
1796 };
1797 let shared = Arc::new(scenarios);
1798 cache.insert(resource_id.to_string(), Arc::clone(&shared));
1799 shared
1800 }
1801
1802 pub fn resolve_properties_scenarios(&self, resource_id: &str) -> Vec<(ResolvedValue, HashMap<String, bool>)> {
1803 self.resolve_properties_scenarios_shared(resource_id).as_ref().clone()
1804 }
1805
1806 pub fn scenario_source_path(
1810 &self,
1811 resource_id: &str,
1812 effective_path: &str,
1813 conditions: &HashMap<String, bool>,
1814 ) -> Option<String> {
1815 let properties = self.resolved_properties_value(resource_id)?;
1816 let relative_path = effective_path
1817 .strip_prefix("Properties.")
1818 .or_else(|| (effective_path == KEY_PROPERTIES).then_some(""))
1819 .unwrap_or(effective_path);
1820 scenario_source_path_at(&properties, relative_path, conditions, KEY_PROPERTIES)
1821 }
1822
1823 pub fn resolve_scenarios(&self, resource_id: &str, path: &str) -> Vec<(ResolvedValue, HashMap<String, bool>)> {
1824 let key = (resource_id.to_string(), path.to_string());
1825 let mut memo = self.raw_scenario_memo.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1826 if let Some(scenarios) = memo.get(&key) {
1827 return scenarios.clone();
1828 }
1829 let scenarios = self.resolve_scenarios_with_limit(resource_id, path, MAX_SCENARIO_COMBINATIONS).0;
1830 memo.insert(key, scenarios.clone());
1831 scenarios
1832 }
1833
1834 pub fn resolve_scenarios_with_limit(
1835 &self,
1836 resource_id: &str,
1837 path: &str,
1838 per_value_limit: usize,
1839 ) -> (Vec<(ResolvedValue, HashMap<String, bool>)>, bool) {
1840 let value = match self.resolve_deep(resource_id, path) {
1841 Some(value) => value,
1842 None => match self.resolve(resource_id, path) {
1843 Some(value) => value.clone(),
1844 None => match self.resolve_via_properties_if(resource_id, path) {
1845 Some(value) => value,
1846 None => return (Vec::new(), false),
1847 },
1848 },
1849 };
1850 self.collect_scenarios_with_budget_status(&value, per_value_limit, MAX_TOTAL_SCENARIO_COMBINATIONS)
1851 }
1852
1853 fn resolve_via_properties_if(&self, resource_id: &str, path: &str) -> Option<ResolvedValue> {
1857 let resource = self.resources.get(resource_id)?;
1858 let conditional = resource.properties.get(FN_IF)?;
1859 let properties_prefix = format!("{}.", KEY_PROPERTIES);
1860 let prop_path = path.strip_prefix(&properties_prefix).unwrap_or(path);
1861 if prop_path.is_empty() {
1862 return Some(conditional.clone());
1863 }
1864 resolved_value_at_path(conditional, prop_path)
1865 }
1866
1867 fn resolve_scenarios_json_uncached(
1868 &self,
1869 resource_id: &str,
1870 path: &str,
1871 ) -> Vec<(serde_json::Value, HashMap<String, bool>)> {
1872 self.resolve_scenarios(resource_id, path)
1873 .into_iter()
1874 .filter_map(|(val, conds)| {
1875 if contains_dynamic_resolved(&val) {
1876 return None;
1877 }
1878 if !conds.is_empty() {
1879 let assumptions: Vec<(String, bool)> = conds.iter().map(|(k, v)| (k.clone(), *v)).collect();
1880 if !self.conditions.is_satisfiable(&assumptions) {
1881 return None;
1882 }
1883 }
1884 let json = crate::serialization::resolved_value_to_json_clean(&val)?;
1885 if json_contains_markers(&json) {
1886 return None;
1887 }
1888 Some((json, conds))
1889 })
1890 .collect()
1891 }
1892
1893 fn cache_json_scenarios(
1894 &self,
1895 memo_key: (String, String),
1896 scenarios: Vec<(serde_json::Value, HashMap<String, bool>)>,
1897 ) -> Arc<Vec<(serde_json::Value, HashMap<String, bool>)>> {
1898 let mut memo = self.scenario_memo.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1899 Arc::clone(memo.entry(memo_key).or_insert_with(|| Arc::new(scenarios)))
1900 }
1901
1902 pub fn resolve_scenarios_json_shared(
1904 &self,
1905 resource_id: &str,
1906 path: &str,
1907 ) -> Arc<Vec<(serde_json::Value, HashMap<String, bool>)>> {
1908 let memo_key = (resource_id.to_string(), path.to_string());
1909 {
1910 let memo = self.scenario_memo.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1911 if let Some(memoized) = memo.get(&memo_key) {
1912 return Arc::clone(memoized);
1913 }
1914 }
1915 let scenarios = self.resolve_scenarios_json_uncached(resource_id, path);
1916 self.cache_json_scenarios(memo_key, scenarios)
1917 }
1918
1919 pub fn resolve_scenarios_json(
1920 &self,
1921 resource_id: &str,
1922 path: &str,
1923 ) -> Vec<(serde_json::Value, HashMap<String, bool>)> {
1924 let memo_key = (resource_id.to_string(), path.to_string());
1925 {
1926 let memo = self.scenario_memo.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1927 if let Some(memoized) = memo.get(&memo_key) {
1928 return memoized.as_ref().clone();
1929 }
1930 }
1931 let scenarios = self.resolve_scenarios_json_uncached(resource_id, path);
1932 self.cache_json_scenarios(memo_key, scenarios).as_ref().clone()
1933 }
1934
1935 pub fn follow_ref(&self, resource_id: &str, path: &str) -> Option<&str> {
1936 if let Some(ResolvedValue::Reference { target, kind: _ }) = self.resolve(resource_id, path) {
1937 return Some(target.as_str());
1938 }
1939 if let Some(ResolvedValue::Reference { target, kind: _ }) = self.resolve_deep(resource_id, path).as_ref() {
1940 for edge in self.graph.outgoing_edges(resource_id) {
1941 if edge.target == *target {
1942 return Some(&edge.target);
1943 }
1944 }
1945 }
1946 None
1947 }
1948
1949 pub fn source_location(&self, path: &str) -> Option<&SourceSpan> {
1950 self.span_index.get(path)
1951 }
1952
1953 pub fn resource_span(&self, resource_id: &str, prop_path: &str) -> SourceSpan {
1963 if resource_id.is_empty() {
1970 return self.walk_up_span(prop_path).unwrap_or(UNKNOWN_SPAN);
1971 }
1972 if let Some((authored_path, function_name)) = prop_path.rsplit_once('.')
1976 && let Some(node_ref) = self.value_nodes.get(&(resource_id.to_string(), authored_path.to_string()))
1977 && let Node::Intrinsic(intrinsic) = self.arena.node(*node_ref)
1978 && cfn_function_name(intrinsic) == function_name
1979 {
1980 let intrinsic_path = format!("{}/{}", self.arena.get(*node_ref).path, function_name);
1981 if let Some(span) = self.walk_up_span(&intrinsic_path) {
1982 return span;
1983 }
1984 }
1985 let specific = if prop_path.is_empty() {
1986 format!("Resources/{}", resource_id)
1987 } else {
1988 format!("Resources/{}/{}", resource_id, prop_path.replace('.', "/"))
1989 };
1990 self.walk_up_span(&specific).unwrap_or(UNKNOWN_SPAN)
1996 }
1997
1998 fn walk_up_span(&self, key: &str) -> Option<SourceSpan> {
2004 let mut current = key;
2005 loop {
2006 match self.span_index.get(current) {
2011 Some(&span) if span != UNKNOWN_SPAN => return Some(span),
2012 _ => match current.rfind('/') {
2013 Some(cut) => current = ¤t[..cut],
2014 None => return None,
2015 },
2016 }
2017 }
2018 }
2019
2020 pub fn diagnostic_span(&self, resource_id: Option<&str>, property_path: &str) -> Option<SourceSpan> {
2036 let rid = resource_id.filter(|r| !r.is_empty());
2037
2038 if property_path.contains('/') || (rid.is_none() && !property_path.is_empty()) {
2039 if let Some(span) = self.walk_up_span(property_path) {
2041 return Some(span);
2042 }
2043 } else if let Some(rid) = rid {
2044 let key = if property_path.is_empty() {
2047 format!("Resources/{}", rid)
2048 } else {
2049 format!("Resources/{}/{}", rid, property_path.replace('.', "/"))
2050 };
2051 if let Some(span) = self.walk_up_span(&key) {
2052 return Some(span);
2053 }
2054 }
2055
2056 rid.and_then(|rid| self.span_index.get(&format!("Resources/{}", rid)))
2058 .filter(|span| **span != UNKNOWN_SPAN)
2059 .copied()
2060 }
2061
2062 pub fn estimated_string_length_bounds(&self, resource_id: &str, path: &str) -> Option<(usize, usize)> {
2071 let val = self.resolve_deep(resource_id, path).or_else(|| self.resolve(resource_id, path).cloned())?;
2072 if matches!(&val, ResolvedValue::Concrete { value } if value.is_string()) {
2073 return None;
2074 }
2075 estimate_resolved_string_length_bounds(&val)
2076 }
2077}
2078
2079impl SpanProvider for SemanticModel {
2080 fn source_location(&self, path: &str) -> Option<SourceSpan> {
2081 self.span_index.get(path).copied()
2082 }
2083}
2084
2085fn parse_rules(rules_json: &Option<serde_json::Value>, arena: &Arena, rules_node: NodeRef) -> Vec<TemplateRule> {
2086 let Some(rules) = rules_json else {
2087 return Vec::new();
2088 };
2089 let Some(obj) = rules.as_object() else {
2090 return Vec::new();
2091 };
2092
2093 let rule_nodes: HashMap<&str, NodeRef> =
2095 arena.as_map(rules_node).unwrap_or(&[]).iter().map(|(k, v)| (k.as_str(), *v)).collect();
2096
2097 obj.iter()
2098 .filter_map(|(name, rule)| {
2099 let rule_obj = rule.as_object()?;
2100 let condition = rule_obj.get(KEY_RULE_CONDITION).cloned();
2101
2102 let rule_ir = rule_nodes.get(name.as_str()).copied().unwrap_or(NULL_REF);
2104 let condition_node = arena.map_get(rule_ir, KEY_RULE_CONDITION).unwrap_or(NULL_REF);
2105
2106 let assertions_node = arena.map_get(rule_ir, KEY_ASSERTIONS).unwrap_or(NULL_REF);
2107 let assertion_items = arena.as_list(assertions_node).unwrap_or(&[]);
2108
2109 let assertions = rule_obj
2110 .get(KEY_ASSERTIONS)
2111 .and_then(|a| a.as_array())
2112 .map(|arr| {
2113 arr.iter()
2114 .enumerate()
2115 .filter_map(|(idx, a)| {
2116 let a_obj = a.as_object()?;
2117 let assert_node = assertion_items
2118 .get(idx)
2119 .and_then(|item_ref| arena.map_get(*item_ref, KEY_ASSERT))
2120 .unwrap_or(NULL_REF);
2121 Some(RuleAssertion {
2122 assert: a_obj.get(KEY_ASSERT).cloned().unwrap_or(serde_json::Value::Null),
2123 assert_node,
2124 description: a_obj
2125 .get(KEY_ASSERT_DESCRIPTION)
2126 .and_then(|d| d.as_str())
2127 .map(String::from),
2128 })
2129 })
2130 .collect()
2131 })
2132 .unwrap_or_default();
2133 Some(TemplateRule { name: name.clone(), condition, condition_node, assertions })
2134 })
2135 .collect()
2136}
2137
2138fn collect_parameter_definition_refs(ir: &TemplateIR, parameters: &HashMap<String, ParameterInfo>) -> HashSet<String> {
2142 let mut referenced = HashSet::new();
2143 if ir.parameters == NULL_REF {
2144 return referenced;
2145 }
2146 let Some(param_entries) = ir.arena.as_map(ir.parameters) else {
2147 return referenced;
2148 };
2149 for (_, param_ref) in param_entries {
2150 collect_refs_in_subtree(&ir.arena, *param_ref, parameters, &mut referenced);
2151 }
2152 referenced
2153}
2154
2155fn collect_refs_in_subtree(
2156 arena: &Arena,
2157 node_ref: NodeRef,
2158 parameters: &HashMap<String, ParameterInfo>,
2159 referenced: &mut HashSet<String>,
2160) {
2161 match arena.node(node_ref) {
2162 Node::Intrinsic(IntrinsicFn::Ref(target)) => {
2163 if parameters.contains_key(target) {
2164 referenced.insert(target.clone());
2165 }
2166 }
2167 Node::Intrinsic(IntrinsicFn::Sub(_, Some(bindings))) => {
2168 for (_, v) in bindings {
2169 collect_refs_in_subtree(arena, *v, parameters, referenced);
2170 }
2171 }
2172 Node::List(items) => {
2173 for item in items {
2174 collect_refs_in_subtree(arena, *item, parameters, referenced);
2175 }
2176 }
2177 Node::Map(entries) => {
2178 for (_, v) in entries {
2179 collect_refs_in_subtree(arena, *v, parameters, referenced);
2180 }
2181 }
2182 _ => {}
2183 }
2184}
2185
2186fn parameter_name_from_source(source: &str) -> Option<&str> {
2187 let rest = source.strip_prefix(SECTION_PARAMETERS)?.strip_prefix('/')?;
2188 let name = rest.split('/').next()?;
2189 if name.is_empty() { None } else { Some(name) }
2190}
2191
2192const INTRINSIC_SOURCE_PREFIX: &str = "Intrinsic/";
2194
2195fn build_intrinsic_source_paths(
2203 resolution_sources: &HashMap<(String, String), String>,
2204 graph: &ReferenceGraph,
2205) -> HashMap<String, HashSet<String>> {
2206 let mut paths_by_resource: HashMap<String, HashSet<String>> = HashMap::new();
2207 for ((resource_id, path), source) in resolution_sources {
2208 if source.starts_with(INTRINSIC_SOURCE_PREFIX) {
2209 paths_by_resource.entry(resource_id.clone()).or_default().insert(path.clone());
2210 }
2211 }
2212 for edge in &graph.edges {
2213 paths_by_resource.entry(edge.source_resource.clone()).or_default().insert(edge.source_path.clone());
2214 }
2215 paths_by_resource
2216}
2217
2218fn intrinsic_synthetic_key(arena: &Arena, node_ref: NodeRef) -> Option<String> {
2225 let Node::Intrinsic(func) = arena.node(node_ref) else {
2226 return None;
2227 };
2228 match func {
2229 IntrinsicFn::If(_, _, _) | IntrinsicFn::IfExpr(_, _, _) => Some(FN_IF.to_string()),
2230 IntrinsicFn::ForEach(uid, _, _, _) => Some(format!("{}::{}", FN_FOR_EACH, uid)),
2231 _ => None,
2232 }
2233}
2234
2235const VALID_RESOURCE_ATTRIBUTES: &[&str] = &[
2239 KEY_TYPE,
2240 KEY_PROPERTIES,
2241 KEY_DEPENDS_ON,
2242 KEY_CONDITION,
2243 SECTION_METADATA,
2244 KEY_DELETION_POLICY,
2245 KEY_UPDATE_REPLACE_POLICY,
2246 KEY_UPDATE_POLICY,
2247 KEY_CREATION_POLICY,
2248 FN_TRANSFORM,
2249 "Version",
2250];
2251
2252const SAM_RESOURCE_ATTRIBUTES: &[&str] = &["Connectors", "IgnoreGlobals"];
2256
2257fn invalid_resource_condition_ref(arena: &Arena, node_ref: NodeRef) -> Option<NodeRef> {
2258 let entries = arena.as_map(node_ref)?;
2259 let condition_ref = entries.iter().find(|(key, _)| key == KEY_CONDITION).map(|(_, value)| *value)?;
2260 (!matches!(arena.node(condition_ref), Node::String(_))).then_some(condition_ref)
2261}
2262
2263fn validate_resource_shape(
2267 arena: &Arena,
2268 name: &str,
2269 node_ref: NodeRef,
2270 is_sam: bool,
2271 span_index: &SourceSpanIndex,
2272) -> Vec<ParseDefect> {
2273 let mut out = Vec::new();
2274 let resource_span = span_index.get(&format!("Resources/{}", name)).copied().unwrap_or(UNKNOWN_SPAN);
2275
2276 let entries = match arena.as_map(node_ref) {
2278 Some(entries) => entries,
2279 None => {
2280 let shape = match arena.node(node_ref) {
2281 Node::Null => "null",
2282 Node::Bool(_) => "a boolean",
2283 Node::Int(_) | Node::Float(_) => "a number",
2284 Node::String(_) => "a string",
2285 Node::List(_) => "a list",
2286 Node::Intrinsic(_) => "an intrinsic function",
2287 Node::Map(_) => return out,
2288 };
2289 out.push(crate::make_parse_defect_for_resource(
2290 "E3001",
2291 format!("Resource '{}' body must be an object, got {}", name, shape),
2292 resource_span,
2293 name,
2294 ));
2295 return out;
2296 }
2297 };
2298
2299 match entries.iter().find(|(k, _)| k == KEY_TYPE) {
2301 None => {
2302 out.push(crate::make_parse_defect_for_resource(
2303 "E3001",
2304 format!("Resource '{}' is missing required property 'Type'", name),
2305 resource_span,
2306 name,
2307 ));
2308 }
2309 Some((_, type_ref)) if !matches!(arena.node(*type_ref), Node::String(_)) => {
2310 let type_span = span_index.get(&format!("Resources/{}/Type", name)).copied().unwrap_or(resource_span);
2311 out.push(crate::make_parse_defect_for_resource(
2312 "E3001",
2313 format!("Resource '{}' property 'Type' must be a string", name),
2314 type_span,
2315 name,
2316 ));
2317 }
2318 _ => {}
2319 }
2320
2321 if invalid_resource_condition_ref(arena, node_ref).is_some() {
2323 let cond_span = span_index.get(&format!("Resources/{}/Condition", name)).copied().unwrap_or(resource_span);
2324 out.push(crate::make_parse_defect_for_resource(
2325 "E3001",
2326 format!("Resource '{}' property 'Condition' must be a string", name),
2327 cond_span,
2328 name,
2329 ));
2330 }
2331
2332 if let Some((_, dep_ref)) = entries.iter().find(|(k, _)| k == KEY_DEPENDS_ON) {
2334 match arena.node(*dep_ref) {
2335 Node::String(_) => {}
2336 Node::List(items) => {
2337 for item_ref in items {
2338 if !matches!(arena.node(*item_ref), Node::String(_)) {
2339 let dep_span =
2340 span_index.get(&format!("Resources/{}/DependsOn", name)).copied().unwrap_or(resource_span);
2341 out.push(crate::make_parse_defect_for_resource(
2342 "E3001",
2343 format!("Resource '{}' property 'DependsOn' list elements must be strings", name),
2344 dep_span,
2345 name,
2346 ));
2347 break;
2348 }
2349 }
2350 }
2351 _ => {
2352 let dep_span =
2353 span_index.get(&format!("Resources/{}/DependsOn", name)).copied().unwrap_or(resource_span);
2354 out.push(crate::make_parse_defect_for_resource(
2355 "E3001",
2356 format!("Resource '{}' property 'DependsOn' must be a string or list of strings", name),
2357 dep_span,
2358 name,
2359 ));
2360 }
2361 }
2362 }
2363
2364 let resource_type = entries.iter().find(|(key, _)| key == KEY_TYPE).and_then(|(_, value)| arena.as_str(*value));
2365 if let Some(resource_type) = resource_type {
2366 let is_custom_resource = is_custom_resource_type(resource_type);
2367 if let Some((_, version_ref)) = entries.iter().find(|(key, _)| key == "Version") {
2368 let version_span = span_index.get(&format!("Resources/{}/Version", name)).copied().unwrap_or(resource_span);
2369 if !is_custom_resource {
2370 out.push(crate::make_parse_defect_for_resource(
2371 "E3001",
2372 format!("Resource '{}' property 'Version' is only valid for custom resources", name),
2373 version_span,
2374 name,
2375 ));
2376 } else if !matches!(arena.node(*version_ref), Node::String(_) | Node::Int(_)) {
2377 out.push(crate::make_parse_defect_for_resource(
2378 "E3001",
2379 format!("Resource '{}' property 'Version' must be a string or integer", name),
2380 version_span,
2381 name,
2382 ));
2383 }
2384 }
2385
2386 for policy_name in [KEY_CREATION_POLICY, KEY_UPDATE_POLICY] {
2387 let Some((_, policy_ref)) = entries.iter().find(|(key, _)| key == policy_name) else {
2388 continue;
2389 };
2390 let policy_span =
2391 span_index.get(&format!("Resources/{}/{}", name, policy_name)).copied().unwrap_or(resource_span);
2392 if is_custom_resource {
2393 out.push(crate::make_parse_defect_for_resource(
2394 "E3001",
2395 format!("Resource '{}' property '{}' is not valid for custom resources", name, policy_name),
2396 policy_span,
2397 name,
2398 ));
2399 } else if !matches!(arena.node(*policy_ref), Node::Map(_) | Node::Intrinsic(_)) {
2400 out.push(crate::make_parse_defect_for_resource(
2401 "E3001",
2402 format!("Resource '{}' property '{}' must be an object", name, policy_name),
2403 policy_span,
2404 name,
2405 ));
2406 }
2407 }
2408 }
2409
2410 for (key, _) in entries {
2411 if VALID_RESOURCE_ATTRIBUTES.contains(&key.as_str()) {
2412 continue;
2413 }
2414 if is_sam && SAM_RESOURCE_ATTRIBUTES.contains(&key.as_str()) {
2415 continue;
2416 }
2417 let key_span = span_index.get(&format!("Resources/{}/{}", name, key)).copied().unwrap_or(resource_span);
2418 out.push(crate::make_parse_defect_for_resource(
2419 "E3001",
2420 format!(
2421 "Resource '{}' has invalid property '{}'. Valid resource attributes: {}",
2422 name,
2423 key,
2424 valid_attributes_display(is_sam),
2425 ),
2426 key_span,
2427 name,
2428 ));
2429 }
2430
2431 out
2432}
2433
2434fn valid_attributes_display(is_sam: bool) -> String {
2436 let mut attrs: Vec<&str> = VALID_RESOURCE_ATTRIBUTES.to_vec();
2437 if is_sam {
2438 attrs.extend_from_slice(SAM_RESOURCE_ATTRIBUTES);
2439 }
2440 attrs.join(", ")
2441}
2442
2443fn collect_lifecycle_attribute_status(
2444 arena: &Arena,
2445 node: NodeRef,
2446 conditions: &ConditionModel,
2447 allows_no_value_omission: bool,
2448 assumptions: &mut Vec<(String, bool)>,
2449 status: &mut LifecycleAttributeStatus,
2450) {
2451 if matches!(conditions.satisfiability(assumptions), Satisfiability::Unsatisfiable) {
2452 return;
2453 }
2454
2455 if !allows_no_value_omission {
2456 status.may_be_present = true;
2457 if matches!(
2458 arena.node(node),
2459 Node::Null | Node::Bool(_) | Node::Int(_) | Node::Float(_) | Node::String(_) | Node::List(_)
2460 ) && status.invalid_value.is_none()
2461 {
2462 status.invalid_value = Some(crate::message::render_value(&node_to_json(arena, node)));
2463 }
2464 return;
2465 }
2466
2467 match arena.node(node) {
2468 Node::Intrinsic(IntrinsicFn::Ref(target)) if target == PSEUDO_NO_VALUE => {}
2469 Node::Intrinsic(IntrinsicFn::If(condition, when_true, when_false)) => {
2470 assumptions.push((condition.clone(), true));
2471 collect_lifecycle_attribute_status(
2472 arena,
2473 *when_true,
2474 conditions,
2475 allows_no_value_omission,
2476 assumptions,
2477 status,
2478 );
2479 assumptions.pop();
2480 assumptions.push((condition.clone(), false));
2481 collect_lifecycle_attribute_status(
2482 arena,
2483 *when_false,
2484 conditions,
2485 allows_no_value_omission,
2486 assumptions,
2487 status,
2488 );
2489 assumptions.pop();
2490 }
2491 Node::Intrinsic(_) | Node::Map(_) => status.may_be_present = true,
2492 Node::Null | Node::Bool(_) | Node::Int(_) | Node::Float(_) | Node::String(_) | Node::List(_) => {
2493 status.may_be_present = true;
2494 if status.invalid_value.is_none() {
2495 status.invalid_value = Some(crate::message::render_value(&node_to_json(arena, node)));
2496 }
2497 }
2498 }
2499}
2500
2501fn resolve_resource(arena: &Arena, name: &str, node_ref: NodeRef, resolver: &mut Resolver) -> ResolvedResource {
2502 let entries = arena.as_map(node_ref).unwrap_or(&[]);
2503 let resource_type =
2504 entries.iter().find(|(k, _)| k == KEY_TYPE).and_then(|(_, v)| arena.as_str(*v)).unwrap_or("").to_string();
2505 let condition =
2506 entries.iter().find(|(k, _)| k == KEY_CONDITION).and_then(|(_, v)| arena.as_str(*v)).map(|s| s.to_string());
2507 let depends_on = entries
2508 .iter()
2509 .find(|(k, _)| k == KEY_DEPENDS_ON)
2510 .map(|(_, v)| match arena.node(*v) {
2511 Node::String(s) => vec![s.clone()],
2512 Node::List(items) => items.iter().filter_map(|r| arena.as_str(*r).map(|s| s.to_string())).collect(),
2513 _ => vec![],
2514 })
2515 .unwrap_or_default();
2516 let deletion_policy =
2517 entries.iter().find(|(k, _)| k == KEY_DELETION_POLICY).map(|(_, v)| resolver.resolve_node(*v));
2518 let update_replace_policy =
2519 entries.iter().find(|(k, _)| k == KEY_UPDATE_REPLACE_POLICY).map(|(_, v)| resolver.resolve_node(*v));
2520 let metadata_ref = entries.iter().find(|(k, _)| k == SECTION_METADATA).map(|(_, v)| *v);
2521 let metadata = metadata_ref.map(|v| node_to_json(arena, v));
2522 let update_policy = entries.iter().find(|(k, _)| k == KEY_UPDATE_POLICY).map(|(_, v)| node_to_json(arena, *v));
2523 let creation_policy = entries.iter().find(|(k, _)| k == KEY_CREATION_POLICY).map(|(_, v)| node_to_json(arena, *v));
2524
2525 let resolved_metadata = if let Some(meta_ref) = metadata_ref {
2526 resolver.set_current_path(SECTION_METADATA);
2527 Some(resolver.resolve_node(meta_ref))
2528 } else {
2529 None
2530 };
2531
2532 let mut properties = HashMap::new();
2533 let mut properties_dynamic = false;
2534 if let Some((_, props_ref)) = entries.iter().find(|(k, _)| k == KEY_PROPERTIES) {
2535 if let Some(prop_entries) = arena.as_map(*props_ref) {
2536 for (key, val_ref) in prop_entries {
2537 resolver.set_current_path(&format!("Properties.{}", key));
2538 properties.insert(key.clone(), resolver.resolve_node(*val_ref));
2539 }
2540 } else if let Some(synthetic_key) = intrinsic_synthetic_key(arena, *props_ref) {
2541 resolver.set_current_path(KEY_PROPERTIES);
2549 properties.insert(synthetic_key, resolver.resolve_node(*props_ref));
2550 } else if matches!(arena.node(*props_ref), Node::Intrinsic(_)) {
2551 properties_dynamic = true;
2555 }
2556 }
2557
2558 let mut conditionally_null_props = Vec::new();
2559 for (key, val) in &properties {
2560 collect_conditional_nulls(val, key, &mut conditionally_null_props);
2561 }
2562
2563 let mut condition_refs = Vec::new();
2564 for v in properties.values() {
2565 collect_condition_refs_from_resolved(v, &mut condition_refs);
2566 }
2567 if let Some(ref meta_resolved) = resolved_metadata {
2568 collect_condition_refs_from_resolved(meta_resolved, &mut condition_refs);
2569 }
2570 if let Some(ref dp) = deletion_policy {
2571 collect_condition_refs_from_resolved(dp, &mut condition_refs);
2572 }
2573 if let Some(ref urp) = update_replace_policy {
2574 collect_condition_refs_from_resolved(urp, &mut condition_refs);
2575 }
2576 if let Some(mut extra) = resolver.extra_condition_refs.remove(name) {
2577 condition_refs.append(&mut extra);
2578 }
2579 condition_refs.sort();
2580 condition_refs.dedup();
2581
2582 ResolvedResource {
2583 logical_id: name.to_string(),
2584 resource_type,
2585 condition,
2586 depends_on,
2587 deletion_policy,
2588 update_replace_policy,
2589 update_policy: update_policy.map(JsonValue),
2590 creation_policy: creation_policy.map(JsonValue),
2591 metadata: metadata.map(JsonValue),
2592 properties,
2593 properties_dynamic,
2594 diagnostics: ResourceDiagnostics {
2595 find_in_map_refs: resolver.find_in_map_refs.remove(name).unwrap_or_default(),
2596 simple_subs: resolver
2597 .simple_subs
2598 .remove(name)
2599 .unwrap_or_default()
2600 .into_iter()
2601 .map(|(a, b)| PathValuePair { path: a, value: b })
2602 .collect(),
2603 redundant_subs: resolver.redundant_subs.remove(name).unwrap_or_default(),
2604 empty_joins: resolver.empty_joins.remove(name).unwrap_or_default(),
2605 hardcoded_partition_arns: collapse_list_sibling_arn_paths(
2606 resolver.hardcoded_partition_arns.remove(name).unwrap_or_default(),
2607 ),
2608 foreach_expansions: resolver
2609 .foreach_expansions
2610 .remove(name)
2611 .unwrap_or_default()
2612 .into_iter()
2613 .map(|(path, ident, coll)| ForEachExpansion {
2614 property_path: path,
2615 identifier: ident,
2616 collection_source: coll,
2617 })
2618 .collect(),
2619 unsubstituted_variables: resolver
2620 .unsubstituted_variables
2621 .remove(name)
2622 .unwrap_or_default()
2623 .into_iter()
2624 .map(|(a, b)| PathValuePair { path: a, value: b })
2625 .collect(),
2626 unused_sub_keys: resolver
2627 .unused_sub_keys
2628 .remove(name)
2629 .unwrap_or_default()
2630 .into_iter()
2631 .map(|(a, b)| PathValuePair { path: a, value: b })
2632 .collect(),
2633 raw_pseudo_params: resolver
2634 .raw_pseudo_params
2635 .remove(name)
2636 .unwrap_or_default()
2637 .into_iter()
2638 .map(|(a, b)| PathValuePair { path: a, value: b })
2639 .collect(),
2640 secretsmanager_ref_paths: resolver.secretsmanager_ref_paths.remove(name).unwrap_or_default(),
2641 invalid_refs: resolver
2642 .invalid_refs
2643 .remove(name)
2644 .unwrap_or_default()
2645 .into_iter()
2646 .map(|(a, b)| PathValuePair { path: a, value: b })
2647 .collect(),
2648 conditionally_null_props: conditionally_null_props
2649 .into_iter()
2650 .map(|(a, b, c)| ConditionalNullEntry { path: a, condition: b, null_in_true_branch: c })
2651 .collect(),
2652 condition_refs,
2653 },
2654 }
2655}
2656
2657fn collapse_list_sibling_arn_paths(paths: Vec<String>) -> Vec<String> {
2666 let mut min_index: HashMap<String, usize> = HashMap::new();
2670 let mut ungrouped: Vec<String> = Vec::new();
2671 for path in &paths {
2672 match split_trailing_list_index(path) {
2673 Some((prefix, idx, suffix)) => {
2674 let key = format!("{}\u{0}{}", prefix, suffix);
2675 min_index.entry(key).and_modify(|m| *m = (*m).min(idx)).or_insert(idx);
2676 }
2677 None => ungrouped.push(path.clone()),
2678 }
2679 }
2680 let mut out = ungrouped;
2681 for (key, idx) in min_index {
2682 let (prefix, suffix) = key.split_once('\u{0}').unwrap_or((key.as_str(), ""));
2683 out.push(format!("{}{}.{}", prefix, idx, suffix));
2684 }
2685 out.sort();
2686 out
2687}
2688
2689fn split_trailing_list_index(path: &str) -> Option<(String, usize, String)> {
2692 let suffix = "Fn::Sub";
2693 let stem = path.strip_suffix(suffix)?.strip_suffix('.')?;
2694 let (head, last) = stem.rsplit_once('.')?;
2695 let idx: usize = last.parse().ok()?;
2696 Some((format!("{}.", head), idx, suffix.to_string()))
2697}
2698
2699fn check_output_value_is_string(arena: &Arena, value_ref: NodeRef, output_name: &str, resolver: &mut Resolver) {
2710 let build_path = format!("Outputs/{}/Value", output_name);
2711 check_output_value_node(arena, value_ref, output_name, &build_path, resolver);
2712}
2713
2714fn check_output_value_node(
2720 arena: &Arena,
2721 value_ref: NodeRef,
2722 output_name: &str,
2723 build_path: &str,
2724 resolver: &mut Resolver,
2725) {
2726 let span = arena.span(value_ref);
2727 match arena.node(value_ref) {
2728 Node::List(items) if !items.is_empty() => {
2729 resolver.diagnostics.push(crate::make_parse_defect_at(
2730 "F6101",
2731 format!("Output '{}' value must be a string, not a list", output_name),
2732 span,
2733 build_path,
2734 ));
2735 }
2736 Node::Map(entries) if !entries.is_empty() => {
2737 resolver.diagnostics.push(crate::make_parse_defect_at(
2738 "F6101",
2739 format!("Output '{}' value must be a string, not an object", output_name),
2740 span,
2741 build_path,
2742 ));
2743 }
2744 Node::Intrinsic(IntrinsicFn::If(_, if_true, if_false) | IntrinsicFn::IfExpr(_, if_true, if_false)) => {
2745 let (if_true, if_false) = (*if_true, *if_false);
2746 check_output_value_node(arena, if_true, output_name, &format!("{}/{}/1", build_path, FN_IF), resolver);
2747 check_output_value_node(arena, if_false, output_name, &format!("{}/{}/2", build_path, FN_IF), resolver);
2748 }
2749 Node::Intrinsic(intrinsic) if returns_list(intrinsic) => {
2750 resolver.diagnostics.push(crate::make_parse_defect_at(
2751 "F6101",
2752 format!("Output '{}' value must be a string, not a list", output_name),
2753 span,
2754 build_path,
2755 ));
2756 }
2757 _ => {}
2758 }
2759}
2760
2761fn returns_list(intrinsic: &IntrinsicFn) -> bool {
2766 matches!(intrinsic, IntrinsicFn::GetAZs(_) | IntrinsicFn::Split(_, _) | IntrinsicFn::Cidr(_, _, _))
2767}
2768
2769fn resolve_output(arena: &Arena, node_ref: NodeRef, resolver: &mut Resolver) -> ResolvedOutput {
2770 let entries = arena.as_map(node_ref).unwrap_or(&[]);
2771
2772 const VALID_OUTPUT_KEYS: &[&str] = &[KEY_VALUE, SECTION_DESCRIPTION, KEY_CONDITION, KEY_EXPORT];
2774 let output_name = resolver.current_resource.as_deref().unwrap_or("");
2775 let display_name = output_name.strip_prefix(OUTPUT_PSEUDO_RESOURCE_PREFIX).unwrap_or(output_name);
2776 for (key, _) in entries {
2777 if !VALID_OUTPUT_KEYS.contains(&key.as_str()) {
2778 resolver.diagnostics.push(crate::make_parse_defect(
2779 "E6001",
2780 format!(
2781 "Output '{}' has invalid property '{}'. Valid properties: Value, Description, Condition, Export",
2782 display_name, key
2783 ),
2784 crate::ir::UNKNOWN_SPAN,
2785 ));
2786 }
2787 }
2788
2789 if let Some((_, value_ref)) = entries.iter().find(|(k, _)| k == KEY_VALUE) {
2790 let value_ref = *value_ref;
2791 let name = display_name.to_string();
2792 check_output_value_is_string(arena, value_ref, &name, resolver);
2793 }
2794
2795 let value = entries
2796 .iter()
2797 .find(|(k, _)| k == KEY_VALUE)
2798 .map(|(_, v)| resolver.resolve_node(*v))
2799 .unwrap_or(ResolvedValue::Dynamic { reason: "missing output value".into() });
2800 let description = entries
2801 .iter()
2802 .find(|(k, _)| k == SECTION_DESCRIPTION)
2803 .and_then(|(_, v)| arena.as_str(*v))
2804 .map(|s| s.to_string());
2805 let condition =
2806 entries.iter().find(|(k, _)| k == KEY_CONDITION).and_then(|(_, v)| arena.as_str(*v)).map(|s| s.to_string());
2807 let export_name = entries
2808 .iter()
2809 .find(|(k, _)| k == KEY_EXPORT)
2810 .and_then(|(_, v)| arena.as_map(*v))
2811 .and_then(|m| m.iter().find(|(k, _)| k == KEY_NAME))
2812 .map(|(_, v)| resolver.resolve_node(*v));
2813 ResolvedOutput { value, description, condition, export_name }
2814}
2815
2816#[cfg(test)]
2817mod tests {
2818 use super::*;
2819
2820 #[test]
2821 fn invalid_overrides_reports_nothing_when_unset_or_valid() {
2822 assert!(PseudoParameterOverrides::default().invalid_overrides().is_empty(), "unset overrides are valid");
2823 let valid = PseudoParameterOverrides {
2824 account_id: Some("123456789012".to_string()),
2825 partition: Some("aws-cn".to_string()),
2826 ..Default::default()
2827 };
2828 assert!(valid.invalid_overrides().is_empty(), "well-formed overrides produce no warnings");
2829 }
2830
2831 #[test]
2832 fn invalid_overrides_reports_each_malformed_provided_value() {
2833 let bad = PseudoParameterOverrides {
2834 account_id: Some("unknown-account".to_string()),
2835 partition: Some("gcp".to_string()),
2836 ..Default::default()
2837 };
2838 let problems = bad.invalid_overrides();
2839 assert_eq!(problems.len(), 2, "one entry per invalid provided field");
2840 assert!(problems.iter().any(|p| p.contains("AccountId") && p.contains("unknown-account")));
2841 assert!(problems.iter().any(|p| p.contains("Partition") && p.contains("gcp")));
2842 }
2843
2844 #[test]
2845 fn invalid_overrides_only_checks_account_id_and_partition() {
2846 let only_region = PseudoParameterOverrides { region: Some("not a region".to_string()), ..Default::default() };
2847 assert!(only_region.invalid_overrides().is_empty());
2848 }
2849
2850 #[test]
2851 fn account_id_shape_requires_exactly_twelve_digits() {
2852 assert!(is_account_id_shaped("123456789012"));
2853 assert!(!is_account_id_shaped("12345678901"));
2854 assert!(!is_account_id_shaped("1234567890123"));
2855 assert!(!is_account_id_shaped("12345678901a"));
2856 assert!(!is_account_id_shaped(""));
2857 }
2858
2859 #[test]
2860 fn partition_shape_accepts_aws_family_and_rejects_others() {
2861 for ok in ["aws", "aws-cn", "aws-us-gov", "aws-iso", "aws-iso-b"] {
2862 assert!(is_partition_shaped(ok), "{ok} should be accepted");
2863 }
2864 for bad in ["gcp", "AWS", "azure", ""] {
2865 assert!(!is_partition_shaped(bad), "{bad} should be rejected");
2866 }
2867 }
2868
2869 #[test]
2870 fn model_from_simple_template() {
2871 let input = r#"
2872AWSTemplateFormatVersion: "2010-09-09"
2873Resources:
2874 MyBucket:
2875 Type: AWS::S3::Bucket
2876 Properties:
2877 BucketName: my-bucket
2878 MyBucket2:
2879 Type: AWS::S3::Bucket
2880 Properties:
2881 BucketName: my-bucket-2
2882"#;
2883 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
2884 assert_eq!(model.resources.len(), 2);
2885 assert_eq!(model.resources_of_type("AWS::S3::Bucket").len(), 2);
2886 assert_eq!(model.resources_of_type("AWS::Fake::Thing").len(), 0);
2887 }
2888
2889 fn intrinsic_source_probe_model() -> SemanticModel {
2895 let input = r#"
2896Resources:
2897 Other:
2898 Type: AWS::S3::Bucket
2899 Properties:
2900 BucketName: other-bucket
2901 R:
2902 Type: AWS::SNS::Topic
2903 Properties:
2904 LiteralProp: plain-literal
2905 RefProp: !Ref Other
2906 GetAttProp: !GetAtt Other.Arn
2907 JoinProp: !Join ["-", ["a", "b"]]
2908 NestedRef:
2909 Inner: !Ref Other
2910 IfR:
2911 Type: AWS::SNS::Topic
2912 Condition: MakeIt
2913 Properties:
2914 Fn::If:
2915 - MakeIt
2916 - TopicName: !Ref Other
2917 DisplayName: literal-in-true-branch
2918 BranchLiteral: literal-one
2919 - TopicName: plain-literal-two
2920 DisplayName: !Ref Other
2921 BranchLiteral: literal-two
2922Conditions:
2923 MakeIt: !Equals ["a", "a"]
2924"#;
2925 SemanticModel::from_bytes(input.as_bytes()).unwrap()
2926 }
2927
2928 #[test]
2929 fn is_from_intrinsic_separates_intrinsic_values_from_literals() {
2930 let model = intrinsic_source_probe_model();
2931 assert!(model.is_from_intrinsic("R", "Properties.RefProp"), "a Ref value is intrinsic-sourced");
2932 assert!(model.is_from_intrinsic("R", "Properties.GetAttProp"), "a GetAtt value is intrinsic-sourced");
2933 assert!(
2934 model.is_from_intrinsic("R", "Properties.JoinProp"),
2935 "an Fn::Join value keeps its Intrinsic/* source even when it resolves concretely"
2936 );
2937 assert!(!model.is_from_intrinsic("R", "Properties.LiteralProp"), "a plain literal is not intrinsic-sourced");
2938 }
2939
2940 #[test]
2941 fn is_from_intrinsic_inherits_from_intrinsic_ancestors() {
2942 let model = intrinsic_source_probe_model();
2943 assert!(model.is_from_intrinsic("R", "Properties.NestedRef.Inner"));
2946 assert!(model.is_from_intrinsic("R", "Properties.NestedRef.Inner.Deeper"));
2947 assert!(!model.is_from_intrinsic("R", "Properties.NestedRef"));
2949 assert!(!model.is_from_intrinsic("Missing", "Properties.Anything"));
2951 }
2952
2953 #[test]
2954 fn is_from_intrinsic_attributes_fn_if_branch_sources_to_the_bare_path() {
2955 let model = intrinsic_source_probe_model();
2956 assert!(model.is_from_intrinsic("IfR", "Properties.TopicName"));
2959 assert!(model.is_from_intrinsic("IfR", "Properties.DisplayName"));
2961 assert!(!model.is_from_intrinsic("IfR", "Properties.BranchLiteral"));
2963 }
2964
2965 #[test]
2966 fn diagnostic_span_resolves_dotted_resource_property_path() {
2967 let input = r#"
2968Resources:
2969 MyBucket:
2970 Type: AWS::S3::Bucket
2971 Properties:
2972 BucketName: my-bucket
2973"#;
2974 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
2975 let via_diag = model.diagnostic_span(Some("MyBucket"), "Properties.BucketName").expect("should resolve");
2978 let expected = model.source_location("Resources/MyBucket/Properties/BucketName").copied().expect("indexed");
2979 assert_eq!(via_diag, expected, "dotted path should resolve to the exact property span");
2980 }
2981
2982 #[test]
2983 fn diagnostic_span_resolves_bare_top_level_path_without_resource() {
2984 let input = r#"
2985BogusSection:
2986 Value: invalid
2987Resources:
2988 MyBucket:
2989 Type: AWS::S3::Bucket
2990"#;
2991 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
2992 let via_diag = model.diagnostic_span(None, "BogusSection").expect("should resolve");
2993 let expected = model.source_location("BogusSection").copied().expect("indexed");
2994 assert_eq!(via_diag, expected, "bare top-level path should resolve to its authored key");
2995 }
2996
2997 #[test]
2998 fn diagnostic_span_resource_relative_path_never_matches_top_level_section() {
2999 let input = r#"
3002Metadata:
3003 AWS::CloudFormation::Interface:
3004 ParameterGroups: []
3005Resources:
3006 MyBucket:
3007 Type: AWS::S3::Bucket
3008 Metadata:
3009 cfn_nag: skip
3010"#;
3011 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3012 let via_diag = model.diagnostic_span(Some("MyBucket"), "Metadata").expect("should resolve");
3013 let resource_meta = model.source_location("Resources/MyBucket/Metadata").copied().expect("indexed");
3014 let top_level_meta = model.source_location("Metadata").copied().expect("indexed");
3015 assert_eq!(via_diag, resource_meta, "resource-relative Metadata must anchor at the resource");
3016 assert_ne!(via_diag, top_level_meta, "must not mislocate onto the top-level Metadata section");
3017 }
3018
3019 #[test]
3020 fn diagnostic_span_resolves_absolute_section_rooted_path() {
3021 let input = r#"
3022Resources:
3023 MyBucket:
3024 Type: AWS::S3::Bucket
3025Outputs:
3026 BucketRef:
3027 Value: !Ref MyBucket
3028"#;
3029 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3030 let span = model.diagnostic_span(Some("BucketRef"), "Outputs/BucketRef/Value");
3033 assert!(span.is_some() && span != Some(UNKNOWN_SPAN), "output path should resolve to a real span");
3034 }
3035
3036 #[test]
3037 fn diagnostic_span_walks_up_when_leaf_node_is_unindexed() {
3038 let input = r#"
3039Resources:
3040 MyBucket:
3041 Type: AWS::S3::Bucket
3042 Properties:
3043 BucketName: my-bucket
3044"#;
3045 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3046 let span = model.diagnostic_span(Some("MyBucket"), "Properties.BucketName.DoesNotExist.Deeper");
3049 assert!(span.is_some() && span != Some(UNKNOWN_SPAN), "unindexed leaf should walk up to a real span");
3050 }
3051
3052 #[test]
3053 fn diagnostic_span_returns_none_when_nothing_resolvable() {
3054 let input = r#"
3055Resources:
3056 MyBucket:
3057 Type: AWS::S3::Bucket
3058"#;
3059 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3060 assert_eq!(model.diagnostic_span(None, ""), None, "no resource and no path yields no span");
3062 assert_eq!(
3065 model.diagnostic_span(None, "NoSuchSection/Deep/Path"),
3066 None,
3067 "an unindexed absolute path yields no span"
3068 );
3069 }
3070
3071 #[test]
3072 fn model_resolve_property() {
3073 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"Name":"hello"}}}}"#;
3074 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3075 match model.resolve("R", "Properties.Name").unwrap() {
3076 ResolvedValue::Concrete { value: v } => assert_eq!(v.as_str().unwrap(), "hello"),
3077 other => panic!("Expected Concrete, got {:?}", other),
3078 }
3079 }
3080
3081 #[test]
3082 fn model_follow_ref() {
3083 let input = r#"{"Resources":{"Svc":{"Type":"T","Properties":{"TaskDef":{"Ref":"TD"}}},"TD":{"Type":"T2"}}}"#;
3084 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3085 assert_eq!(model.follow_ref("Svc", "Properties.TaskDef"), Some("TD"));
3086 }
3087
3088 #[test]
3089 fn model_to_diagnostic_json() {
3090 let input = r#"{"Resources":{"R":{"Type":"AWS::S3::Bucket","Properties":{"Name":"test"}}}}"#;
3091 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3092 let json = serde_json::to_value(model.to_diagnostic_json()).unwrap();
3093 assert_ne!(json.get("resources"), None, "expected 'resources' key in diagnostic JSON");
3094 assert_ne!(json["resources"].get("R"), None, "expected resource 'R' in diagnostic JSON");
3095 }
3096
3097 #[test]
3098 fn model_send_sync() {
3099 fn assert_send_sync<T: Send + Sync>() {}
3100 assert_send_sync::<SemanticModel>();
3101 }
3102
3103 #[test]
3104 fn model_with_conditions() {
3105 let input = r#"
3106Parameters:
3107 Env:
3108 Type: String
3109 AllowedValues: [Prod, Dev]
3110Conditions:
3111 IsProd:
3112 Fn::Equals: [!Ref Env, Prod]
3113Resources:
3114 R:
3115 Type: T
3116 Condition: IsProd
3117 Properties:
3118 Size:
3119 Fn::If: [IsProd, 100, 20]
3120"#;
3121 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3122 assert_eq!(model.conditions.conditions.len(), 1);
3123 let r = model.resource("R").unwrap();
3124 assert_eq!(r.condition.as_deref(), Some("IsProd"));
3125 assert!(matches!(
3126 r.properties.get("Size"),
3127 Some(ResolvedValue::Conditional { condition: _, if_true: _, if_false: _ })
3128 ));
3129 }
3130
3131 #[test]
3132 fn model_with_outputs() {
3133 let input =
3134 "Resources:\n R:\n Type: T\nOutputs:\n Out1:\n Value: !Ref R\n Description: test output\n";
3135 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3136 assert_eq!(model.outputs.len(), 1);
3137 assert!(model.outputs.contains_key("Out1"));
3138 }
3139
3140 #[test]
3141 fn resolve_deep_nested_object() {
3142 let input =
3143 r#"{"Resources":{"R":{"Type":"T","Properties":{"Config":{"SubKey":"value","Nested":{"Deep":"found"}}}}}}"#;
3144 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3145 match model.resolve_deep("R", "Properties.Config.SubKey") {
3146 Some(ResolvedValue::Concrete { value: v }) => assert_eq!(v.as_str().unwrap(), "value"),
3147 other => panic!("Expected Concrete, got {:?}", other),
3148 }
3149 match model.resolve_deep("R", "Properties.Config.Nested.Deep") {
3150 Some(ResolvedValue::Concrete { value: v }) => assert_eq!(v.as_str().unwrap(), "found"),
3151 other => panic!("Expected Concrete, got {:?}", other),
3152 }
3153 }
3154
3155 #[test]
3156 fn resolve_deep_array_index() {
3157 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"Tags":[{"Key":"Env","Value":"prod"},{"Key":"App","Value":"web"}]}}}}"#;
3158 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3159 match model.resolve_deep("R", "Properties.Tags.0.Key") {
3160 Some(ResolvedValue::Concrete { value: v }) => assert_eq!(v.as_str().unwrap(), "Env"),
3161 other => panic!("Expected Concrete, got {:?}", other),
3162 }
3163 }
3164
3165 #[test]
3166 fn resolve_deep_out_of_bounds() {
3167 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"Tags":[{"Key":"A"}]}}}}"#;
3168 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3169 assert!(model.resolve_deep("R", "Properties.Tags.5.Key").is_none(), "out-of-bounds index should return None");
3170 }
3171
3172 #[test]
3173 fn resolve_deep_missing_intermediate() {
3174 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"Name":"hello"}}}}"#;
3175 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3176 assert!(model.resolve_deep("R", "Properties.NonExistent.Sub").is_none());
3177 }
3178
3179 #[test]
3180 fn resolve_deep_top_level_still_works() {
3181 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"Name":"hello"}}}}"#;
3182 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3183 match model.resolve_deep("R", "Properties.Name") {
3184 Some(ResolvedValue::Concrete { value: v }) => assert_eq!(v.as_str().unwrap(), "hello"),
3185 other => panic!("Expected Concrete, got {:?}", other),
3186 }
3187 }
3188
3189 #[test]
3190 fn model_findinmap_refs_tracked() {
3191 let input = br#"{"Resources":{"R":{"Type":"T","Properties":{"V":{"Fn::FindInMap":["MyMap","k1","k2"]}}}}}"#;
3192 let model = SemanticModel::from_bytes(input).unwrap();
3193 assert!(model.resource("R").unwrap().diagnostics.find_in_map_refs.contains(&"MyMap".to_string()));
3194 }
3195
3196 #[test]
3197 fn model_findinmap_refs_tracked_yaml() {
3198 let input = b"Resources:\n R:\n Type: T\n Properties:\n V: !FindInMap [MyMap, k1, k2]\n";
3199 let model = SemanticModel::from_bytes(input).unwrap();
3200 assert!(model.resource("R").unwrap().diagnostics.find_in_map_refs.contains(&"MyMap".to_string()));
3201 }
3202
3203 #[test]
3204 fn model_to_diagnostic_json_has_outputs_and_mappings() {
3205 let input = b"AWSTemplateFormatVersion: '2010-09-09'\nMappings:\n M:\n k1:\n k2: val\nResources:\n R:\n Type: AWS::S3::Bucket\nOutputs:\n Out:\n Value: !Ref R\n";
3206 let model = SemanticModel::from_bytes(input).unwrap();
3207 let json = serde_json::to_value(model.to_diagnostic_json()).unwrap();
3208 assert_ne!(json.get("outputs"), None, "expected 'outputs' key in diagnostic JSON");
3209 assert_ne!(json.get("mappings"), None, "expected 'mappings' key in diagnostic JSON");
3210 assert_eq!(json["mappings"]["M"]["k1"]["k2"], "val");
3211 }
3212
3213 #[test]
3214 fn resolve_deep_into_reference() {
3215 let input = r#"{"Resources":{"Svc":{"Type":"T","Properties":{"TaskDef":{"Ref":"TD"}}},"TD":{"Type":"T2"}}}"#;
3216 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3217 assert!(
3218 model.resolve_deep("Svc", "Properties.TaskDef.Something").is_none(),
3219 "path through Reference should return None"
3220 );
3221 match model.resolve_deep("Svc", "Properties.TaskDef") {
3222 Some(ResolvedValue::Reference { target, kind: _ }) => assert_eq!(target, "TD"),
3223 other => panic!("Expected Reference, got {:?}", other),
3224 }
3225 }
3226
3227 #[test]
3228 fn scenario_source_path_maps_effective_indexes_to_authored_branches() {
3229 let input = br#"{
3230 "Parameters": {"Mode": {"Type": "String"}},
3231 "Conditions": {"ChooseFirst": {"Fn::Equals": [{"Ref": "Mode"}, "first"]}},
3232 "Resources": {"R": {"Type": "T", "Properties": {
3233 "Values": {"Fn::If": ["ChooseFirst", ["bad"], ["good"]]}
3234 }}}
3235 }"#;
3236 let model = SemanticModel::from_bytes(input).unwrap();
3237 let true_conditions = HashMap::from([("ChooseFirst".to_string(), true)]);
3238 let false_conditions = HashMap::from([("ChooseFirst".to_string(), false)]);
3239 assert_eq!(
3240 model.scenario_source_path("R", "Properties.Values.0", &true_conditions),
3241 Some("Properties.Values.Fn::If.1.0".to_string())
3242 );
3243 assert_eq!(
3244 model.scenario_source_path("R", "Properties.Values.0", &false_conditions),
3245 Some("Properties.Values.Fn::If.2.0".to_string())
3246 );
3247 }
3248
3249 #[test]
3250 fn resolve_scenarios_json_filters_dynamic() {
3251 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":{"Fn::ImportValue":"Stack"}}}}}"#;
3252 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3253 let scenarios = model.resolve_scenarios_json("R", "Properties.V");
3254 assert!(scenarios.is_empty(), "ImportValue should be filtered as dynamic");
3255 }
3256
3257 #[test]
3258 fn resolve_scenarios_json_returns_concrete() {
3259 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"hello"}}}}"#;
3260 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3261 let scenarios = model.resolve_scenarios_json("R", "Properties.V");
3262 assert_eq!(scenarios.len(), 1);
3263 assert_eq!(scenarios[0].0, serde_json::json!("hello"));
3264 }
3265
3266 #[test]
3267 fn resolve_scenarios_json_memoized() {
3268 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"hello"}}}}"#;
3269 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3270 let s1 = model.resolve_scenarios_json("R", "Properties.V");
3271 let s2 = model.resolve_scenarios_json("R", "Properties.V");
3272 assert_eq!(s1, s2);
3273 }
3274
3275 #[test]
3276 fn resolve_scenarios_json_shared_reuses_allocation_and_matches_owned() {
3277 let input = br#"{
3278 "Parameters": {"Mode": {"Type": "String"}},
3279 "Conditions": {"ChooseFirst": {"Fn::Equals": [{"Ref": "Mode"}, "first"]}},
3280 "Resources": {"R": {"Type": "T", "Properties": {
3281 "V": {"Fn::If": ["ChooseFirst", "a", "b"]}
3282 }}}
3283 }"#;
3284 let model = SemanticModel::from_bytes(input).unwrap();
3285
3286 let first = model.resolve_scenarios_json_shared("R", "Properties.V");
3287 let combinations_after_first = model.scenario_combinations_used();
3288 let second = model.resolve_scenarios_json_shared("R", "Properties.V");
3289 let owned = model.resolve_scenarios_json("R", "Properties.V");
3290
3291 assert!(Arc::ptr_eq(&first, &second));
3292 assert_eq!(first.as_ref(), owned.as_slice());
3293 assert!(combinations_after_first > 0);
3294 assert_eq!(model.scenario_combinations_used(), combinations_after_first);
3295 }
3296
3297 #[test]
3298 fn resolve_properties_scenarios_shared_reuses_allocation_and_matches_owned() {
3299 let input = br#"{
3300 "Parameters": {"Mode": {"Type": "String"}},
3301 "Conditions": {"ChooseFirst": {"Fn::Equals": [{"Ref": "Mode"}, "first"]}},
3302 "Resources": {"R": {"Type": "T", "Properties": {
3303 "V": {"Fn::If": ["ChooseFirst", "a", "b"]}
3304 }}}
3305 }"#;
3306 let model = SemanticModel::from_bytes(input).unwrap();
3307
3308 let first = model.resolve_properties_scenarios_shared("R");
3309 let combinations_after_first = model.scenario_combinations_used();
3310 let second = model.resolve_properties_scenarios_shared("R");
3311 let owned = model.resolve_properties_scenarios("R");
3312
3313 assert!(Arc::ptr_eq(&first, &second), "repeated shared access must reuse one allocation");
3314 assert!(first.len() > 1, "the Fn::If value must expand the whole-properties object into multiple scenarios");
3315 assert_eq!(
3316 serde_json::to_value(first.as_ref()).expect("shared scenarios serialize"),
3317 serde_json::to_value(&owned).expect("owned scenarios serialize"),
3318 "the owned API must return the same scenarios as the shared accessor"
3319 );
3320 assert_eq!(
3321 model.scenario_combinations_used(),
3322 combinations_after_first,
3323 "a cached shared access must not consume additional scenario budget"
3324 );
3325 }
3326
3327 #[test]
3328 fn default_scenario_queries_are_memoized_and_global_budget_halts_uncached_expansion() {
3329 let input = br#"{
3330 "Parameters": {"Env": {"Type": "String"}},
3331 "Conditions": {"IsProd": {"Fn::Equals": [{"Ref": "Env"}, "prod"]}},
3332 "Resources": {"R": {"Type": "T", "Properties": {
3333 "V": {"Fn::If": ["IsProd", "a", "b"]},
3334 "W": {"Fn::If": ["IsProd", "c", "d"]},
3335 "X": {"Fn::If": ["IsProd", "e", "f"]}
3336 }}}
3337 }"#;
3338 let model = SemanticModel::from_bytes(input).unwrap();
3339
3340 assert_eq!(model.scenario_combinations_used(), 0, "a freshly built model has materialized no scenarios");
3341 assert!(!model.scenario_budget_exhausted());
3342
3343 let first = model.resolve_scenarios("R", "Properties.V");
3344 assert!(first.len() > 1, "an Fn::If value must expand into multiple scenarios; got {}", first.len());
3345 let after_first = model.scenario_combinations_used();
3346 assert_eq!(after_first, first.len() as u64, "the first query charges exactly the scenarios it produced");
3347
3348 let repeated = model.resolve_scenarios("R", "Properties.V");
3349 assert_eq!(repeated.len(), first.len());
3350 assert_eq!(
3351 model.scenario_combinations_used(),
3352 after_first,
3353 "a repeated default-limit query must reuse its raw scenarios without consuming budget"
3354 );
3355
3356 let distinct = model.resolve_scenarios("R", "Properties.W");
3357 assert!(!distinct.is_empty());
3358 assert!(
3359 model.scenario_combinations_used() > after_first,
3360 "a distinct scenario path must still charge the model-wide budget"
3361 );
3362
3363 let to_threshold = MAX_TOTAL_SCENARIO_COMBINATIONS - model.scenario_combinations_used();
3364 model.add_scenario_combinations_for_test(to_threshold);
3365 assert!(model.scenario_budget_exhausted());
3366
3367 let cached = model.resolve_scenarios("R", "Properties.V");
3368 assert_eq!(
3369 cached.len(),
3370 first.len(),
3371 "cached scenarios remain usable after unrelated queries consume the budget"
3372 );
3373 assert!(!model.scenario_expansion_curtailed(), "reading a cached result does not curtail expansion");
3374
3375 let before_short_circuit = model.scenario_combinations_used();
3376 let curtailed = model.resolve_scenarios("R", "Properties.X");
3377 assert!(curtailed.is_empty(), "an uncached query must stop when the model-wide budget is exhausted");
3378 assert_eq!(model.scenario_combinations_used(), before_short_circuit);
3379 assert!(model.scenario_expansion_curtailed());
3380 }
3381
3382 fn two_scenario_value() -> ResolvedValue {
3383 ResolvedValue::Conditional {
3384 condition: "C".to_string(),
3385 if_true: Box::new(ResolvedValue::Concrete { value: serde_json::json!("yes").into() }),
3386 if_false: Box::new(ResolvedValue::Concrete { value: serde_json::json!("no").into() }),
3387 }
3388 }
3389
3390 #[test]
3391 fn exact_remaining_scenario_budget_does_not_mark_curtailment() {
3392 let model = SemanticModel::from_bytes(br#"{"Resources":{"R":{"Type":"T"}}}"#).unwrap();
3393 let scenarios = model.collect_scenarios_with_budget(&two_scenario_value(), 8, 2);
3394 assert_eq!(scenarios.len(), 2);
3395 assert_eq!(model.scenario_combinations_used(), 2);
3396 assert!(
3397 !model.scenario_expansion_curtailed(),
3398 "materializing exactly every possible scenario at the budget boundary is not curtailment"
3399 );
3400 }
3401
3402 #[test]
3403 fn remaining_scenario_budget_truncates_and_marks_curtailment() {
3404 let model = SemanticModel::from_bytes(br#"{"Resources":{"R":{"Type":"T"}}}"#).unwrap();
3405 let first = model.collect_scenarios_with_budget(&two_scenario_value(), 8, 3);
3406 assert_eq!(first.len(), 2);
3407 assert!(!model.scenario_expansion_curtailed());
3408
3409 let second = model.collect_scenarios_with_budget(&two_scenario_value(), 8, 3);
3410 assert_eq!(second.len(), 1, "only the one remaining global slot may be used");
3411 assert_eq!(model.scenario_combinations_used(), 3);
3412 assert!(model.scenario_expansion_curtailed());
3413
3414 let exhausted = model.collect_scenarios_with_budget(&two_scenario_value(), 8, 3);
3415 assert!(exhausted.is_empty());
3416 assert_eq!(model.scenario_combinations_used(), 3, "the global limit must never be exceeded");
3417 }
3418
3419 #[test]
3420 fn concurrent_scenario_queries_cannot_exceed_global_budget() {
3421 let model = std::sync::Arc::new(SemanticModel::from_bytes(br#"{"Resources":{"R":{"Type":"T"}}}"#).unwrap());
3422 let handles: Vec<_> = (0..8)
3423 .map(|_| {
3424 let model = std::sync::Arc::clone(&model);
3425 std::thread::spawn(move || {
3426 let value = ResolvedValue::Concrete { value: serde_json::json!("value").into() };
3427 model.collect_scenarios_with_budget(&value, 8, 4).len()
3428 })
3429 })
3430 .collect();
3431 let produced: usize =
3432 handles.into_iter().map(|handle| handle.join().expect("scenario worker must not panic")).sum();
3433
3434 assert_eq!(produced, 4, "exactly the global budget may be materialized across all workers");
3435 assert_eq!(model.scenario_combinations_used(), 4, "concurrent accounting must not overshoot the limit");
3436 assert!(model.scenario_expansion_curtailed(), "workers denied by exhaustion must mark curtailment");
3437 }
3438
3439 #[test]
3440 fn scenario_expansion_curtailment_flag_starts_false() {
3441 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"literal"}}}}"#;
3442 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3443 assert!(
3444 !model.scenario_expansion_curtailed(),
3445 "a freshly built model must not have scenario expansion curtailed"
3446 );
3447 }
3448
3449 #[test]
3450 fn scenario_expansion_curtailment_flag_set_by_test_helper() {
3451 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"literal"}}}}"#;
3452 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3453 model.set_scenario_expansion_curtailed_for_test();
3454 assert!(model.scenario_expansion_curtailed(), "the test helper must set the curtailment flag");
3455 }
3456
3457 #[test]
3458 fn scenario_expansion_curtailment_flag_is_monotonic() {
3459 let input = r#"{
3462 "Resources": {"R": {"Type": "T", "Properties": {"V": {"Fn::If": ["C", "a", "b"]}}}}
3463 }"#;
3464 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3465 model.set_scenario_expansion_curtailed_for_test();
3466 let _ = model.resolve_scenarios("R", "Properties.V");
3468 assert!(model.scenario_expansion_curtailed(), "the curtailment flag must be monotonic — once set it stays set");
3469 }
3470
3471 #[test]
3472 fn estimated_bounds_are_absent_for_a_literal_string() {
3473 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"hello"}}}}"#;
3476 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3477 assert_eq!(model.estimated_string_length_bounds("R", "Properties.V"), None);
3478 }
3479
3480 #[test]
3481 fn estimated_bounds_span_every_allowed_value() {
3482 let input = r#"{"Parameters":{"Size":{"Type":"String","AllowedValues":["xs","large"]}},
3483 "Resources":{"R":{"Type":"T","Properties":{"V":{"Ref":"Size"}}}}}"#;
3484 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3485 assert_eq!(model.estimated_string_length_bounds("R", "Properties.V"), Some((2, 5)));
3486 }
3487
3488 #[test]
3489 fn estimated_bounds_are_absent_when_a_possibility_is_unknown() {
3490 let input = r#"{"Parameters":{"Free":{"Type":"String"}},
3491 "Resources":{"R":{"Type":"T","Properties":{"V":{"Ref":"Free"}}}}}"#;
3492 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3493 assert_eq!(model.estimated_string_length_bounds("R", "Properties.V"), None);
3494 }
3495
3496 #[test]
3497 fn estimate_string_length_missing_property() {
3498 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"hello"}}}}"#;
3499 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3500 assert!(model.estimated_string_length_bounds("R", "Properties.Missing").is_none());
3501 }
3502
3503 #[test]
3504 fn resource_span_specific_path() {
3505 let input = "Resources:\n R:\n Type: T\n Properties:\n Name: hello\n";
3506 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3507 let span = model.resource_span("R", "Properties/Name");
3508 assert!(span.start_line > 0 || span.end_line > 0, "expected non-zero span for Properties/Name");
3510 }
3511
3512 #[test]
3513 fn resource_span_specific_path_dotted_form() {
3514 let input = "Resources:\n R:\n Type: T\n Properties:\n Name: hello\n";
3515 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3516 let dotted = model.resource_span("R", "Properties.Name");
3519 let slashed = model.resource_span("R", "Properties/Name");
3520 let resource = model.resource_span("R", "");
3521 assert_eq!(dotted, slashed, "dotted and slash forms must resolve to the same span");
3522 assert_ne!(dotted, resource, "specific property span must differ from the resource span");
3523 }
3524
3525 #[test]
3526 fn resource_span_falls_back_to_resource() {
3527 let input = "Resources:\n R:\n Type: T\n Properties:\n Name: hello\n";
3528 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3529 let span = model.resource_span("R", "Properties/NonExistent/Deep");
3530 assert!(span.start_line > 0 || span.end_line > 0, "expected non-zero span, got {:?}", span);
3532 }
3533
3534 #[test]
3535 fn resource_span_nested_array_property_anchors_at_element() {
3536 let input =
3539 "Resources:\n R:\n Type: T\n Properties:\n Ingress:\n - Port: 80\n - Port: 443\n";
3540 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3541 let first = model.resource_span("R", "Properties.Ingress.0.Port");
3542 let second = model.resource_span("R", "Properties.Ingress.1.Port");
3543 assert_eq!(first.start_line, 6, "Ingress[0].Port is on line 6, got {:?}", first);
3544 assert_eq!(second.start_line, 7, "Ingress[1].Port is on line 7, got {:?}", second);
3545 }
3546
3547 #[test]
3548 fn resource_span_empty_id_resolves_section_absolute_path_precisely() {
3549 let input = concat!(
3554 "Resources:\n R:\n Type: T\n", "Outputs:\n Combined:\n Value: !Join [\"\", [\"a\", \"b\"]]\n", );
3557 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3558 let value = model.resource_span("", "Outputs/Combined/Value");
3560 assert_eq!(value.start_line, 6, "Outputs/Combined/Value is on line 6, got {:?}", value);
3561 let combined = model.resource_span("", "Outputs/Combined");
3563 assert_eq!(combined.start_line, 5, "Outputs/Combined is on line 5, got {:?}", combined);
3564 }
3565
3566 #[test]
3567 fn resource_span_empty_id_fused_intrinsic_suffix_anchors_at_nearest_slash_ancestor() {
3568 let input = concat!(
3577 "Resources:\n R:\n Type: T\n", "Outputs:\n Combined:\n Value: !Join [\"\", [\"a\", \"b\"]]\n", );
3580 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3581 let span = model.resource_span("", "Outputs/Combined/Value.Fn::Join");
3582 assert_eq!(
3583 span.start_line, 5,
3584 "fused-suffix path must anchor at the enclosing output (line 5), got {:?}",
3585 span
3586 );
3587 }
3588
3589 #[test]
3590 fn resource_span_empty_id_does_not_leak_onto_resources_block() {
3591 let input = "Resources:\n R:\n Type: T\n";
3595 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3596 let span = model.resource_span("", "Outputs/DoesNotExist/Value");
3597 assert_eq!(span, UNKNOWN_SPAN, "unresolvable empty-id path must be UNKNOWN, got {:?}", span);
3598 }
3599
3600 #[test]
3601 fn resource_span_empty_path_returns_resource_span() {
3602 let input = "Resources:\n R:\n Type: T\n";
3603 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3604 let span = model.resource_span("R", "");
3605 assert!(span.start_line > 0 || span.end_line > 0, "expected non-zero span, got {:?}", span);
3606 }
3607
3608 #[test]
3609 fn resolve_nonexistent_resource_returns_none() {
3610 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"x"}}}}"#;
3611 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3612 assert!(model.resolve("NoSuchResource", "Properties.V").is_none(), "nonexistent resource should return None");
3613 assert!(model.resolve_deep("NoSuchResource", "Properties.V").is_none());
3614 }
3615
3616 #[test]
3617 fn parse_config_with_parameter_overrides() {
3618 let input = r#"{"Parameters":{"Env":{"Type":"String","AllowedValues":["dev","prod"]}},"Resources":{"R":{"Type":"T","Properties":{"V":{"Ref":"Env"}}}}}"#;
3619 let config = ParseConfig {
3620 parameters: [("Env".to_string(), "staging".to_string())].into_iter().collect(),
3621 pseudo_parameters: PseudoParameterOverrides::default(),
3622 };
3623 let result = SemanticModel::parse(input.as_bytes(), config).unwrap();
3624 match result.model.resolve("R", "Properties.V") {
3625 Some(ResolvedValue::Concrete { value: v }) => {
3626 assert_eq!(v.as_str().unwrap(), "staging")
3627 }
3628 other => panic!("Expected Concrete(\"staging\"), got {:?}", other),
3629 }
3630 }
3631
3632 #[test]
3633 fn parse_config_with_pseudo_parameter_overrides() {
3634 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":{"Ref":"AWS::Region"}}}}}"#;
3635 let config = ParseConfig {
3636 parameters: HashMap::new(),
3637 pseudo_parameters: PseudoParameterOverrides { region: Some("eu-west-1".to_string()), ..Default::default() },
3638 };
3639 let result = SemanticModel::parse(input.as_bytes(), config).unwrap();
3640 match result.model.resolve("R", "Properties.V") {
3641 Some(ResolvedValue::Concrete { value: v }) => {
3642 assert_eq!(v.as_str().unwrap(), "eu-west-1")
3643 }
3644 other => panic!("Expected Concrete(\"eu-west-1\"), got {:?}", other),
3645 }
3646 }
3647
3648 #[test]
3649 fn pseudo_parameter_overrides_defaults() {
3650 let overrides = PseudoParameterOverrides::default();
3651 assert_eq!(overrides.region(), DEFAULT_REGION);
3652 assert_eq!(overrides.get("AWS::AccountId").unwrap(), DEFAULT_ACCOUNT_ID);
3653 assert_eq!(overrides.get("AWS::Partition").unwrap(), DEFAULT_PARTITION);
3654 assert_eq!(overrides.get("AWS::StackName").unwrap(), DEFAULT_STACK_NAME);
3655 assert_eq!(overrides.get("AWS::URLSuffix").unwrap(), DEFAULT_URL_SUFFIX);
3656 assert!(overrides.get("AWS::StackId").unwrap().contains("arn:"));
3657 assert!(overrides.get("AWS::NotificationARNs").unwrap().contains("sns"));
3658 assert_eq!(overrides.get("Unknown"), None, "unknown pseudo-param should return None");
3659 }
3660
3661 #[test]
3662 fn pseudo_parameter_overrides_china_region() {
3663 let overrides = PseudoParameterOverrides { region: Some("cn-north-1".to_string()), ..Default::default() };
3664 assert_eq!(overrides.get("AWS::Partition").unwrap(), "aws-cn");
3665 assert_eq!(overrides.get("AWS::URLSuffix").unwrap(), "amazonaws.com.cn");
3666 }
3667
3668 #[test]
3675 fn fixed_value_returns_none_for_unset_pseudo_parameters() {
3676 let overrides = PseudoParameterOverrides::default();
3677
3678 for name in [
3679 "AWS::AccountId",
3680 "AWS::NotificationARNs",
3681 "AWS::Partition",
3682 "AWS::Region",
3683 "AWS::StackId",
3684 "AWS::StackName",
3685 "AWS::URLSuffix",
3686 ] {
3687 assert_eq!(
3688 overrides.fixed_value(name),
3689 None,
3690 "{name} must be a free variable when the user has not explicitly pinned it"
3691 );
3692 }
3693 }
3694
3695 #[test]
3696 fn parameter_name_at_names_the_parameter_behind_a_value() {
3697 let input = r#"{"Parameters":{"BucketName":{"Type":"String"}},
3698 "Resources":{"R":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":{"Ref":"BucketName"}}}}}"#;
3699 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3700 assert_eq!(model.parameter_name_at("R", "Properties.BucketName"), Some("BucketName"));
3701 assert!(model.is_from_parameter("R", "Properties.BucketName"));
3702 }
3703
3704 #[test]
3705 fn parameter_name_at_is_absent_for_a_value_no_parameter_produced() {
3706 let input = r#"{"Resources":{"R":{"Type":"AWS::S3::Bucket",
3709 "Properties":{"BucketName":{"Fn::ImportValue":"SharedName"}}}}}"#;
3710 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3711 assert_eq!(model.parameter_name_at("R", "Properties.BucketName"), None);
3712 assert!(!model.is_from_parameter("R", "Properties.BucketName"));
3713 }
3714
3715 #[test]
3716 fn fixed_value_returns_user_supplied_overrides() {
3717 let overrides = PseudoParameterOverrides {
3718 account_id: Some("999999999999".to_string()),
3719 partition: Some("aws-cn".to_string()),
3720 region: Some("cn-north-1".to_string()),
3721 stack_name: Some("MyStack".to_string()),
3722 ..Default::default()
3723 };
3724
3725 assert_eq!(overrides.fixed_value("AWS::AccountId"), Some("999999999999".to_string()));
3726 assert_eq!(overrides.fixed_value("AWS::Partition"), Some("aws-cn".to_string()));
3727 assert_eq!(overrides.fixed_value("AWS::Region"), Some("cn-north-1".to_string()));
3728 assert_eq!(overrides.fixed_value("AWS::StackName"), Some("MyStack".to_string()));
3729 assert_eq!(overrides.fixed_value("AWS::URLSuffix"), None, "URLSuffix not set; must remain a free variable");
3730 assert_eq!(overrides.fixed_value("Unknown"), None);
3731 }
3732
3733 #[test]
3734 fn parameter_name_from_source_reads_only_a_parameter_entry() {
3735 assert_eq!(parameter_name_from_source("Parameters/InstanceType/Default"), Some("InstanceType"));
3736 assert_eq!(parameter_name_from_source("Parameters/InstanceType/AllowedValues"), Some("InstanceType"));
3737 assert_eq!(parameter_name_from_source("Parameters/InstanceType"), Some("InstanceType"));
3738 assert_eq!(parameter_name_from_source("Intrinsic/Ref"), None);
3739 assert_eq!(parameter_name_from_source("Parameters/"), None);
3740 assert_eq!(parameter_name_from_source("ParametersLookAlike/Name"), None);
3741 }
3742
3743 #[test]
3750 fn fixed_value_does_not_propagate_region_to_partition() {
3751 let overrides = PseudoParameterOverrides { region: Some("cn-north-1".to_string()), ..Default::default() };
3752
3753 assert_eq!(overrides.fixed_value("AWS::Region"), Some("cn-north-1".to_string()));
3754 assert_eq!(
3755 overrides.fixed_value("AWS::Partition"),
3756 None,
3757 "region override must not propagate to partition - partition stays free unless the caller pins it"
3758 );
3759 }
3760
3761 #[test]
3762 fn model_rejects_oversized_template() {
3763 let huge = vec![b' '; 11 * 1024 * 1024];
3764 let result = SemanticModel::from_bytes(&huge);
3765 match result {
3766 Err(e) => assert!(e.message.contains("maximum size")),
3767 Ok(_) => panic!("Expected error for oversized template"),
3768 }
3769 }
3770
3771 #[test]
3772 fn follow_ref_returns_none_for_non_reference() {
3773 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"hello"}}}}"#;
3774 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3775 assert_eq!(model.follow_ref("R", "Properties.V"), None, "non-reference value should return None");
3776 }
3777
3778 #[test]
3779 fn resolve_deep_memoization_consistency() {
3780 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"Config":{"A":"1","B":"2"}}}}}"#;
3781 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3782 let r1 = model.resolve_deep("R", "Properties.Config.A");
3783 let r2 = model.resolve_deep("R", "Properties.Config.A");
3784 match (&r1, &r2) {
3785 (Some(ResolvedValue::Concrete { value: a }), Some(ResolvedValue::Concrete { value: b })) => {
3786 assert_eq!(a, b);
3787 }
3788 _ => panic!("Expected matching Concrete values"),
3789 }
3790 }
3791
3792 #[test]
3793 fn model_with_mappings_and_findinmap() {
3794 let input = r#"
3795Mappings:
3796 RegionMap:
3797 us-east-1:
3798 AMI: ami-12345
3799 us-west-2:
3800 AMI: ami-67890
3801Resources:
3802 R:
3803 Type: T
3804 Properties:
3805 ImageId: !FindInMap [RegionMap, us-east-1, AMI]
3806"#;
3807 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3808 match model.resolve("R", "Properties.ImageId") {
3809 Some(ResolvedValue::Concrete { value: v }) => {
3810 assert_eq!(v.as_str().unwrap(), "ami-12345")
3811 }
3812 other => panic!("Expected Concrete, got {:?}", other),
3813 }
3814 }
3815
3816 #[test]
3817 fn model_invalid_ref_tracked() {
3818 let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":{"Ref":"NonExistent"}}}}}"#;
3819 let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
3820 let r = model.resource("R").unwrap();
3821 assert!(!r.diagnostics.invalid_refs.is_empty());
3822 assert!(r.diagnostics.invalid_refs.iter().any(|s| s.value == "NonExistent"));
3823 }
3824
3825 #[test]
3826 fn collapse_arn_paths_folds_list_siblings_to_lowest_index() {
3827 let input = vec![
3828 "Properties.KeyPolicy.Statement.2.Principal.AWS.1.Fn::Sub".to_string(),
3829 "Properties.KeyPolicy.Statement.2.Principal.AWS.0.Fn::Sub".to_string(),
3830 ];
3831 let out = collapse_list_sibling_arn_paths(input);
3832 assert_eq!(out, vec!["Properties.KeyPolicy.Statement.2.Principal.AWS.0.Fn::Sub".to_string()]);
3833 }
3834
3835 #[test]
3836 fn collapse_arn_paths_keeps_distinct_parent_lists() {
3837 let input = vec![
3840 "Properties.PolicyDocument.Statement.0.Resource.Fn::Sub".to_string(),
3841 "Properties.PolicyDocument.Statement.1.Resource.Fn::Sub".to_string(),
3842 ];
3843 let mut out = collapse_list_sibling_arn_paths(input.clone());
3844 out.sort();
3845 assert_eq!(out, input);
3846 }
3847
3848 #[test]
3849 fn collapse_arn_paths_leaves_scalar_paths_untouched() {
3850 let input = vec![
3851 "Properties.KeyPolicy.Statement.0.Principal.AWS.Fn::Sub".to_string(),
3852 "Properties.KeyPolicy.Statement.1.Principal.AWS.Fn::Sub".to_string(),
3853 ];
3854 let mut out = collapse_list_sibling_arn_paths(input.clone());
3855 out.sort();
3856 assert_eq!(out, input);
3857 }
3858
3859 fn output_string_type_diagnostics(template: &str) -> usize {
3861 let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
3862 model.diagnostics.iter().filter(|d| d.rule_id == "F6101").count()
3863 }
3864
3865 #[test]
3866 fn output_literal_list_value_flagged() {
3867 let template = "Resources:\n R:\n Type: T\nOutputs:\n O:\n Value:\n - a\n - b\n";
3868 assert_eq!(output_string_type_diagnostics(template), 1);
3869 }
3870
3871 #[test]
3872 fn output_literal_object_value_flagged() {
3873 let template = "Resources:\n R:\n Type: T\nOutputs:\n O:\n Value:\n Key: v\n";
3874 assert_eq!(output_string_type_diagnostics(template), 1);
3875 }
3876
3877 #[test]
3878 fn output_list_returning_functions_flagged() {
3879 for value in ["!GetAZs \"\"", "!Split [\",\", \"a,b\"]", "!Cidr [\"10.0.0.0/16\", 1, 8]"] {
3880 let template = format!("Resources:\n R:\n Type: T\nOutputs:\n O:\n Value: {}\n", value);
3881 assert_eq!(output_string_type_diagnostics(&template), 1, "expected F6101 for output value {}", value);
3882 }
3883 }
3884
3885 #[test]
3886 fn output_empty_container_value_not_flagged() {
3887 for value in ["[]", "{}"] {
3890 let template = format!("Resources:\n R:\n Type: T\nOutputs:\n O:\n Value: {}\n", value);
3891 assert_eq!(output_string_type_diagnostics(&template), 0, "empty container {} must not be flagged", value);
3892 }
3893 }
3894
3895 #[test]
3896 fn output_string_producing_values_not_flagged() {
3897 for value in ["hello", "42", "true", "!Ref R", "!Sub \"${R}\"", "!Join [\",\", [\"a\"]]", "!ImportValue X"] {
3900 let template = format!("Resources:\n R:\n Type: T\nOutputs:\n O:\n Value: {}\n", value);
3901 assert_eq!(output_string_type_diagnostics(&template), 0, "string-valued output {} must not fire", value);
3902 }
3903 }
3904
3905 #[test]
3906 fn output_find_in_map_list_value_not_flagged() {
3907 let template = "Mappings:\n M:\n k:\n l:\n - a\n - b\nResources:\n R:\n Type: T\nOutputs:\n O:\n Value: !FindInMap [M, k, l]\n";
3913 assert_eq!(output_string_type_diagnostics(template), 0);
3914 }
3915
3916 #[test]
3917 fn output_fn_if_flags_each_list_branch() {
3918 let template = "Conditions:\n C:\n Fn::Equals: [\"a\", \"a\"]\nResources:\n R:\n Type: T\nOutputs:\n O:\n Value:\n Fn::If: [C, [\"a\"], [\"b\"]]\n";
3921 assert_eq!(output_string_type_diagnostics(template), 2);
3922 }
3923
3924 #[test]
3925 fn output_fn_if_string_branches_not_flagged() {
3926 let template = "Conditions:\n C:\n Fn::Equals: [\"a\", \"a\"]\nResources:\n R:\n Type: T\nOutputs:\n O:\n Value:\n Fn::If: [C, \"yes\", \"no\"]\n";
3927 assert_eq!(output_string_type_diagnostics(template), 0);
3928 }
3929
3930 #[test]
3931 fn join_with_enum_list_exact_4096_not_curtailed() {
3932 use crate::consts::MAX_ENUM_EXPANSION;
3933 use crate::resolver::join_with_enum_list;
3934 let variants_a: Vec<ResolvedValue> = (0..64)
3937 .map(|i| ResolvedValue::Concrete { value: serde_json::Value::String(format!("a{i}")).into() })
3938 .collect();
3939 let variants_b: Vec<ResolvedValue> = (0..64)
3940 .map(|i| ResolvedValue::Concrete { value: serde_json::Value::String(format!("b{i}")).into() })
3941 .collect();
3942 let items = vec![ResolvedValue::Enum { variants: variants_a }, ResolvedValue::Enum { variants: variants_b }];
3943 let (result, curtailed) = join_with_enum_list(",", &items);
3944 assert!(!curtailed, "exactly {MAX_ENUM_EXPANSION} combinations must not signal curtailment");
3945 if let ResolvedValue::Enum { variants } = &result {
3946 assert_eq!(variants.len(), MAX_ENUM_EXPANSION);
3947 } else {
3948 panic!("expected Enum result");
3949 }
3950 }
3951
3952 #[test]
3953 fn join_with_enum_list_one_over_curtailed() {
3954 use crate::consts::MAX_ENUM_EXPANSION;
3955 use crate::resolver::join_with_enum_list;
3956 let variants_a: Vec<ResolvedValue> = (0..65)
3958 .map(|i| ResolvedValue::Concrete { value: serde_json::Value::String(format!("a{i}")).into() })
3959 .collect();
3960 let variants_b: Vec<ResolvedValue> = (0..64)
3961 .map(|i| ResolvedValue::Concrete { value: serde_json::Value::String(format!("b{i}")).into() })
3962 .collect();
3963 let items = vec![ResolvedValue::Enum { variants: variants_a }, ResolvedValue::Enum { variants: variants_b }];
3964 let (result, curtailed) = join_with_enum_list(",", &items);
3965 assert!(curtailed, "exceeding {MAX_ENUM_EXPANSION} combinations must signal curtailment");
3966 if let ResolvedValue::Enum { variants } = &result {
3967 assert_eq!(variants.len(), MAX_ENUM_EXPANSION);
3968 } else {
3969 panic!("expected Enum result");
3970 }
3971 }
3972
3973 #[test]
3974 fn primary_id_same_parameter_across_ref_sub_join_collides() {
3975 let template = r#"
3976Parameters:
3977 Name: {Type: String}
3978Resources:
3979 A:
3980 Type: AWS::S3::Bucket
3981 Properties: {BucketName: !Ref Name}
3982 B:
3983 Type: AWS::S3::Bucket
3984 Properties: {BucketName: !Sub '${Name}'}
3985 C:
3986 Type: AWS::S3::Bucket
3987 Properties: {BucketName: !Sub ['${V}', {V: !Ref Name}]}
3988 D:
3989 Type: AWS::S3::Bucket
3990 Properties: {BucketName: !Join ['', [!Ref Name]]}
3991"#;
3992 let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
3993 let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
3994 assert_eq!(conflicts.len(), 1, "all four forms must collide into one group");
3995 let (_, resources) = conflicts.into_iter().next().unwrap();
3996 assert_eq!(resources.len(), 4, "all four resources must be in the group");
3997 }
3998
3999 #[test]
4000 fn primary_id_different_parameters_with_equal_defaults_stay_distinct() {
4001 let template = r#"
4002Parameters:
4003 A: {Type: String, Default: shared}
4004 B: {Type: String, Default: shared}
4005Resources:
4006 One:
4007 Type: AWS::S3::Bucket
4008 Properties: {BucketName: !Ref A}
4009 Two:
4010 Type: AWS::S3::Bucket
4011 Properties: {BucketName: !Ref B}
4012"#;
4013 let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
4014 let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
4015 assert!(conflicts.is_empty(), "different overridable parameters must not collide: {:?}", conflicts);
4016 }
4017
4018 #[test]
4019 fn primary_id_comparison_identity_is_separate_from_display_value() {
4020 let template = r#"
4021Parameters:
4022 Name: {Type: String}
4023Resources:
4024 DynamicOne:
4025 Type: AWS::S3::Bucket
4026 Properties: {BucketName: !Ref Name}
4027 DynamicTwo:
4028 Type: AWS::S3::Bucket
4029 Properties: {BucketName: !Ref Name}
4030 LiteralOne:
4031 Type: AWS::S3::Bucket
4032 Properties: {BucketName: 'Ref("Name")'}
4033 LiteralTwo:
4034 Type: AWS::S3::Bucket
4035 Properties: {BucketName: 'Ref("Name")'}
4036"#;
4037 let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
4038 let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
4039 assert_eq!(conflicts.len(), 2, "equal display text must not merge distinct identities");
4040 assert!(
4041 conflicts
4042 .iter()
4043 .all(|(tuple, resources)| { tuple == &["Ref(\"Name\")".to_string()] && resources.len() == 2 })
4044 );
4045 }
4046
4047 #[test]
4048 fn primary_id_mutually_exclusive_conditions_do_not_collide() {
4049 let template = r#"
4050Parameters:
4051 Env: {Type: String}
4052 Name: {Type: String}
4053Conditions:
4054 IsProd: !Equals [!Ref Env, prod]
4055 IsNotProd: !Not [!Condition IsProd]
4056Resources:
4057 ProdBucket:
4058 Type: AWS::S3::Bucket
4059 Condition: IsProd
4060 Properties: {BucketName: !Ref Name}
4061 DevBucket:
4062 Type: AWS::S3::Bucket
4063 Condition: IsNotProd
4064 Properties: {BucketName: !Ref Name}
4065"#;
4066 let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
4067 let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
4068 assert!(conflicts.is_empty(), "mutually exclusive conditions must not collide");
4069 }
4070
4071 #[test]
4072 fn primary_id_no_internal_marker_leakage_in_tuple_values() {
4073 let template = r#"
4074Parameters:
4075 Name: {Type: String}
4076Resources:
4077 A:
4078 Type: AWS::S3::Bucket
4079 Properties: {BucketName: !Ref Name}
4080 B:
4081 Type: AWS::S3::Bucket
4082 Properties: {BucketName: !Ref Name}
4083"#;
4084 let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
4085 let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
4086 assert_eq!(conflicts.len(), 1);
4087 let (tuple, _) = conflicts.into_iter().next().unwrap();
4088 let value = &tuple[0];
4089 assert!(!value.contains("$dyn:"), "tuple value must not contain $dyn: marker");
4090 assert!(!value.contains("expr:"), "tuple value must not contain expr: prefix");
4091 }
4092
4093 fn primary_identifier_conflicts_all_pairs_reference(
4097 model: &SemanticModel,
4098 resource_type: &str,
4099 identifier_properties: &[String],
4100 ) -> Vec<(Vec<String>, BTreeSet<String>)> {
4101 let mut per_resource = Vec::new();
4102 for resource_id in model.resources_of_type(resource_type) {
4103 let scenarios = model.primary_identifier_scenarios(resource_id, identifier_properties);
4104 if !scenarios.is_empty() {
4105 per_resource.push((resource_id, scenarios));
4106 }
4107 }
4108 let mut conflicts: BTreeMap<Vec<String>, (Vec<String>, BTreeSet<String>)> = BTreeMap::new();
4109 for left_index in 0..per_resource.len() {
4110 for right_index in (left_index + 1)..per_resource.len() {
4111 let (left_resource, left_scenarios) = &per_resource[left_index];
4112 let (right_resource, right_scenarios) = &per_resource[right_index];
4113 for left in left_scenarios {
4114 for right in right_scenarios {
4115 if left.identity_tuple != right.identity_tuple {
4116 continue;
4117 }
4118 let mut assumptions = left.assumptions.clone();
4119 assumptions.extend(right.assumptions.iter().cloned());
4120 if assumptions.is_empty() || model.conditions.is_satisfiable(&assumptions) {
4121 let (_, resources) = conflicts
4122 .entry(left.identity_tuple.clone())
4123 .or_insert_with(|| (left.display_tuple.clone(), BTreeSet::new()));
4124 resources.insert((*left_resource).clone());
4125 resources.insert((*right_resource).clone());
4126 }
4127 }
4128 }
4129 }
4130 }
4131 conflicts.into_values().collect()
4132 }
4133
4134 #[test]
4135 fn primary_id_unconditional_resource_collides_with_every_conditional_duplicate() {
4136 let template = r#"
4137Parameters:
4138 Env: {Type: String}
4139Conditions:
4140 IsAlpha: !Equals [!Ref Env, alpha]
4141 IsBeta: !Equals [!Ref Env, beta]
4142Resources:
4143 Always:
4144 Type: AWS::S3::Bucket
4145 Properties: {BucketName: shared}
4146 WhenAlpha:
4147 Type: AWS::S3::Bucket
4148 Condition: IsAlpha
4149 Properties: {BucketName: shared}
4150 WhenBeta:
4151 Type: AWS::S3::Bucket
4152 Condition: IsBeta
4153 Properties: {BucketName: shared}
4154"#;
4155 let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
4156 let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
4157 assert_eq!(conflicts.len(), 1, "the single shared name is one collision group: {conflicts:?}");
4158 let (display, resources) = conflicts.into_iter().next().unwrap();
4159 assert_eq!(display, vec!["shared".to_string()]);
4160 assert_eq!(
4161 resources,
4162 BTreeSet::from(["Always".to_string(), "WhenAlpha".to_string(), "WhenBeta".to_string()]),
4163 "the unconditional resource collides with each conditional duplicate, joining all three even though the two conditions are themselves mutually exclusive"
4164 );
4165 }
4166
4167 #[test]
4168 fn primary_id_mutually_exclusive_conditions_across_identities_never_collide() {
4169 let template = r#"
4170Parameters:
4171 Env: {Type: String}
4172 Left: {Type: String}
4173 Right: {Type: String}
4174Conditions:
4175 IsProd: !Equals [!Ref Env, prod]
4176 IsNotProd: !Not [!Condition IsProd]
4177Resources:
4178 LeftProd:
4179 Type: AWS::S3::Bucket
4180 Condition: IsProd
4181 Properties: {BucketName: !Ref Left}
4182 LeftDev:
4183 Type: AWS::S3::Bucket
4184 Condition: IsNotProd
4185 Properties: {BucketName: !Ref Left}
4186 RightProd:
4187 Type: AWS::S3::Bucket
4188 Condition: IsProd
4189 Properties: {BucketName: !Ref Right}
4190 RightDev:
4191 Type: AWS::S3::Bucket
4192 Condition: IsNotProd
4193 Properties: {BucketName: !Ref Right}
4194"#;
4195 let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
4196 let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
4197 assert!(
4198 conflicts.is_empty(),
4199 "each identity's two resources are guarded by mutually exclusive conditions, so neither identity group yields a collision: {conflicts:?}"
4200 );
4201 }
4202
4203 #[test]
4204 fn primary_id_duplicate_scenarios_of_one_resource_do_not_self_collide() {
4205 let template = r#"
4206Parameters:
4207 Env: {Type: String}
4208Conditions:
4209 IsProd: !Equals [!Ref Env, prod]
4210Resources:
4211 Lonely:
4212 Type: AWS::S3::Bucket
4213 Properties:
4214 BucketName: !If [IsProd, shared, shared]
4215"#;
4216 let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
4217 let scenarios = model.primary_identifier_scenarios("Lonely", &["BucketName".to_string()]);
4218 assert!(
4219 scenarios.len() >= 2,
4220 "the Fn::If must expand into multiple scenarios so self-comparison is actually exercised: {}",
4221 scenarios.len()
4222 );
4223 let identities: BTreeSet<Vec<String>> =
4224 scenarios.iter().map(|scenario| scenario.identity_tuple.clone()).collect();
4225 assert_eq!(identities.len(), 1, "the branches must share one comparison identity so they land in one group");
4226
4227 let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
4228 assert!(
4229 conflicts.is_empty(),
4230 "a single resource whose branches produce the same identifier must not be reported as colliding with itself: {conflicts:?}"
4231 );
4232 }
4233
4234 #[test]
4235 fn primary_id_overlapping_conditions_collide() {
4236 let template = r#"
4237Parameters:
4238 Env: {Type: String}
4239 Name: {Type: String}
4240Conditions:
4241 NotAlpha: !Not [!Equals [!Ref Env, alpha]]
4242 NotBeta: !Not [!Equals [!Ref Env, beta]]
4243Resources:
4244 One:
4245 Type: AWS::S3::Bucket
4246 Condition: NotAlpha
4247 Properties: {BucketName: !Ref Name}
4248 Two:
4249 Type: AWS::S3::Bucket
4250 Condition: NotBeta
4251 Properties: {BucketName: !Ref Name}
4252"#;
4253 let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
4254 let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
4255 assert_eq!(
4256 conflicts.len(),
4257 1,
4258 "the two resources share one identity and their conditions can both hold: {conflicts:?}"
4259 );
4260 let (_, resources) = conflicts.into_iter().next().unwrap();
4261 assert_eq!(resources, BTreeSet::from(["One".to_string(), "Two".to_string()]));
4262 }
4263
4264 #[test]
4265 fn primary_id_display_tuple_comes_from_first_compatible_pair_not_first_candidate() {
4266 let template = r#"
4267Parameters:
4268 Env: {Type: String}
4269Conditions:
4270 IsProd: !Equals [!Ref Env, prod]
4271 IsDev: !Not [!Condition IsProd]
4272Resources:
4273 ProdKeyed:
4274 Type: AWS::S3::Bucket
4275 Condition: IsProd
4276 Properties:
4277 BucketName: {alpha: one, beta: two}
4278 DevKeyedFirst:
4279 Type: AWS::S3::Bucket
4280 Condition: IsDev
4281 Properties:
4282 BucketName: {beta: two, alpha: one}
4283 DevKeyedSecond:
4284 Type: AWS::S3::Bucket
4285 Condition: IsDev
4286 Properties:
4287 BucketName: {beta: two, alpha: one}
4288"#;
4289 let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
4290 let conflicts = model.primary_identifier_conflicts("AWS::S3::Bucket", &["BucketName".to_string()]);
4291 assert_eq!(conflicts.len(), 1, "all three author the same key-sorted identity: {conflicts:?}");
4292 let (display, resources) = conflicts.into_iter().next().unwrap();
4293 assert_eq!(
4294 resources,
4295 BTreeSet::from(["DevKeyedFirst".to_string(), "DevKeyedSecond".to_string()]),
4296 "the earlier-declared prod resource is mutually exclusive with both dev resources, so it never forms a compatible pair and is absent from the group"
4297 );
4298 assert!(
4299 display[0].starts_with("{\"beta\""),
4300 "display must come from the left scenario of the first compatible pair (a dev resource, authored beta-first), not the earlier incompatible prod candidate authored alpha-first: {display:?}"
4301 );
4302 }
4303
4304 #[test]
4305 fn primary_id_grouped_traversal_matches_all_pairs_reference_and_sat_budget() {
4306 let template = r#"
4307Parameters:
4308 Env: {Type: String}
4309 Shared: {Type: String}
4310Conditions:
4311 IsProd: !Equals [!Ref Env, prod]
4312 IsStaging: !Equals [!Ref Env, staging]
4313 IsProdAlias: !Equals [!Ref Env, prod]
4314Resources:
4315 AlphaAlways:
4316 Type: AWS::S3::Bucket
4317 Properties: {BucketName: alpha}
4318 AlphaProd:
4319 Type: AWS::S3::Bucket
4320 Condition: IsProd
4321 Properties: {BucketName: alpha}
4322 AlphaStaging:
4323 Type: AWS::S3::Bucket
4324 Condition: IsStaging
4325 Properties: {BucketName: alpha}
4326 BetaProd:
4327 Type: AWS::S3::Bucket
4328 Condition: IsProd
4329 Properties: {BucketName: beta}
4330 BetaProdAlias:
4331 Type: AWS::S3::Bucket
4332 Condition: IsProdAlias
4333 Properties: {BucketName: beta}
4334 SharedOne:
4335 Type: AWS::S3::Bucket
4336 Properties: {BucketName: !Ref Shared}
4337 SharedTwo:
4338 Type: AWS::S3::Bucket
4339 Properties: {BucketName: !Ref Shared}
4340 Unique:
4341 Type: AWS::S3::Bucket
4342 Properties: {BucketName: unique}
4343"#;
4344 let identifier_properties = ["BucketName".to_string()];
4345
4346 let reference_model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
4347 let reference = primary_identifier_conflicts_all_pairs_reference(
4348 &reference_model,
4349 "AWS::S3::Bucket",
4350 &identifier_properties,
4351 );
4352 let reference_budget = reference_model.conditions.sat_iterations_used();
4353
4354 let model = SemanticModel::from_bytes(template.as_bytes()).unwrap();
4355 let grouped = model.primary_identifier_conflicts("AWS::S3::Bucket", &identifier_properties);
4356 let grouped_budget = model.conditions.sat_iterations_used();
4357
4358 assert_eq!(
4359 grouped, reference,
4360 "grouped traversal must produce the identical conflicts as the all-pairs reference"
4361 );
4362 assert!(
4363 reference_budget > 0,
4364 "the fixture must drive the satisfiability solver so the budget comparison is meaningful"
4365 );
4366 assert_eq!(
4367 grouped_budget, reference_budget,
4368 "grouped traversal must issue satisfiability queries in the same order and count, spending the shared budget identically across multiple identities"
4369 );
4370 }
4371
4372 #[test]
4373 fn output_invalid_ref_has_canonical_path() {
4374 let template = "Resources:\n R:\n Type: T\nOutputs:\n Bad:\n Value: !Ref Missing\n";
4375 let result = SemanticModel::parse(template.as_bytes(), ParseConfig::default()).unwrap();
4376 let ref_defect = result
4377 .model
4378 .diagnostics
4379 .iter()
4380 .find(|d| d.rule_id == "F6101" && d.message.contains("Missing"))
4381 .expect("F6101 for missing ref");
4382 assert_eq!(
4383 ref_defect.property_path.as_deref(),
4384 Some("Outputs.Bad.Value.Ref"),
4385 "parse-time output ref diagnostic must have dot-separated path"
4386 );
4387 assert_ne!(ref_defect.span, crate::UNKNOWN_SPAN, "span must be resolved");
4388 }
4389}