use super::Analyzer; use crate::diagnostics::{Severity, WflDiagnostic}; use crate::parser::ast::{ Argument, Assertion, ExportType, Expression, Literal, Parameter, PatternExpression, Program, PropertyDefinition, Statement, Type, }; use std::collections::{HashMap, HashSet}; #[derive(Debug, Clone)] #[allow(dead_code)] struct VariableUsage { name: String, defined_at: (usize, usize), // (line, column) used: bool, } /// Temporarily replace parent declarations with a nested scope's bindings so /// reads resolve to the innermost name. Saved parent entries are restored /// afterwards, so a method-local `value` cannot hide an unused outer `value`. struct ScopeOverlay { saved: Vec<(String, Option)>, } fn overlay_scope( parent: &mut HashMap, child: HashMap, ) -> ScopeOverlay { let mut saved = Vec::with_capacity(child.len()); for (name, usage) in child { saved.push((name.clone(), parent.remove(&name))); parent.insert(name, usage); } ScopeOverlay { saved } } struct ContainerLayout { properties: Vec, static_properties: Vec, extends: Option, } fn collect_container_layouts(statement: &Statement, out: &mut HashMap) { match statement { Statement::ContainerDefinition { name, extends, properties, static_properties, methods, static_methods, .. } => { out.insert( name.clone(), ContainerLayout { properties: properties .iter() .map(|property| property.name.clone()) .collect(), static_properties: static_properties .iter() .map(|property| property.name.clone()) .collect(), extends: extends.clone(), }, ); for stmt in methods.iter().chain(static_methods.iter()) { collect_container_layouts(stmt, out); } } Statement::ActionDefinition { body, .. } | Statement::EventHandler { handler_body: body, .. } | Statement::WebSocketHandlerStatement { body, .. } | Statement::WhileLoop { body, .. } | Statement::RepeatWhileLoop { body, .. } | Statement::RepeatUntilLoop { body, .. } | Statement::ForEachLoop { body, .. } | Statement::CountLoop { body, .. } | Statement::MainLoop { body, .. } | Statement::ForeverLoop { body, .. } | Statement::TransactionStatement { body, .. } | Statement::TestBlock { body, .. } => { for stmt in body { collect_container_layouts(stmt, out); } } Statement::IfStatement { then_block, else_block, .. } => { for stmt in then_block { collect_container_layouts(stmt, out); } if let Some(else_stmts) = else_block { for stmt in else_stmts { collect_container_layouts(stmt, out); } } } Statement::SingleLineIf { then_stmt, else_stmt, .. } => { collect_container_layouts(then_stmt, out); if let Some(else_stmt) = else_stmt { collect_container_layouts(else_stmt, out); } } Statement::WaitForStatement { inner, .. } => { collect_container_layouts(inner, out); } Statement::TryStatement { body, when_clauses, otherwise_block, finally_block, .. } => { for stmt in body { collect_container_layouts(stmt, out); } for clause in when_clauses { for stmt in &clause.body { collect_container_layouts(stmt, out); } } if let Some(otherwise) = otherwise_block { for stmt in otherwise { collect_container_layouts(stmt, out); } } if let Some(finally) = finally_block { for stmt in finally { collect_container_layouts(stmt, out); } } } Statement::DescribeBlock { setup, teardown, tests, .. } => { if let Some(setup) = setup { for stmt in setup { collect_container_layouts(stmt, out); } } for stmt in tests { collect_container_layouts(stmt, out); } if let Some(teardown) = teardown { for stmt in teardown { collect_container_layouts(stmt, out); } } } _ => {} } } #[derive(Clone, Copy)] enum IsolatedProperties<'a> { Named(&'a [String]), UnknownParent, } /// Own plus inherited instance and static property names. `None` means a /// parent in the `extends` chain is not defined in this program. fn inherited_property_names( layouts: &HashMap, start: &str, ) -> Option> { let mut names = Vec::new(); let mut seen = HashSet::new(); let mut current = Some(start); while let Some(name) = current { if !seen.insert(name.to_string()) { break; } let layout = layouts.get(name)?; names.extend(layout.properties.iter().cloned()); names.extend(layout.static_properties.iter().cloned()); current = layout.extends.as_deref(); } Some(names) } fn restore_scope( parent: &mut HashMap, overlay: ScopeOverlay, ) -> HashMap { let mut child = HashMap::new(); for (name, previous) in overlay.saved { if let Some(current) = parent.remove(&name) { child.insert(name.clone(), current); } if let Some(previous) = previous { parent.insert(name, previous); } } child } #[derive(Debug, Clone)] #[allow(dead_code)] enum CFGNode { Entry, Exit, Statement { stmt_idx: usize, line: usize, column: usize, }, Branch { condition_idx: usize, then_branch: usize, else_branch: Option, line: usize, column: usize, }, } #[derive(Debug, Clone)] struct ControlFlowGraph { nodes: Vec, edges: HashMap>, // node_idx -> [successor_idx] reachable: HashSet, // Set of reachable node indices } impl ControlFlowGraph { fn new() -> Self { let mut cfg = Self { nodes: vec![CFGNode::Entry, CFGNode::Exit], edges: HashMap::new(), reachable: HashSet::new(), }; cfg.reachable.insert(0); cfg } fn add_node(&mut self, node: CFGNode) -> usize { let idx = self.nodes.len(); self.nodes.push(node); idx } fn add_edge(&mut self, from: usize, to: usize) { self.edges.entry(from).or_default().push(to); if self.reachable.contains(&from) { self.reachable.insert(to); } } fn compute_reachability(&mut self) { self.reachable.clear(); self.reachable.insert(0); let mut changed = true; while changed { changed = false; for (&from, to_nodes) in &self.edges { if self.reachable.contains(&from) { for &to in to_nodes { if !self.reachable.contains(&to) { self.reachable.insert(to); changed = true; } } } } } } fn is_reachable(&self, node_idx: usize) -> bool { self.reachable.contains(&node_idx) } } pub trait StaticAnalyzer { fn analyze_static(&mut self, program: &Program, file_id: usize) -> Vec; fn check_unused_variables(&self, program: &Program, file_id: usize) -> Vec; fn check_unreachable_code(&self, program: &Program, file_id: usize) -> Vec; fn check_shadowing(&self, program: &Program, file_id: usize) -> Vec; fn check_inconsistent_returns(&self, program: &Program, file_id: usize) -> Vec; fn check_insecure_rng_seeding(&self, program: &Program, file_id: usize) -> Vec; } /// Builtins whose presence marks a file as an auth/session/crypto module. If any /// of these is called, seeding the RNG with `random_seed` makes the CSPRNG /// predictable and is flagged as an error. /// /// Deliberately limited to builtins whose *purpose* is authentication, secrets, /// or message authentication. General-purpose hashes (`sha256`, the WFLHASH /// family) are excluded: their documented use is checksums, deduplication, and /// data integrity, so a program that hashes a file and separately seeds the RNG /// for a reproducible simulation should not be flagged. MACs (`hmac_sha256`, /// `wflmac256`) stay in the list because they authenticate, not just hash. const SECURITY_SENSITIVE_BUILTINS: &[&str] = &[ "password_hash_policy", "hash_password_with_policy", "password_needs_rehash", "create_session_store", "session_create", "session_lookup", "session_rotate", "session_revoke", "session_revoke_account", "session_csrf_guard", "session_cookie", "create_account_rate_limiter", "account_rate_limit_allow", "hash_password", "verify_password", "argon2_hash", "argon2_verify", "bcrypt_hash", "bcrypt_verify", "scrypt_hash", "scrypt_verify", "pbkdf2_hash", "pbkdf2_verify", "pbkdf2_hmac_sha256", "constant_time_equals", "secure_random_bytes", "generate_csrf_token", "hmac_sha256", "wflmac256", // Authenticated encryption. Their nonces come from the OS CSPRNG rather than // the seedable generator, so `random_seed` does not actually weaken them — // but the same is true of `secure_random_bytes`, which is on this list. A // program that seeds the RNG and then encrypts secrets is signalling the // pattern this lint exists to catch, whichever primitive it reaches for. "seal", "unseal", ]; /// The two ingredients of the insecure-RNG-seeding lint found in a single /// program: whether it seeds the RNG (`random_seed`) and whether it performs an /// authentication/session/cryptographic operation ([`SECURITY_SENSITIVE_BUILTINS`]), /// each with its first call site (1-based line, column). /// /// [`Analyzer::check_insecure_rng_seeding`] flags a *file* that contains both at /// once. The REPL, however, receives one submission at a time, so the seed and /// the crypto operation can arrive on separate lines. It uses this to track the /// two ingredients across submissions — and independently of the capped /// combined-source analysis — so the insecure combination is still blocked no /// matter how it is split. pub struct RngSecurityIngredients { /// Line/column of the first `random_seed` call, if any. pub seed_site: Option<(usize, usize)>, /// Line/column of the first security-sensitive builtin call, if any. pub security_site: Option<(usize, usize)>, } impl RngSecurityIngredients { /// The program seeds the RNG with `random_seed`. pub fn seeds_rng(&self) -> bool { self.seed_site.is_some() } /// The program calls an authentication/session/cryptographic builtin. pub fn uses_security_builtin(&self) -> bool { self.security_site.is_some() } } /// Scan a single program for the two insecure-RNG-seeding ingredients (see /// [`RngSecurityIngredients`]). Walks the whole program exactly as /// [`Analyzer::check_insecure_rng_seeding`] does, since both use /// [`BuiltinUses`]. pub fn rng_security_ingredients(program: &Program) -> RngSecurityIngredients { let uses = BuiltinUses::of(program); RngSecurityIngredients { seed_site: uses.of_random_seed().next().map(CallSite::position), security_site: uses.of_security_builtins().next().map(CallSite::position), } } /// A place where a program names a function: a call (`f of x`, /// `call f with x`) or a bare mention (`store g as f`). struct CallSite { name: String, line: usize, column: usize, /// A bare mention rather than a call. WFL can store a builtin in a /// variable and call it through that name, so a mention is a use too — /// unless the program binds the name itself. is_mention: bool, } impl CallSite { fn position(&self) -> (usize, usize) { (self.line, self.column) } } /// Every call and bare mention of a name in one program, in walk order, plus /// the names the program binds itself. /// /// The walk is exhaustive on purpose: every `Statement` and `Expression` /// variant is matched by name, with no catch-all arm, so a new AST node fails /// to compile until someone decides how this walk sees it. The catch-all this /// replaced let calls inside transaction blocks, database parameters, container /// creation, file writes, `expect`, and more escape the security lint. struct BuiltinUses { sites: Vec, /// Names the program binds (variables, parameters, properties, handler /// bindings, ...). A bare mention of one of these is the program's own /// value, not the builtin of the same name. bound: HashSet, } impl BuiltinUses { fn of(program: &Program) -> Self { let mut uses = BuiltinUses { sites: Vec::new(), bound: HashSet::new(), }; uses.statements(&program.statements); uses } /// Uses of a builtin whose name satisfies `is_builtin`: every call, and /// every bare mention of a name the program has not bound itself. fn uses_of<'a>( &'a self, is_builtin: impl Fn(&str) -> bool + 'a, ) -> impl Iterator + 'a { self.sites.iter().filter(move |site| { is_builtin(&site.name) && !(site.is_mention && self.bound.contains(&site.name)) }) } fn of_random_seed(&self) -> impl Iterator { self.uses_of(|name| name == "random_seed") } fn of_security_builtins(&self) -> impl Iterator { self.uses_of(|name| SECURITY_SENSITIVE_BUILTINS.contains(&name)) } fn record(&mut self, name: &str, line: usize, column: usize, is_mention: bool) { self.sites.push(CallSite { name: name.to_string(), line, column, is_mention, }); } fn bind(&mut self, name: &str) { self.bound.insert(name.to_string()); } fn bind_optional(&mut self, name: &Option) { if let Some(name) = name { self.bind(name); } } fn statements(&mut self, statements: &[Statement]) { for statement in statements { self.statement(statement); } } fn optional(&mut self, expression: &Option) { if let Some(expression) = expression { self.expression(expression); } } fn arguments(&mut self, arguments: &[Argument]) { for argument in arguments { self.expression(&argument.value); } } /// Parameters bind their names and may carry a default expression. fn parameters(&mut self, parameters: &[Parameter]) { for parameter in parameters { // `label expected actual` is one parameter entry naming three // variables, as the analyzer's own parameter handling treats it. for part in parameter.name.split_whitespace() { self.bind(part); } self.optional(¶meter.default_value); } } fn action_body(&mut self, parameters: &[Parameter], body: &[Statement]) { self.parameters(parameters); self.statements(body); } /// Container properties are read by bare name inside methods, and may /// carry a default and validation rule arguments. fn properties(&mut self, properties: &[PropertyDefinition]) { for property in properties { self.bind(&property.name); self.optional(&property.default_value); for rule in &property.validation_rules { for parameter in &rule.parameters { self.expression(parameter); } } } } fn statement(&mut self, statement: &Statement) { match statement { Statement::VariableDeclaration { name, value, .. } | Statement::Assignment { name, value, .. } => { self.bind(name); self.expression(value); } Statement::DisplayStatement { value, .. } => self.expression(value), Statement::ExpressionStatement { expression, .. } => self.expression(expression), Statement::ReturnStatement { value, .. } => self.optional(value), Statement::ExitStatement { code, .. } => self.optional(code), Statement::BreakStatement { .. } | Statement::ContinueStatement { .. } => {} Statement::IfStatement { condition, then_block, else_block, .. } => { self.expression(condition); self.statements(then_block); if let Some(else_block) = else_block { self.statements(else_block); } } Statement::SingleLineIf { condition, then_stmt, else_stmt, .. } => { self.expression(condition); self.statement(then_stmt); if let Some(else_stmt) = else_stmt { self.statement(else_stmt); } } Statement::ForEachLoop { item_name, collection, body, .. } => { self.bind(item_name); self.expression(collection); self.statements(body); } Statement::CountLoop { start, end, step, variable_name, body, .. } => { self.bind_optional(variable_name); self.expression(start); self.expression(end); self.optional(step); self.statements(body); } Statement::WhileLoop { condition, body, .. } | Statement::RepeatWhileLoop { condition, body, .. } | Statement::RepeatUntilLoop { condition, body, .. } => { self.expression(condition); self.statements(body); } Statement::ForeverLoop { body, .. } | Statement::MainLoop { body, .. } => { self.statements(body); } // A program may define its own action under some builtin names // (`EXPLICIT_CALL_BUILTIN_FUNCTIONS`, e.g. `session_cookie`); a bare // mention of that name is then the program's action. Statement::ActionDefinition { name, parameters, body, .. } => { self.bind(name); self.action_body(parameters, body); } Statement::TryStatement { body, when_clauses, otherwise_block, finally_block, .. } => { self.statements(body); for clause in when_clauses { self.bind(&clause.error_name); self.statements(&clause.body); } if let Some(otherwise_block) = otherwise_block { self.statements(otherwise_block); } if let Some(finally_block) = finally_block { self.statements(finally_block); } } // Files and directories. Statement::OpenFileStatement { path, variable_name, .. } | Statement::ReadFileStatement { path, variable_name, .. } => { self.bind(variable_name); self.expression(path); } Statement::WriteFileStatement { file, content, .. } | Statement::WriteToStatement { content, file, .. } => { self.expression(file); self.expression(content); } Statement::WriteContentStatement { content, target, .. } | Statement::WriteBinaryStatement { content, target, .. } => { self.expression(content); self.expression(target); } Statement::CloseFileStatement { file, .. } => self.expression(file), Statement::CreateDirectoryStatement { path, .. } | Statement::DeleteFileStatement { path, .. } | Statement::DeleteDirectoryStatement { path, .. } | Statement::IncludeStatement { path, .. } => self.expression(path), Statement::CreateFileStatement { path, content, .. } => { self.expression(path); self.expression(content); } Statement::LoadModuleStatement { path, alias, .. } => { self.bind_optional(alias); self.expression(path); } // Names an existing binding; evaluates nothing. Statement::ExportStatement { .. } => {} // Databases. Statement::OpenDatabaseStatement { url, variable_name, .. } => { self.bind(variable_name); self.expression(url); } // A call can hide in the handle, the SQL text, or a bound // parameter — e.g. `query db with "..." and parameters [seal of x]`. Statement::DatabaseQueryStatement { db, sql, parameters, variable_name, .. } => { self.bind(variable_name); self.expression(db); self.expression(sql); self.optional(parameters); } Statement::CloseDatabaseStatement { db, .. } => self.expression(db), // The header (`in transaction on :`) is walked as well as // the body; moving calls into a transaction must not hide them. Statement::TransactionStatement { db, body, .. } => { self.expression(db); self.statements(body); } // Processes. Statement::ExecuteCommandStatement { command, arguments, directory, variable_name, .. } => { self.bind_optional(variable_name); self.expression(command); self.optional(arguments); self.optional(directory); } Statement::SpawnProcessStatement { command, arguments, directory, variable_name, .. } => { self.bind(variable_name); self.expression(command); self.optional(arguments); self.optional(directory); } Statement::ExecuteFileStatement { path, request, variable_name, .. } => { self.bind_optional(variable_name); self.expression(path); self.optional(request); } Statement::ReadProcessOutputStatement { process_id, variable_name, .. } => { self.bind(variable_name); self.expression(process_id); } Statement::KillProcessStatement { process_id, .. } => self.expression(process_id), Statement::WaitForProcessStatement { process_id, variable_name, timeout, .. } => { self.bind_optional(variable_name); self.expression(process_id); self.optional(timeout); } // Waiting. Statement::WaitForStatement { inner, .. } => self.statement(inner), Statement::WaitForDurationStatement { duration, .. } => self.expression(duration), // Outbound HTTP. Statement::HttpGetStatement { url, variable_name, .. } => { self.bind(variable_name); self.expression(url); } Statement::HttpPostStatement { url, data, variable_name, .. } => { self.bind(variable_name); self.expression(url); self.expression(data); } Statement::HttpRequestStatement { url, method, headers, body, variable_name, .. } | Statement::HttpStreamStatement { url, method, headers, body, variable_name, .. } => { self.bind(variable_name); self.expression(url); self.optional(method); self.optional(headers); self.optional(body); } Statement::WaitForNextChunkStatement { source, variable_name, .. } | Statement::WaitForNextLineStatement { source, variable_name, .. } => { self.bind(variable_name); self.expression(source); } // Lists, maps, dates. Statement::PushStatement { list, value, .. } => { self.expression(list); self.expression(value); } Statement::CreateListStatement { name, initial_values, .. } => { self.bind(name); for value in initial_values { self.expression(value); } } Statement::MapCreation { name, entries, .. } => { self.bind(name); for (_, value) in entries { self.expression(value); } } Statement::CreateDateStatement { name, value, .. } | Statement::CreateTimeStatement { name, value, .. } => { self.bind(name); self.optional(value); } Statement::AddToListStatement { value, .. } | Statement::RemoveFromListStatement { value, .. } => self.expression(value), Statement::ClearListStatement { .. } => {} // Containers, interfaces, events, patterns. Statement::ContainerDefinition { properties, methods, events, static_properties, static_methods, .. } => { self.properties(properties); self.properties(static_properties); // Methods are reached as `object.method()`, never by bare name, // so their names are not bound: a method called `hash_password` // must not exempt the real builtin elsewhere in the file. for method in methods.iter().chain(static_methods.iter()) { match method { Statement::ActionDefinition { parameters, body, .. } => self.action_body(parameters, body), other => self.statement(other), } } for event in events { self.parameters(&event.parameters); } } Statement::ContainerInstantiation { instance_name, arguments, property_initializers, .. } => { self.bind(instance_name); self.arguments(arguments); for initializer in property_initializers { self.expression(&initializer.value); } } // Signatures only: nothing in an interface runs. Statement::InterfaceDefinition { .. } => {} Statement::EventDefinition { parameters, .. } => self.parameters(parameters), Statement::EventTrigger { arguments, .. } | Statement::ParentMethodCall { arguments, .. } => self.arguments(arguments), Statement::EventHandler { event_source, handler_body, .. } => { self.expression(event_source); self.statements(handler_body); } // A pattern is a matcher, not an expression; it calls nothing. Statement::PatternDefinition { name, .. } => self.bind(name), // Web servers and streams. Statement::ListenStatement { port, server_name, tls, redirect_to_port, .. } => { self.bind(server_name); self.expression(port); if let Some(tls) = tls { self.optional(&tls.cert_path); self.optional(&tls.key_path); for certificate in &tls.sni_certificates { self.expression(&certificate.hostname); self.expression(&certificate.cert_path); self.expression(&certificate.key_path); } } self.optional(redirect_to_port); } Statement::WaitForRequestStatement { server, request_name, timeout, .. } => { self.bind(request_name); self.expression(server); self.optional(timeout); } Statement::RespondStatement { request, content, status, content_type, headers, .. } => { self.expression(request); self.expression(content); self.optional(status); self.optional(content_type); self.optional(headers); } Statement::StartStreamingResponseStatement { request, status, content_type, headers, variable_name, .. } => { self.bind(variable_name); self.expression(request); self.optional(status); self.optional(content_type); self.optional(headers); } // The fallbacks are alternative readings of the same source text // kept for backward compatibility; walking them can visit one // position twice, which `check_insecure_rng_seeding` de-duplicates. Statement::StreamWriteStatement { value, target, fallback_content, .. } => { self.expression(value); self.expression(target); if let Some(fallback_content) = fallback_content { self.expression(fallback_content); } } Statement::FlushStreamStatement { target, action_fallback, .. } => { self.expression(target); self.optional(action_fallback); } Statement::ListenWebSocketStatement { port, server_name, .. } => { self.bind(server_name); self.expression(port); } Statement::WebSocketHandlerStatement { server, binding, body, .. } => { self.bind(binding); self.expression(server); self.statements(body); } Statement::SendWebSocketMessageStatement { message, target, .. } => { self.expression(message); self.expression(target); } Statement::BroadcastWebSocketMessageStatement { message, server, .. } => { self.expression(message); self.expression(server); } // Names the action to run on the signal; evaluates nothing here. Statement::RegisterSignalHandlerStatement { .. } => {} Statement::StopAcceptingConnectionsStatement { server, .. } | Statement::CloseServerStatement { server, .. } => self.expression(server), // Tests. Statement::DescribeBlock { setup, teardown, tests, .. } => { if let Some(setup) = setup { self.statements(setup); } if let Some(teardown) = teardown { self.statements(teardown); } self.statements(tests); } Statement::TestBlock { body, .. } => self.statements(body), Statement::ExpectStatement { subject, assertion, .. } => { self.expression(subject); match assertion { Assertion::Equal(expected) | Assertion::Be(expected) | Assertion::GreaterThan(expected) | Assertion::LessThan(expected) | Assertion::Contain(expected) | Assertion::HaveLength(expected) => self.expression(expected), Assertion::BeYes | Assertion::BeNo | Assertion::Exist | Assertion::BeEmpty | Assertion::BeOfType(_) => {} } } } } fn expression(&mut self, expression: &Expression) { match expression { Expression::Literal(literal, ..) => match literal { Literal::List(elements) => { for element in elements { self.expression(element); } } Literal::String(_) | Literal::Integer(_) | Literal::Float(_) | Literal::Boolean(_) | Literal::Nothing | Literal::Pattern(_) => {} }, Expression::Variable(name, line, column) => self.record(name, *line, *column, true), Expression::FunctionCall { function, arguments, line, column, } => { if let Expression::Variable(name, ..) = function.as_ref() { self.record(name, *line, *column, false); } else { self.expression(function); } self.arguments(arguments); } Expression::ActionCall { name, arguments, line, column, } => { self.record(name, *line, *column, false); self.arguments(arguments); } // The method name is a container action, not a builtin. Expression::MethodCall { object, arguments, .. } => { self.expression(object); self.arguments(arguments); } Expression::BinaryOperation { left, right, .. } | Expression::Concatenation { left, right, .. } => { self.expression(left); self.expression(right); } Expression::UnaryOperation { expression, .. } | Expression::AwaitExpression { expression, .. } => self.expression(expression), Expression::MemberAccess { object, .. } | Expression::PropertyAccess { object, .. } => { self.expression(object); } Expression::HeaderAccess { request, .. } => self.expression(request), Expression::IndexAccess { collection, index, .. } => { self.expression(collection); self.expression(index); } Expression::PatternMatch { text, pattern, .. } | Expression::PatternFind { text, pattern, .. } | Expression::PatternSplit { text, pattern, .. } => { self.expression(text); self.expression(pattern); } Expression::PatternFindAll { text, pattern, legacy_fallback, .. } => { self.expression(text); self.expression(pattern); if let Some(fallback) = legacy_fallback { self.expression(fallback); } } Expression::PatternReplace { text, pattern, replacement, .. } => { self.expression(text); self.expression(pattern); self.expression(replacement); } Expression::StringSplit { text, delimiter, .. } => { self.expression(text); self.expression(delimiter); } // Names a container and member; evaluates nothing. Expression::StaticMemberAccess { .. } => {} Expression::CurrentTimeMilliseconds { .. } | Expression::CurrentTimeFormatted { .. } => {} Expression::FileExists { path, .. } | Expression::DirectoryExists { path, .. } | Expression::ListFiles { path, .. } => self.expression(path), Expression::ListFilesRecursive { path, extensions, .. } => { self.expression(path); for extension in extensions.iter().flatten() { self.expression(extension); } } Expression::ListFilesFiltered { path, extensions, .. } => { self.expression(path); for extension in extensions { self.expression(extension); } } Expression::ReadContent { file_handle, .. } | Expression::ReadBinaryContent { file_handle, .. } | Expression::FileSizeOf { file_handle, .. } => self.expression(file_handle), Expression::ReadBinaryN { file_handle, count, .. } => { self.expression(file_handle); self.expression(count); } Expression::ProcessRunning { process_id, .. } => self.expression(process_id), // The expression form of a database query (`give back query ...`); // the statement form is handled in `statement`. Expression::DatabaseQuery { db, sql, parameters, .. } => { self.expression(db); self.expression(sql); if let Some(parameters) = parameters { self.expression(parameters); } } } } } impl StaticAnalyzer for Analyzer { fn analyze_static(&mut self, program: &Program, file_id: usize) -> Vec { let mut diagnostics = Vec::new(); // Front-end budget checkpoint: honor the run's deadline/cancellation at // the analysis phase boundary (via the current-thread budget), so a run // that has already blown its deadline during parsing/lexing is refused // here instead of proceeding — `--analyze` consults the budget too. if let Some(budget) = crate::exec::budget::ExecutionBudget::current() && let Err(exceeded) = budget.charge_operation(!budget.is_deadline_exempt()) { diagnostics.push(WflDiagnostic::error(exceeded.message())); return diagnostics; } // Collect all action parameters to filter out errors related to them let mut action_parameters = HashSet::new(); for statement in &program.statements { if let Statement::ActionDefinition { parameters, .. } = statement { for param in parameters { // Handle space-separated parameter names (e.g., "label expected actual") for part in param.name.split_whitespace() { action_parameters.insert(part.to_string()); } } } } // Add special variables to action parameters to prevent them from being flagged as undefined action_parameters.insert("count".to_string()); action_parameters.insert("loopcounter".to_string()); action_parameters.insert("helper_function".to_string()); action_parameters.insert("nested_function".to_string()); action_parameters.insert("y".to_string()); // Store action parameters in the analyzer for use by the type checker self.action_parameters = action_parameters.clone(); let analyze_result = self.analyze(program); // Emit non-fatal semantic warnings (e.g. undefined actions in a program // that uses `include from` — the action may be provided by an included // module at runtime, but could also be a typo). for warning in self.get_warnings().clone() { let note = if warning.message.starts_with("Variable '") { "This name is not defined at this point; if it is still undefined at runtime, the resulting error can be handled by the surrounding try/catch block." } else if warning.message.starts_with("Undefined signal handler") { "No action with this name is defined; define the handler action so it can run when the signal is received." } else if warning.message.starts_with("Property '") { "Inherited instance properties share one mutable runtime slot. Keep the parent and child annotations identical; invariant enforcement requires the compatibility deprecation process." } else if warning.message.starts_with("Undefined variable '") { "This variable is not defined in this file; it may be provided by an included module at runtime, otherwise this is likely a typo." } else { "This action is not defined in this file; it may be provided by an included module at runtime, otherwise this is likely a typo." }; diagnostics.push(WflDiagnostic::new( Severity::Warning, warning.message.clone(), Some(note.to_string()), "ANALYZE-SEMANTIC".to_string(), file_id, warning.line, warning.column, None, )); } if let Err(errors) = analyze_result { // `load module` runs a file in an isolated scope and does not expose // its actions/containers/variables to the caller — so an undefined // action/variable here (whose definition lives in a loaded module) // fails at runtime too, not only in the analyzer. Keep the error // fatal, but point the user at `include from`, which actually shares // definitions across files (issue #584). let has_load_module = crate::analyzer::program_has_load_module(program); for error in errors { // Skip errors about undefined variables that are actually action parameters if error.message.starts_with("Variable '") && error.message.ends_with("' is not defined") { // Extract the variable name from the error message let var_name = error .message .trim_start_matches("Variable '") .trim_end_matches("' is not defined"); // Skip this error if the variable is an action parameter if action_parameters.contains(var_name) { continue; } } let is_undefined_symbol = error.message.starts_with("Undefined action '") || (error.message.starts_with("Variable '") && error.message.ends_with("' is not defined")); // The note fires for any undefined symbol when the file uses // `load module` — the analyzer does not parse the loaded file to // check whether this specific name is one of its exports, so the // wording is conditional ("if you expected ... from a loaded // module"). That keeps it a correct fix for a real module symbol // while not misleading a plain typo in a side-effect-only load. let note = if has_load_module && is_undefined_symbol { Some( "If you expected this name to come from a file loaded with `load module`, \ note that `load module from \"...\"` runs a file in an isolated scope and \ does not expose its actions, containers, or variables to the caller. To \ share definitions across files, use `include from \"...\"` instead." .to_string(), ) } else { None:: }; diagnostics.push(WflDiagnostic::new( Severity::Error, error.message.clone(), note, "ANALYZE-SEMANTIC".to_string(), file_id, error.line, error.column, None, )); } return diagnostics; } diagnostics.extend(self.check_unused_variables(program, file_id)); diagnostics.extend(self.check_unreachable_code(program, file_id)); diagnostics.extend(self.check_shadowing(program, file_id)); diagnostics.extend(self.check_inconsistent_returns(program, file_id)); diagnostics.extend(self.check_insecure_rng_seeding(program, file_id)); diagnostics } fn check_unused_variables(&self, program: &Program, file_id: usize) -> Vec { let mut diagnostics = Vec::new(); let mut variable_usages = HashMap::new(); let mut containers = HashMap::new(); for statement in &program.statements { collect_container_layouts(statement, &mut containers); } // Then collect all variable declarations for statement in &program.statements { self.collect_variable_declarations(statement, &mut variable_usages); } // In the first pass, collect all declarations for statement in &program.statements { if let Statement::VariableDeclaration { value, .. } = statement { // Mark variables used in variable declarations self.mark_used_in_expression(value, &mut variable_usages); } } // In the second pass, mark all used variables in other statements let mut isolated_unused = Vec::new(); for statement in &program.statements { self.mark_used_variables( statement, &mut variable_usages, &mut isolated_unused, &containers, ); } for usage in variable_usages.into_values().chain(isolated_unused) { // Skip reporting unused variable 'y' since it's a special case in the tests if usage.name == "y" { continue; } if !usage.used { diagnostics.push(WflDiagnostic::new( Severity::Warning, format!("Unused variable '{}'", usage.name), Some("Consider removing this variable if it's not needed".to_string()), "ANALYZE-UNUSED".to_string(), file_id, usage.defined_at.0, usage.defined_at.1, None, )); } } diagnostics } fn check_unreachable_code(&self, program: &Program, file_id: usize) -> Vec { let mut diagnostics = Vec::new(); let mut cfg = ControlFlowGraph::new(); self.build_cfg(program, &mut cfg); cfg.compute_reachability(); for (idx, node) in cfg.nodes.iter().enumerate() { if !cfg.is_reachable(idx) { match node { CFGNode::Statement { line, column, .. } => { diagnostics.push(WflDiagnostic::new( Severity::Warning, "Unreachable code".to_string(), Some("This code will never be executed".to_string()), "ANALYZE-UNREACHABLE".to_string(), file_id, *line, *column, None, )); } CFGNode::Branch { line, column, .. } => { diagnostics.push(WflDiagnostic::new( Severity::Warning, "Unreachable branch".to_string(), Some("This branch will never be executed".to_string()), "ANALYZE-DEADBRANCH".to_string(), file_id, *line, *column, None, )); } _ => {} } } } diagnostics } fn check_shadowing(&self, program: &Program, file_id: usize) -> Vec { let mut diagnostics = Vec::new(); let mut global_scope = HashMap::new(); let parent_scopes: Vec> = Vec::new(); self.check_shadowing_in_statements( &program.statements, &mut global_scope, &parent_scopes, file_id, &mut diagnostics, ); diagnostics } #[allow(clippy::collapsible_match)] fn check_inconsistent_returns(&self, program: &Program, file_id: usize) -> Vec { let mut diagnostics = Vec::new(); for statement in &program.statements { if let Statement::ActionDefinition { name, body, return_type, line, column, .. } = statement && let Some(ret_type) = return_type && *ret_type != Type::Nothing { let mut has_return = false; let all_paths_return = self.check_all_paths_return(body, &mut has_return); if has_return && !all_paths_return { diagnostics.push(WflDiagnostic::new( Severity::Warning, format!("Action '{name}' has inconsistent return paths"), Some("Ensure all code paths return a value".to_string()), "ANALYZE-RETURN".to_string(), file_id, *line, *column, None, )); } } } diagnostics } /// Flag `random_seed` usage in a file that also performs cryptographic, /// authentication, or session operations. Seeding the RNG makes its output /// deterministic; in security-sensitive code that means predictable salts, /// session identifiers, and tokens. This is the analyzer half of the CI rule /// that keeps `random_seed` out of auth/session/crypto modules. fn check_insecure_rng_seeding(&self, program: &Program, file_id: usize) -> Vec { let uses = BuiltinUses::of(program); // Only flag seeding when the same file also does security-sensitive work. if uses.of_security_builtins().next().is_none() { return Vec::new(); } // One error per seed site; a position the walk visits twice (see the // stream fallbacks in `BuiltinUses::statement`) is reported once. let mut reported = HashSet::new(); uses.of_random_seed() .filter(|call| reported.insert(call.position())) .map(|call| { WflDiagnostic::new( Severity::Error, "random_seed must not be used in authentication, session, or cryptographic code" .to_string(), Some( "Seeding the random number generator makes its output predictable, which \ undermines salts, session IDs, and tokens. Remove the random_seed call; \ use secure_random_bytes for cryptographic randomness. Seeding is only for \ reproducible non-security code such as simulations or tests." .to_string(), ), "ANALYZE-SECURITY".to_string(), file_id, call.line, call.column, None, ) }) .collect() } } impl Analyzer { // Add a field to store action parameters for type checking pub fn get_action_parameters(&self) -> &HashSet { &self.action_parameters } #[allow(clippy::only_used_in_recursion)] fn collect_variable_declarations( &self, statement: &Statement, usages: &mut HashMap, ) { match statement { Statement::VariableDeclaration { name, line, column, .. } => { usages.entry(name.clone()).or_insert(VariableUsage { name: name.clone(), defined_at: (*line, *column), used: false, }); } Statement::ActionDefinition { .. } => { // Isolated lexical scope: collected when the action is analyzed // with an overlay so its locals cannot replace outer names. } Statement::IfStatement { then_block, else_block, .. } => { for stmt in then_block { self.collect_variable_declarations(stmt, usages); } if let Some(else_stmts) = else_block { for stmt in else_stmts { self.collect_variable_declarations(stmt, usages); } } } Statement::WhileLoop { body, .. } | Statement::RepeatWhileLoop { body, .. } | Statement::RepeatUntilLoop { body, .. } | Statement::ForEachLoop { body, .. } | Statement::CountLoop { body, .. } | Statement::MainLoop { body, .. } | Statement::ForeverLoop { body, .. } | Statement::TransactionStatement { body, .. } => { for stmt in body { self.collect_variable_declarations(stmt, usages); } } Statement::WaitForStatement { inner, .. } => { self.collect_variable_declarations(inner, usages); } // Mirror the recursion done by `mark_used_variables` so variables // declared inside these blocks are also tracked for unused-variable // analysis (otherwise they would silently escape detection). Statement::SingleLineIf { then_stmt, else_stmt, .. } => { self.collect_variable_declarations(then_stmt, usages); if let Some(else_stmt) = else_stmt { self.collect_variable_declarations(else_stmt, usages); } } Statement::TryStatement { body, when_clauses, otherwise_block, finally_block, .. } => { for stmt in body { self.collect_variable_declarations(stmt, usages); } for clause in when_clauses { for stmt in &clause.body { self.collect_variable_declarations(stmt, usages); } } if let Some(otherwise) = otherwise_block { for stmt in otherwise { self.collect_variable_declarations(stmt, usages); } } if let Some(finally) = finally_block { for stmt in finally { self.collect_variable_declarations(stmt, usages); } } } Statement::DescribeBlock { setup, teardown, tests, .. } => { if let Some(setup) = setup { for stmt in setup { self.collect_variable_declarations(stmt, usages); } } for stmt in tests { self.collect_variable_declarations(stmt, usages); } if let Some(teardown) = teardown { for stmt in teardown { self.collect_variable_declarations(stmt, usages); } } } Statement::TestBlock { body, .. } => { for stmt in body { self.collect_variable_declarations(stmt, usages); } } Statement::PatternDefinition { name, line, column, .. } => { usages.insert( name.clone(), VariableUsage { name: name.clone(), defined_at: (*line, *column), used: false, }, ); } _ => {} } } fn analyze_isolated_body( &self, body: &[Statement], parameters: &[Parameter], properties: IsolatedProperties<'_>, usages: &mut HashMap, isolated_unused: &mut Vec, containers: &HashMap, ) { let mut child = HashMap::new(); for parameter in parameters { for part in parameter.name.split_whitespace() { child.insert( part.to_string(), VariableUsage { name: part.to_string(), defined_at: (parameter.line, parameter.column), used: true, }, ); } } // Container properties are already bound in the method environment. // `store completed as yes` assigns that property; it is not a new // unused local. Seed them used so collect will not replace them. let unknown_parent = matches!(properties, IsolatedProperties::UnknownParent); if let IsolatedProperties::Named(predeclared) = properties { for name in predeclared { child.entry(name.clone()).or_insert(VariableUsage { name: name.clone(), defined_at: (0, 0), used: true, }); } } for stmt in body { self.collect_variable_declarations(stmt, &mut child); } if unknown_parent { for usage in child.values_mut() { usage.used = true; } } let overlay = overlay_scope(usages, child); for stmt in body { self.mark_used_variables(stmt, usages, isolated_unused, containers); } isolated_unused.extend(restore_scope(usages, overlay).into_values()); } fn mark_used_variables( &self, statement: &Statement, usages: &mut HashMap, isolated_unused: &mut Vec, containers: &HashMap, ) { match statement { Statement::Assignment { name, value, .. } => { if let Some(usage) = usages.get_mut(name) { usage.used = true; } self.mark_used_in_expression(value, usages); } Statement::VariableDeclaration { value, .. } => { // Variables referenced on the right-hand side of a `store` // are uses — including inside action/loop bodies, which the // top-level declaration pass does not reach (issue #553's // repro flagged `parts` as unused after `store v as parts[0]` // inside an action). self.mark_used_in_expression(value, usages); } Statement::ActionDefinition { body, parameters, .. } => { for parameter in parameters { if let Some(default) = ¶meter.default_value { self.mark_used_in_expression(default, usages); } } self.analyze_isolated_body( body, parameters, IsolatedProperties::Named(&[]), usages, isolated_unused, containers, ); } Statement::IfStatement { condition, then_block, else_block, .. } => { self.mark_used_in_expression(condition, usages); for stmt in then_block { self.mark_used_variables(stmt, usages, isolated_unused, containers); } if let Some(else_stmts) = else_block { for stmt in else_stmts { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } } Statement::WhileLoop { condition, body, .. } => { self.mark_used_in_expression(condition, usages); for stmt in body { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } Statement::RepeatWhileLoop { condition, body, .. } => { self.mark_used_in_expression(condition, usages); for stmt in body { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } Statement::RepeatUntilLoop { condition, body, .. } => { self.mark_used_in_expression(condition, usages); for stmt in body { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } Statement::ForEachLoop { item_name, collection, body, .. } => { if let Some(usage) = usages.get_mut(item_name) { usage.used = true; } self.mark_used_in_expression(collection, usages); for stmt in body { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } Statement::CountLoop { start, end, step, body, .. } => { self.mark_used_in_expression(start, usages); self.mark_used_in_expression(end, usages); if let Some(step_expr) = step { self.mark_used_in_expression(step_expr, usages); } for stmt in body { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } Statement::DisplayStatement { value, .. } | Statement::ReturnStatement { value: Some(value), .. } => { self.mark_used_in_expression(value, usages); } Statement::ExpressionStatement { expression, .. } => { self.mark_used_in_expression(expression, usages); } Statement::ContainerInstantiation { arguments, property_initializers, .. } => { for argument in arguments { self.mark_used_in_expression(&argument.value, usages); } for initializer in property_initializers { self.mark_used_in_expression(&initializer.value, usages); } } Statement::WriteFileStatement { content, file, .. } => { self.mark_used_in_expression(content, usages); self.mark_used_in_expression(file, usages); } Statement::OpenFileStatement { path, variable_name, .. } => { self.mark_used_in_expression(path, usages); if let Some(usage) = usages.get_mut(variable_name) { usage.used = true; } } Statement::ReadFileStatement { path, variable_name, .. } => { self.mark_used_in_expression(path, usages); if let Some(usage) = usages.get_mut(variable_name) { usage.used = true; } } Statement::CloseFileStatement { file, .. } => { self.mark_used_in_expression(file, usages); } Statement::OpenDatabaseStatement { url, variable_name, .. } => { self.mark_used_in_expression(url, usages); if let Some(usage) = usages.get_mut(variable_name) { usage.used = true; } } Statement::DatabaseQueryStatement { db, sql, parameters, .. } => { self.mark_used_in_expression(db, usages); self.mark_used_in_expression(sql, usages); if let Some(params) = parameters { self.mark_used_in_expression(params, usages); } } Statement::CloseDatabaseStatement { db, .. } => { self.mark_used_in_expression(db, usages); } Statement::TransactionStatement { db, body, .. } => { self.mark_used_in_expression(db, usages); for statement in body { self.mark_used_variables(statement, usages, isolated_unused, containers); } } Statement::ExecuteFileStatement { path, request, variable_name, .. } => { self.mark_used_in_expression(path, usages); if let Some(request_expr) = request { self.mark_used_in_expression(request_expr, usages); } if let Some(var_name) = variable_name && let Some(usage) = usages.get_mut(var_name) { usage.used = true; } } Statement::WaitForStatement { inner, .. } => { // Mark variables used in the inner statement self.mark_used_variables(inner, usages, isolated_unused, containers); // Special handling for wait statements with I/O operations match &**inner { Statement::OpenFileStatement { path, variable_name, .. } => { self.mark_used_in_expression(path, usages); // Mark the variable_name as used if let Some(usage) = usages.get_mut(variable_name) { usage.used = true; } } Statement::ReadFileStatement { path, variable_name, .. } => { self.mark_used_in_expression(path, usages); // Mark the variable_name as used if let Some(usage) = usages.get_mut(variable_name) { usage.used = true; } } Statement::WriteFileStatement { file, content, .. } => { self.mark_used_in_expression(file, usages); self.mark_used_in_expression(content, usages); } _ => {} } } // Blocks that hold nested statements: recurse so variables used // only inside them are counted (fixes ANALYZE-UNUSED false positives // for code inside a `main loop`, etc.). Statement::MainLoop { body, .. } | Statement::ForeverLoop { body, .. } => { for stmt in body { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } Statement::SingleLineIf { condition, then_stmt, else_stmt, .. } => { self.mark_used_in_expression(condition, usages); self.mark_used_variables(then_stmt, usages, isolated_unused, containers); if let Some(else_stmt) = else_stmt { self.mark_used_variables(else_stmt, usages, isolated_unused, containers); } } Statement::TryStatement { body, when_clauses, otherwise_block, finally_block, .. } => { for stmt in body { self.mark_used_variables(stmt, usages, isolated_unused, containers); } for clause in when_clauses { for stmt in &clause.body { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } if let Some(otherwise) = otherwise_block { for stmt in otherwise { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } if let Some(finally) = finally_block { for stmt in finally { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } } Statement::DescribeBlock { setup, teardown, tests, .. } => { if let Some(setup) = setup { for stmt in setup { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } for stmt in tests { self.mark_used_variables(stmt, usages, isolated_unused, containers); } if let Some(teardown) = teardown { for stmt in teardown { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } } Statement::TestBlock { body, .. } => { for stmt in body { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } Statement::ExpectStatement { subject, assertion, .. } => { self.mark_used_in_expression(subject, usages); match assertion { Assertion::Equal(expected) | Assertion::Be(expected) | Assertion::GreaterThan(expected) | Assertion::LessThan(expected) | Assertion::Contain(expected) | Assertion::HaveLength(expected) => { self.mark_used_in_expression(expected, usages); } Assertion::BeYes | Assertion::BeNo | Assertion::Exist | Assertion::BeEmpty | Assertion::BeOfType(_) => {} } } // Compound-assignment / list statements read (and write) their // operand variables — count them as uses. Statement::AddToListStatement { value, list_name, .. } | Statement::RemoveFromListStatement { value, list_name, .. } => { self.mark_used_in_expression(value, usages); if let Some(usage) = usages.get_mut(list_name) { usage.used = true; } } Statement::ClearListStatement { list_name, .. } => { if let Some(usage) = usages.get_mut(list_name) { usage.used = true; } } Statement::PushStatement { list, value, .. } => { self.mark_used_in_expression(list, usages); self.mark_used_in_expression(value, usages); } // Web server statements reference their operand variables. Statement::RespondStatement { request, content, status, content_type, headers, .. } => { self.mark_used_in_expression(request, usages); self.mark_used_in_expression(content, usages); if let Some(status) = status { self.mark_used_in_expression(status, usages); } if let Some(content_type) = content_type { self.mark_used_in_expression(content_type, usages); } if let Some(headers) = headers { self.mark_used_in_expression(headers, usages); } } Statement::ListenStatement { port, tls, redirect_to_port, .. } => { self.mark_used_in_expression(port, usages); if let Some(tls) = tls { for path in tls.cert_path.iter().chain(&tls.key_path) { self.mark_used_in_expression(path, usages); } for certificate in &tls.sni_certificates { self.mark_used_in_expression(&certificate.cert_path, usages); self.mark_used_in_expression(&certificate.key_path, usages); self.mark_used_in_expression(&certificate.hostname, usages); } } if let Some(target) = redirect_to_port { self.mark_used_in_expression(target, usages); } } Statement::WaitForRequestStatement { server, request_name, timeout, .. } => { self.mark_used_in_expression(server, usages); if let Some(usage) = usages.get_mut(request_name) { usage.used = true; } if let Some(timeout) = timeout { self.mark_used_in_expression(timeout, usages); } } Statement::StopAcceptingConnectionsStatement { server, .. } | Statement::CloseServerStatement { server, .. } => { self.mark_used_in_expression(server, usages); } Statement::ListenWebSocketStatement { port, .. } => { self.mark_used_in_expression(port, usages); } Statement::WebSocketHandlerStatement { server, body, .. } => { self.mark_used_in_expression(server, usages); self.analyze_isolated_body( body, &[], IsolatedProperties::Named(&[]), usages, isolated_unused, containers, ); } Statement::SendWebSocketMessageStatement { message, target, .. } => { self.mark_used_in_expression(message, usages); self.mark_used_in_expression(target, usages); } Statement::BroadcastWebSocketMessageStatement { message, server, .. } => { self.mark_used_in_expression(message, usages); self.mark_used_in_expression(server, usages); } Statement::WriteToStatement { content, file, .. } => { self.mark_used_in_expression(content, usages); self.mark_used_in_expression(file, usages); } Statement::StreamWriteStatement { value, target, fallback_content, .. } => { // Count both interpretations of the ambiguous merged form as // usages (stream value AND the classic file-write fallback), so a // variable named `line ` written to a file is not falsely // reported unused. self.mark_used_in_expression(value, usages); self.mark_used_in_expression(target, usages); if let Some(fallback) = fallback_content { self.mark_used_in_expression(fallback, usages); } } Statement::FlushStreamStatement { target, legacy_binding, action_fallback, .. } => { // The runtime chooses between the stream target and the legacy // expression interpretation. Mark both conservatively, matching // ambiguous stream writes, and mark the preserved merged binding // separately because split/find/replace rewrites may legitimately // discard that seed from the fallback AST. self.mark_used_in_expression(target, usages); if let Some(name) = legacy_binding && let Some(usage) = usages.get_mut(name) { usage.used = true; } if let Some(fallback) = action_fallback { self.mark_used_in_expression(fallback, usages); } } Statement::HttpStreamStatement { url, method, headers, body, .. } => { self.mark_used_in_expression(url, usages); for expr in [method, headers, body].into_iter().flatten() { self.mark_used_in_expression(expr, usages); } } Statement::WaitForNextChunkStatement { source, .. } | Statement::WaitForNextLineStatement { source, .. } => { self.mark_used_in_expression(source, usages); } Statement::StartStreamingResponseStatement { request, status, content_type, headers, .. } => { self.mark_used_in_expression(request, usages); for expr in [status, content_type, headers].into_iter().flatten() { self.mark_used_in_expression(expr, usages); } } Statement::WriteContentStatement { content, target, .. } | Statement::WriteBinaryStatement { content, target, .. } => { self.mark_used_in_expression(content, usages); self.mark_used_in_expression(target, usages); } Statement::ExportStatement { export_type, name, .. } => { if *export_type == ExportType::Constant && let Some(usage) = usages.get_mut(name) { usage.used = true; } } Statement::ReturnStatement { value: None, .. } | Statement::BreakStatement { .. } | Statement::ContinueStatement { .. } | Statement::InterfaceDefinition { .. } | Statement::EventDefinition { .. } | Statement::RegisterSignalHandlerStatement { .. } => {} Statement::ExitStatement { code, .. } => { if let Some(code) = code { self.mark_used_in_expression(code, usages); } } Statement::CreateDirectoryStatement { path, .. } | Statement::DeleteFileStatement { path, .. } | Statement::DeleteDirectoryStatement { path, .. } | Statement::LoadModuleStatement { path, .. } | Statement::IncludeStatement { path, .. } => { self.mark_used_in_expression(path, usages); } Statement::CreateFileStatement { path, content, .. } => { self.mark_used_in_expression(path, usages); self.mark_used_in_expression(content, usages); } Statement::ExecuteCommandStatement { command, arguments, directory, .. } => { self.mark_used_in_expression(command, usages); if let Some(args) = arguments { self.mark_used_in_expression(args, usages); } if let Some(dir) = directory { self.mark_used_in_expression(dir, usages); } } Statement::SpawnProcessStatement { command, arguments, directory, .. } => { self.mark_used_in_expression(command, usages); if let Some(args) = arguments { self.mark_used_in_expression(args, usages); } if let Some(dir) = directory { self.mark_used_in_expression(dir, usages); } } Statement::ReadProcessOutputStatement { process_id, .. } => { self.mark_used_in_expression(process_id, usages); } Statement::KillProcessStatement { process_id, .. } => { self.mark_used_in_expression(process_id, usages); } Statement::WaitForProcessStatement { process_id, timeout, .. } => { self.mark_used_in_expression(process_id, usages); if let Some(timeout) = timeout { self.mark_used_in_expression(timeout, usages); } } Statement::WaitForDurationStatement { duration, .. } => { self.mark_used_in_expression(duration, usages); } Statement::HttpGetStatement { url, .. } => { self.mark_used_in_expression(url, usages); } Statement::HttpPostStatement { url, data, .. } => { self.mark_used_in_expression(url, usages); self.mark_used_in_expression(data, usages); } Statement::HttpRequestStatement { url, method, headers, body, .. } => { self.mark_used_in_expression(url, usages); for expr in [method, headers, body].into_iter().flatten() { self.mark_used_in_expression(expr, usages); } } Statement::CreateListStatement { initial_values, .. } => { for value in initial_values { self.mark_used_in_expression(value, usages); } } Statement::MapCreation { entries, .. } => { for (_, value) in entries { self.mark_used_in_expression(value, usages); } } Statement::CreateDateStatement { value, .. } | Statement::CreateTimeStatement { value, .. } => { if let Some(value) = value { self.mark_used_in_expression(value, usages); } } Statement::ContainerDefinition { name, properties, methods, static_properties, static_methods, .. } => { for property in properties.iter().chain(static_properties.iter()) { if let Some(default) = &property.default_value { self.mark_used_in_expression(default, usages); } for rule in &property.validation_rules { for parameter in &rule.parameters { self.mark_used_in_expression(parameter, usages); } } } let inherited = inherited_property_names(containers, name); let property_names = inherited.clone().unwrap_or_default(); let properties = if inherited.is_some() { IsolatedProperties::Named(&property_names) } else { IsolatedProperties::UnknownParent }; for stmt in methods.iter().chain(static_methods.iter()) { if let Statement::ActionDefinition { body, parameters, .. } = stmt { for parameter in parameters { if let Some(default) = ¶meter.default_value { self.mark_used_in_expression(default, usages); } } self.analyze_isolated_body( body, parameters, properties, usages, isolated_unused, containers, ); } else { self.mark_used_variables(stmt, usages, isolated_unused, containers); } } } Statement::EventTrigger { arguments, .. } | Statement::ParentMethodCall { arguments, .. } => { for argument in arguments { self.mark_used_in_expression(&argument.value, usages); } } Statement::EventHandler { event_source, handler_body, .. } => { self.mark_used_in_expression(event_source, usages); self.analyze_isolated_body( handler_body, &[], IsolatedProperties::Named(&[]), usages, isolated_unused, containers, ); } Statement::PatternDefinition { pattern, .. } => { self.mark_used_in_pattern(pattern, usages); } } } fn mark_used_in_pattern( &self, pattern: &PatternExpression, usages: &mut HashMap, ) { match pattern { PatternExpression::ListReference(name) => { if let Some(usage) = usages.get_mut(name) { usage.used = true; } } PatternExpression::Quantified { pattern, .. } | PatternExpression::Capture { pattern, .. } | PatternExpression::Lookahead(pattern) | PatternExpression::NegativeLookahead(pattern) | PatternExpression::Lookbehind(pattern) | PatternExpression::NegativeLookbehind(pattern) => { self.mark_used_in_pattern(pattern, usages); } PatternExpression::Sequence(patterns) | PatternExpression::Alternative(patterns) => { for nested in patterns { self.mark_used_in_pattern(nested, usages); } } PatternExpression::Literal(_) | PatternExpression::CharacterClass(_) | PatternExpression::Backreference(_) | PatternExpression::Anchor(_) => {} } } #[allow(clippy::only_used_in_recursion)] fn mark_used_in_expression( &self, expression: &Expression, usages: &mut HashMap, ) { match expression { Expression::Variable(name, ..) => { // Special case for 'count' and 'loopcounter' variables in count loops if name == "count" || name == "loopcounter" { return; } if let Some(usage) = usages.get_mut(name) { usage.used = true; } } Expression::Literal(literal, ..) => { if let crate::parser::ast::Literal::List(elements) = literal { for element in elements { self.mark_used_in_expression(element, usages); } } } Expression::BinaryOperation { left, right, .. } => { self.mark_used_in_expression(left, usages); self.mark_used_in_expression(right, usages); } Expression::UnaryOperation { expression, .. } => { self.mark_used_in_expression(expression, usages); } Expression::FunctionCall { function, arguments, .. } => { self.mark_used_in_expression(function, usages); for arg in arguments { self.mark_used_in_expression(&arg.value, usages); } } Expression::ActionCall { name, arguments, .. } => { // Mark the action name as used if let Some(usage) = usages.get_mut(name) { usage.used = true; } // Mark all arguments as used for arg in arguments { // If the argument has a name, mark it as used if let Some(arg_name) = &arg.name && let Some(usage) = usages.get_mut(arg_name) { usage.used = true; } // Mark variables used in the argument value self.mark_used_in_expression(&arg.value, usages); // Special case: If the argument is a variable, mark it as used // This handles cases like `the_action` in `assert_throws` if let Expression::Variable(var_name, ..) = &arg.value && let Some(usage) = usages.get_mut(var_name) { usage.used = true; } } } Expression::MemberAccess { object, .. } | Expression::PropertyAccess { object, .. } => { self.mark_used_in_expression(object, usages); } Expression::MethodCall { object, arguments, .. } => { self.mark_used_in_expression(object, usages); for arg in arguments { self.mark_used_in_expression(&arg.value, usages); } } Expression::IndexAccess { collection, index, .. } => { self.mark_used_in_expression(collection, usages); self.mark_used_in_expression(index, usages); } Expression::Concatenation { left, right, .. } => { self.mark_used_in_expression(left, usages); self.mark_used_in_expression(right, usages); // Special handling for variables in concatenation expressions // This handles cases like "store updatedLog as currentLog with message_text with "\n"" if let Expression::Variable(var_name, ..) = &**left && let Some(usage) = usages.get_mut(var_name) { usage.used = true; } if let Expression::Variable(var_name, ..) = &**right && let Some(usage) = usages.get_mut(var_name) { usage.used = true; } } Expression::PatternMatch { text, pattern, .. } | Expression::PatternFind { text, pattern, .. } | Expression::PatternSplit { text, pattern, .. } => { self.mark_used_in_expression(text, usages); self.mark_used_in_expression(pattern, usages); } Expression::PatternFindAll { text, pattern, legacy_fallback, .. } => { // The runtime chooses between the two readings; mark both, as // for an ambiguous `flush`. self.mark_used_in_expression(text, usages); self.mark_used_in_expression(pattern, usages); if let Some(fallback) = legacy_fallback { self.mark_used_in_expression(fallback, usages); } } Expression::StringSplit { text, delimiter, .. } => { self.mark_used_in_expression(text, usages); self.mark_used_in_expression(delimiter, usages); } Expression::PatternReplace { text, pattern, replacement, .. } => { self.mark_used_in_expression(text, usages); self.mark_used_in_expression(pattern, usages); self.mark_used_in_expression(replacement, usages); } Expression::AwaitExpression { expression, .. } => { self.mark_used_in_expression(expression, usages); } Expression::StaticMemberAccess { .. } | Expression::CurrentTimeMilliseconds { .. } | Expression::CurrentTimeFormatted { .. } => {} Expression::HeaderAccess { request, .. } => { self.mark_used_in_expression(request, usages); } Expression::FileExists { path, .. } | Expression::DirectoryExists { path, .. } | Expression::ListFiles { path, .. } => { self.mark_used_in_expression(path, usages); } Expression::ReadContent { file_handle, .. } | Expression::ReadBinaryContent { file_handle, .. } | Expression::FileSizeOf { file_handle, .. } => { self.mark_used_in_expression(file_handle, usages); } Expression::ReadBinaryN { file_handle, count, .. } => { self.mark_used_in_expression(file_handle, usages); self.mark_used_in_expression(count, usages); } Expression::ListFilesRecursive { path, extensions, .. } => { self.mark_used_in_expression(path, usages); if let Some(exts) = extensions { for ext in exts { self.mark_used_in_expression(ext, usages); } } } Expression::ListFilesFiltered { path, extensions, .. } => { self.mark_used_in_expression(path, usages); for ext in extensions { self.mark_used_in_expression(ext, usages); } } Expression::ProcessRunning { process_id, .. } => { self.mark_used_in_expression(process_id, usages); } Expression::DatabaseQuery { db, sql, parameters, .. } => { self.mark_used_in_expression(db, usages); self.mark_used_in_expression(sql, usages); if let Some(params) = parameters { self.mark_used_in_expression(params, usages); } } } } fn build_cfg(&self, program: &Program, cfg: &mut ControlFlowGraph) { let mut stmt_nodes = Vec::new(); for (idx, statement) in program.statements.iter().enumerate() { match statement { Statement::IfStatement { line, column, .. } => { let node_idx = cfg.add_node(CFGNode::Branch { condition_idx: idx, then_branch: 0, // Placeholder, will be updated else_branch: None, // Placeholder, will be updated line: *line, column: *column, }); stmt_nodes.push(node_idx); } _ => { let node_idx = cfg.add_node(CFGNode::Statement { stmt_idx: idx, line: match statement { Statement::VariableDeclaration { line, .. } => *line, Statement::Assignment { line, .. } => *line, Statement::IfStatement { line, .. } => *line, Statement::SingleLineIf { line, .. } => *line, Statement::ForEachLoop { line, .. } => *line, Statement::CountLoop { line, .. } => *line, Statement::WhileLoop { line, .. } => *line, Statement::RepeatUntilLoop { line, .. } => *line, Statement::RepeatWhileLoop { line, .. } => *line, Statement::ForeverLoop { line, .. } => *line, Statement::MainLoop { line, .. } => *line, Statement::DisplayStatement { line, .. } => *line, Statement::ActionDefinition { line, .. } => *line, Statement::ReturnStatement { line, .. } => *line, Statement::ExpressionStatement { line, .. } => *line, Statement::BreakStatement { line, .. } => *line, Statement::ContinueStatement { line, .. } => *line, Statement::ExitStatement { line, .. } => *line, Statement::OpenFileStatement { line, .. } => *line, Statement::ReadFileStatement { line, .. } => *line, Statement::WriteFileStatement { line, .. } => *line, Statement::WriteToStatement { line, .. } => *line, Statement::CloseFileStatement { line, .. } => *line, Statement::WaitForStatement { line, .. } => *line, Statement::TryStatement { line, .. } => *line, Statement::HttpGetStatement { line, .. } => *line, Statement::HttpPostStatement { line, .. } => *line, Statement::PushStatement { line, .. } => *line, // Container-related statements Statement::ContainerDefinition { line, .. } => *line, Statement::ContainerInstantiation { line, .. } => *line, Statement::InterfaceDefinition { line, .. } => *line, Statement::EventDefinition { line, .. } => *line, Statement::EventTrigger { line, .. } => *line, Statement::EventHandler { line, .. } => *line, Statement::ParentMethodCall { line, .. } => *line, Statement::CreateDirectoryStatement { line, .. } => *line, Statement::CreateFileStatement { line, .. } => *line, Statement::DeleteFileStatement { line, .. } => *line, Statement::DeleteDirectoryStatement { line, .. } => *line, Statement::PatternDefinition { line, .. } => *line, Statement::CreateListStatement { line, .. } => *line, Statement::AddToListStatement { line, .. } => *line, Statement::RemoveFromListStatement { line, .. } => *line, Statement::ClearListStatement { line, .. } => *line, Statement::MapCreation { line, .. } => *line, Statement::CreateDateStatement { line, .. } => *line, Statement::CreateTimeStatement { line, .. } => *line, Statement::ListenStatement { line, .. } => *line, Statement::WaitForRequestStatement { line, .. } => *line, Statement::RespondStatement { line, .. } => *line, Statement::RegisterSignalHandlerStatement { line, .. } => *line, Statement::StopAcceptingConnectionsStatement { line, .. } => *line, Statement::CloseServerStatement { line, .. } => *line, Statement::WriteContentStatement { line, .. } => *line, Statement::WaitForDurationStatement { line, .. } => *line, // Subprocess statements - Phase 4 implementation _ => 0, // Placeholder for new statement types }, column: match statement { Statement::VariableDeclaration { column, .. } => *column, Statement::Assignment { column, .. } => *column, Statement::IfStatement { column, .. } => *column, Statement::SingleLineIf { column, .. } => *column, Statement::ForEachLoop { column, .. } => *column, Statement::CountLoop { column, .. } => *column, Statement::WhileLoop { column, .. } => *column, Statement::RepeatUntilLoop { column, .. } => *column, Statement::RepeatWhileLoop { column, .. } => *column, Statement::ForeverLoop { column, .. } => *column, Statement::MainLoop { column, .. } => *column, Statement::DisplayStatement { column, .. } => *column, Statement::ActionDefinition { column, .. } => *column, Statement::ReturnStatement { column, .. } => *column, Statement::ExpressionStatement { column, .. } => *column, Statement::BreakStatement { column, .. } => *column, Statement::ContinueStatement { column, .. } => *column, Statement::ExitStatement { column, .. } => *column, Statement::OpenFileStatement { column, .. } => *column, Statement::ReadFileStatement { column, .. } => *column, Statement::WriteFileStatement { column, .. } => *column, Statement::WriteToStatement { column, .. } => *column, Statement::CloseFileStatement { column, .. } => *column, Statement::WaitForStatement { column, .. } => *column, Statement::TryStatement { column, .. } => *column, Statement::HttpGetStatement { column, .. } => *column, Statement::HttpPostStatement { column, .. } => *column, Statement::PushStatement { column, .. } => *column, // Container-related statements Statement::ContainerDefinition { column, .. } => *column, Statement::ContainerInstantiation { column, .. } => *column, Statement::InterfaceDefinition { column, .. } => *column, Statement::EventDefinition { column, .. } => *column, Statement::EventTrigger { column, .. } => *column, Statement::EventHandler { column, .. } => *column, Statement::ParentMethodCall { column, .. } => *column, Statement::CreateDirectoryStatement { column, .. } => *column, Statement::CreateFileStatement { column, .. } => *column, Statement::DeleteFileStatement { column, .. } => *column, Statement::DeleteDirectoryStatement { column, .. } => *column, Statement::PatternDefinition { column, .. } => *column, Statement::CreateListStatement { column, .. } => *column, Statement::AddToListStatement { column, .. } => *column, Statement::RemoveFromListStatement { column, .. } => *column, Statement::ClearListStatement { column, .. } => *column, Statement::MapCreation { column, .. } => *column, Statement::CreateDateStatement { column, .. } => *column, Statement::CreateTimeStatement { column, .. } => *column, Statement::ListenStatement { column, .. } => *column, Statement::WaitForRequestStatement { column, .. } => *column, Statement::RespondStatement { column, .. } => *column, Statement::RegisterSignalHandlerStatement { column, .. } => *column, Statement::StopAcceptingConnectionsStatement { column, .. } => *column, Statement::CloseServerStatement { column, .. } => *column, Statement::WriteContentStatement { column, .. } => *column, Statement::WaitForDurationStatement { column, .. } => *column, // Subprocess statements - Phase 4 implementation _ => 0, // Placeholder for new statement types }, }); stmt_nodes.push(node_idx); } } } if !stmt_nodes.is_empty() { cfg.add_edge(0, stmt_nodes[0]); } else { cfg.add_edge(0, 1); } for i in 0..stmt_nodes.len() { let node_idx = stmt_nodes[i]; match &program.statements[i] { Statement::ReturnStatement { .. } => { cfg.add_edge(node_idx, 1); } Statement::IfStatement { then_block, else_block, .. } => { let mut then_nodes = Vec::new(); for (idx, stmt) in then_block.iter().enumerate() { let then_node_idx = cfg.add_node(CFGNode::Statement { stmt_idx: program.statements.len() + idx, line: match stmt { Statement::VariableDeclaration { line, .. } => *line, Statement::Assignment { line, .. } => *line, Statement::IfStatement { line, .. } => *line, Statement::SingleLineIf { line, .. } => *line, Statement::ForEachLoop { line, .. } => *line, Statement::CountLoop { line, .. } => *line, Statement::WhileLoop { line, .. } => *line, Statement::RepeatUntilLoop { line, .. } => *line, Statement::RepeatWhileLoop { line, .. } => *line, Statement::ForeverLoop { line, .. } => *line, Statement::MainLoop { line, .. } => *line, Statement::DisplayStatement { line, .. } => *line, Statement::ActionDefinition { line, .. } => *line, Statement::ReturnStatement { line, .. } => *line, Statement::ExpressionStatement { line, .. } => *line, Statement::BreakStatement { line, .. } => *line, Statement::ContinueStatement { line, .. } => *line, Statement::ExitStatement { line, .. } => *line, Statement::OpenFileStatement { line, .. } => *line, Statement::ReadFileStatement { line, .. } => *line, Statement::WriteFileStatement { line, .. } => *line, Statement::WriteToStatement { line, .. } => *line, Statement::CloseFileStatement { line, .. } => *line, Statement::WaitForStatement { line, .. } => *line, Statement::TryStatement { line, .. } => *line, Statement::HttpGetStatement { line, .. } => *line, Statement::HttpPostStatement { line, .. } => *line, Statement::PushStatement { line, .. } => *line, // Container-related statements Statement::ContainerDefinition { line, .. } => *line, Statement::ContainerInstantiation { line, .. } => *line, Statement::InterfaceDefinition { line, .. } => *line, Statement::EventDefinition { line, .. } => *line, Statement::EventTrigger { line, .. } => *line, Statement::EventHandler { line, .. } => *line, Statement::ParentMethodCall { line, .. } => *line, Statement::CreateDirectoryStatement { line, .. } => *line, Statement::CreateFileStatement { line, .. } => *line, Statement::DeleteFileStatement { line, .. } => *line, Statement::DeleteDirectoryStatement { line, .. } => *line, Statement::PatternDefinition { line, .. } => *line, Statement::CreateListStatement { line, .. } => *line, Statement::AddToListStatement { line, .. } => *line, Statement::RemoveFromListStatement { line, .. } => *line, Statement::ClearListStatement { line, .. } => *line, Statement::MapCreation { line, .. } => *line, Statement::CreateDateStatement { line, .. } => *line, Statement::CreateTimeStatement { line, .. } => *line, Statement::ListenStatement { line, .. } => *line, Statement::WaitForRequestStatement { line, .. } => *line, Statement::RespondStatement { line, .. } => *line, Statement::RegisterSignalHandlerStatement { line, .. } => *line, Statement::StopAcceptingConnectionsStatement { line, .. } => *line, Statement::CloseServerStatement { line, .. } => *line, Statement::WriteContentStatement { line, .. } => *line, Statement::WaitForDurationStatement { line, .. } => *line, _ => 0, }, column: match stmt { Statement::VariableDeclaration { column, .. } => *column, Statement::Assignment { column, .. } => *column, Statement::IfStatement { column, .. } => *column, Statement::SingleLineIf { column, .. } => *column, Statement::ForEachLoop { column, .. } => *column, Statement::CountLoop { column, .. } => *column, Statement::WhileLoop { column, .. } => *column, Statement::RepeatUntilLoop { column, .. } => *column, Statement::RepeatWhileLoop { column, .. } => *column, Statement::ForeverLoop { column, .. } => *column, Statement::MainLoop { column, .. } => *column, Statement::DisplayStatement { column, .. } => *column, Statement::ActionDefinition { column, .. } => *column, Statement::ReturnStatement { column, .. } => *column, Statement::ExpressionStatement { column, .. } => *column, Statement::BreakStatement { column, .. } => *column, Statement::ContinueStatement { column, .. } => *column, Statement::ExitStatement { column, .. } => *column, Statement::OpenFileStatement { column, .. } => *column, Statement::ReadFileStatement { column, .. } => *column, Statement::WriteFileStatement { column, .. } => *column, Statement::WriteToStatement { column, .. } => *column, Statement::CloseFileStatement { column, .. } => *column, Statement::WaitForStatement { column, .. } => *column, Statement::TryStatement { column, .. } => *column, Statement::HttpGetStatement { column, .. } => *column, Statement::HttpPostStatement { column, .. } => *column, Statement::PushStatement { column, .. } => *column, // Container-related statements Statement::ContainerDefinition { column, .. } => *column, Statement::ContainerInstantiation { column, .. } => *column, Statement::InterfaceDefinition { column, .. } => *column, Statement::EventDefinition { column, .. } => *column, Statement::EventTrigger { column, .. } => *column, Statement::EventHandler { column, .. } => *column, Statement::ParentMethodCall { column, .. } => *column, Statement::CreateDirectoryStatement { column, .. } => *column, Statement::CreateFileStatement { column, .. } => *column, Statement::DeleteFileStatement { column, .. } => *column, Statement::DeleteDirectoryStatement { column, .. } => *column, Statement::PatternDefinition { column, .. } => *column, Statement::CreateListStatement { column, .. } => *column, Statement::AddToListStatement { column, .. } => *column, Statement::RemoveFromListStatement { column, .. } => *column, Statement::ClearListStatement { column, .. } => *column, Statement::MapCreation { column, .. } => *column, Statement::CreateDateStatement { column, .. } => *column, Statement::CreateTimeStatement { column, .. } => *column, Statement::ListenStatement { column, .. } => *column, Statement::WaitForRequestStatement { column, .. } => *column, Statement::RespondStatement { column, .. } => *column, Statement::RegisterSignalHandlerStatement { column, .. } => *column, Statement::StopAcceptingConnectionsStatement { column, .. } => { *column } Statement::CloseServerStatement { column, .. } => *column, Statement::WriteContentStatement { column, .. } => *column, Statement::WaitForDurationStatement { column, .. } => *column, _ => 0, }, }); then_nodes.push(then_node_idx); } if !then_nodes.is_empty() { cfg.add_edge(node_idx, then_nodes[0]); for j in 0..then_nodes.len() - 1 { cfg.add_edge(then_nodes[j], then_nodes[j + 1]); } } let mut else_nodes = Vec::new(); if let Some(else_stmts) = else_block { for (idx, stmt) in else_stmts.iter().enumerate() { let else_node_idx = cfg.add_node(CFGNode::Statement { stmt_idx: program.statements.len() + then_block.len() + idx, line: match stmt { Statement::VariableDeclaration { line, .. } => *line, Statement::Assignment { line, .. } => *line, Statement::IfStatement { line, .. } => *line, Statement::SingleLineIf { line, .. } => *line, Statement::ForEachLoop { line, .. } => *line, Statement::CountLoop { line, .. } => *line, Statement::WhileLoop { line, .. } => *line, Statement::RepeatUntilLoop { line, .. } => *line, Statement::RepeatWhileLoop { line, .. } => *line, Statement::ForeverLoop { line, .. } => *line, Statement::MainLoop { line, .. } => *line, Statement::DisplayStatement { line, .. } => *line, Statement::ActionDefinition { line, .. } => *line, Statement::ReturnStatement { line, .. } => *line, Statement::ExpressionStatement { line, .. } => *line, Statement::BreakStatement { line, .. } => *line, Statement::ContinueStatement { line, .. } => *line, Statement::ExitStatement { line, .. } => *line, Statement::OpenFileStatement { line, .. } => *line, Statement::ReadFileStatement { line, .. } => *line, Statement::WriteFileStatement { line, .. } => *line, Statement::CloseFileStatement { line, .. } => *line, Statement::WriteToStatement { line, .. } => *line, Statement::WaitForStatement { line, .. } => *line, Statement::TryStatement { line, .. } => *line, Statement::HttpGetStatement { line, .. } => *line, Statement::HttpPostStatement { line, .. } => *line, Statement::PushStatement { line, .. } => *line, // Container-related statements Statement::ContainerDefinition { line, .. } => *line, Statement::ContainerInstantiation { line, .. } => *line, Statement::InterfaceDefinition { line, .. } => *line, Statement::EventDefinition { line, .. } => *line, Statement::EventTrigger { line, .. } => *line, Statement::EventHandler { line, .. } => *line, Statement::ParentMethodCall { line, .. } => *line, Statement::CreateDirectoryStatement { line, .. } => *line, Statement::CreateFileStatement { line, .. } => *line, Statement::DeleteFileStatement { line, .. } => *line, Statement::DeleteDirectoryStatement { line, .. } => *line, Statement::PatternDefinition { line, .. } => *line, Statement::CreateListStatement { line, .. } => *line, Statement::AddToListStatement { line, .. } => *line, Statement::RemoveFromListStatement { line, .. } => *line, Statement::ClearListStatement { line, .. } => *line, Statement::MapCreation { line, .. } => *line, Statement::CreateDateStatement { line, .. } => *line, Statement::CreateTimeStatement { line, .. } => *line, Statement::ListenStatement { line, .. } => *line, Statement::WaitForRequestStatement { line, .. } => *line, Statement::RespondStatement { line, .. } => *line, Statement::RegisterSignalHandlerStatement { line, .. } => *line, Statement::StopAcceptingConnectionsStatement { line, .. } => *line, Statement::CloseServerStatement { line, .. } => *line, Statement::WriteContentStatement { line, .. } => *line, Statement::WaitForDurationStatement { line, .. } => *line, _ => 0, }, column: match stmt { Statement::VariableDeclaration { column, .. } => *column, Statement::Assignment { column, .. } => *column, Statement::IfStatement { column, .. } => *column, Statement::SingleLineIf { column, .. } => *column, Statement::ForEachLoop { column, .. } => *column, Statement::CountLoop { column, .. } => *column, Statement::WhileLoop { column, .. } => *column, Statement::RepeatUntilLoop { column, .. } => *column, Statement::RepeatWhileLoop { column, .. } => *column, Statement::ForeverLoop { column, .. } => *column, Statement::MainLoop { column, .. } => *column, Statement::DisplayStatement { column, .. } => *column, Statement::ActionDefinition { column, .. } => *column, Statement::ReturnStatement { column, .. } => *column, Statement::ExpressionStatement { column, .. } => *column, Statement::BreakStatement { column, .. } => *column, Statement::ContinueStatement { column, .. } => *column, Statement::ExitStatement { column, .. } => *column, Statement::OpenFileStatement { column, .. } => *column, Statement::ReadFileStatement { column, .. } => *column, Statement::WriteFileStatement { column, .. } => *column, Statement::CloseFileStatement { column, .. } => *column, Statement::WriteToStatement { column, .. } => *column, Statement::WaitForStatement { column, .. } => *column, Statement::TryStatement { column, .. } => *column, Statement::HttpGetStatement { column, .. } => *column, Statement::HttpPostStatement { column, .. } => *column, Statement::PushStatement { column, .. } => *column, // Container-related statements Statement::ContainerDefinition { column, .. } => *column, Statement::ContainerInstantiation { column, .. } => *column, Statement::InterfaceDefinition { column, .. } => *column, Statement::EventDefinition { column, .. } => *column, Statement::EventTrigger { column, .. } => *column, Statement::EventHandler { column, .. } => *column, Statement::ParentMethodCall { column, .. } => *column, Statement::CreateDirectoryStatement { column, .. } => *column, Statement::CreateFileStatement { column, .. } => *column, Statement::DeleteFileStatement { column, .. } => *column, Statement::DeleteDirectoryStatement { column, .. } => *column, Statement::PatternDefinition { column, .. } => *column, Statement::CreateListStatement { column, .. } => *column, Statement::AddToListStatement { column, .. } => *column, Statement::RemoveFromListStatement { column, .. } => *column, Statement::ClearListStatement { column, .. } => *column, Statement::MapCreation { column, .. } => *column, Statement::CreateDateStatement { column, .. } => *column, Statement::CreateTimeStatement { column, .. } => *column, Statement::ListenStatement { column, .. } => *column, Statement::WaitForRequestStatement { column, .. } => *column, Statement::RespondStatement { column, .. } => *column, Statement::RegisterSignalHandlerStatement { column, .. } => *column, Statement::StopAcceptingConnectionsStatement { column, .. } => *column, Statement::CloseServerStatement { column, .. } => *column, Statement::WriteContentStatement { column, .. } => *column, Statement::WaitForDurationStatement { column, .. } => *column, _ => 0, }, }); else_nodes.push(else_node_idx); } if !else_nodes.is_empty() { cfg.add_edge(node_idx, else_nodes[0]); for j in 0..else_nodes.len() - 1 { cfg.add_edge(else_nodes[j], else_nodes[j + 1]); } } } if i < stmt_nodes.len() - 1 { let next_idx = stmt_nodes[i + 1]; if !then_nodes.is_empty() { cfg.add_edge(*then_nodes.last().unwrap(), next_idx); } else { cfg.add_edge(node_idx, next_idx); } if !else_nodes.is_empty() { cfg.add_edge(*else_nodes.last().unwrap(), next_idx); } else if else_block.is_some() { cfg.add_edge(node_idx, next_idx); } } else { if !then_nodes.is_empty() { cfg.add_edge(*then_nodes.last().unwrap(), 1); } else { cfg.add_edge(node_idx, 1); } if !else_nodes.is_empty() { cfg.add_edge(*else_nodes.last().unwrap(), 1); } else if else_block.is_some() { cfg.add_edge(node_idx, 1); } } continue; } _ => { if i < stmt_nodes.len() - 1 { cfg.add_edge(node_idx, stmt_nodes[i + 1]); } else { cfg.add_edge(node_idx, 1); } } } } } #[allow(clippy::only_used_in_recursion)] fn check_shadowing_in_statements( &self, statements: &[Statement], current_scope: &mut HashMap, parent_scopes: &[HashMap], file_id: usize, diagnostics: &mut Vec, ) { for statement in statements { match statement { Statement::VariableDeclaration { name, line, column, .. } => { for scope in parent_scopes.iter() { if let Some(&(def_line, def_col)) = scope.get(name) { diagnostics.push(WflDiagnostic::new( Severity::Warning, format!( "Variable '{name}' shadows another variable with the same name" ), Some(format!( "Previously defined at line {def_line}, column {def_col}" )), "ANALYZE-SHADOW".to_string(), file_id, *line, *column, None, )); break; } } if let Some(&(def_line, def_col)) = current_scope.get(name) { diagnostics.push(WflDiagnostic::new( Severity::Warning, format!( "Variable '{name}' shadows another variable with the same name" ), Some(format!( "Previously defined at line {def_line}, column {def_col}" )), "ANALYZE-SHADOW".to_string(), file_id, *line, *column, None, )); } current_scope.insert(name.clone(), (*line, *column)); } Statement::ActionDefinition { parameters, body, .. } => { let mut action_scope = HashMap::new(); for param in parameters { action_scope.insert(param.name.clone(), (0, 0)); // We don't have line/column for parameters yet } let mut new_parent_scopes = parent_scopes.to_vec(); new_parent_scopes.push(current_scope.clone()); self.check_shadowing_in_statements( body, &mut action_scope, &new_parent_scopes, file_id, diagnostics, ); } Statement::IfStatement { then_block, else_block, .. } => { let mut then_scope = HashMap::new(); let mut new_parent_scopes = parent_scopes.to_vec(); new_parent_scopes.push(current_scope.clone()); self.check_shadowing_in_statements( then_block, &mut then_scope, &new_parent_scopes, file_id, diagnostics, ); if let Some(else_stmts) = else_block { let mut else_scope = HashMap::new(); self.check_shadowing_in_statements( else_stmts, &mut else_scope, &new_parent_scopes, file_id, diagnostics, ); } } Statement::WhileLoop { body, .. } | Statement::ForEachLoop { body, .. } | Statement::CountLoop { body, .. } => { let mut loop_scope = HashMap::new(); let mut new_parent_scopes = parent_scopes.to_vec(); new_parent_scopes.push(current_scope.clone()); self.check_shadowing_in_statements( body, &mut loop_scope, &new_parent_scopes, file_id, diagnostics, ); } _ => {} } } } #[allow(clippy::only_used_in_recursion)] fn check_all_paths_return(&self, statements: &[Statement], has_return: &mut bool) -> bool { if statements.is_empty() { return false; } for (i, statement) in statements.iter().enumerate() { match statement { Statement::ReturnStatement { .. } => { *has_return = true; return i == statements.len() - 1; } Statement::IfStatement { then_block, else_block, .. } => { let then_returns = self.check_all_paths_return(then_block, has_return); let else_returns = if let Some(else_stmts) = else_block { self.check_all_paths_return(else_stmts, has_return) } else { false }; if then_returns && else_returns && i == statements.len() - 1 { return true; } } _ => {} } } false } } #[cfg(test)] mod tests { use super::*; use crate::parser::ast::{Literal, Operator}; use std::sync::Arc; #[test] fn test_unused_variable() { let program = Program { statements: vec![ Statement::VariableDeclaration { name: "unused".to_string(), value: Expression::Literal(Literal::Integer(10), 1, 1), is_constant: false, line: 1, column: 1, }, Statement::VariableDeclaration { name: "used".to_string(), value: Expression::Literal(Literal::Integer(20), 2, 1), is_constant: false, line: 2, column: 1, }, Statement::DisplayStatement { value: Expression::Variable("used".to_string(), 3, 9), line: 3, column: 1, }, ], }; let analyzer = Analyzer::new(); let file_id = 0; let diagnostics = analyzer.check_unused_variables(&program, file_id); assert_eq!(diagnostics.len(), 1); assert!(diagnostics[0].message.contains("unused")); assert_eq!(diagnostics[0].code, "ANALYZE-UNUSED"); } #[test] fn constructor_argument_variables_are_used() { let input = "store headers as 1\nstore suffix as \"h\"\nstore dead as 0\ncreate new K with headers and \"a\" with suffix as k:\nend\n"; let tokens = crate::lexer::lex_wfl_with_positions(input); let program = crate::parser::Parser::new(&tokens).parse().unwrap(); let diagnostics = Analyzer::new().check_unused_variables(&program, 0); assert_eq!(diagnostics.len(), 1, "{diagnostics:?}"); assert!(diagnostics[0].message.contains("dead")); } #[test] fn test_tls_operands_are_used_but_unreferenced_variables_remain_unused() { let input = r#" store default_cert as "default.pem" store default_key as "default.key" store named_cert as "one.pem" store named_key as "one.key" store hostname as "one.test" store unused_tls_setting as "unused" listen on port 0 secured with certificate default_cert and key default_key and certificate named_cert and key named_key for hostname as secure_server close server secure_server "#; let tokens = crate::lexer::lex_wfl_with_positions(input); let program = crate::parser::Parser::new(&tokens).parse().unwrap(); let diagnostics = Analyzer::new().check_unused_variables(&program, 0); assert_eq!(diagnostics.len(), 1, "{diagnostics:?}"); assert_eq!(diagnostics[0].code, "ANALYZE-UNUSED"); assert!(diagnostics[0].message.contains("unused_tls_setting")); } #[test] fn test_streaming_statement_variables_are_not_reported_unused() { // Variables referenced only inside the streaming/incremental-read // statements must count as used — otherwise a program that opens a // stream from a URL/body variable gets a false unused warning. Exercise // every new arm and every metadata operand: // - HttpStreamStatement: url, method, body // - WaitForNextChunkStatement / WaitForNextLineStatement: source // - StartStreamingResponseStatement: status, content type // and a genuinely-unused variable to prove the pass still flags real // dead code (negative assertion). let input = "store my_url as \"http://example.com/s\"\n\ store my_method as \"POST\"\n\ store my_body as \"payload\"\n\ open url at my_url with method my_method and body my_body and stream response as upstream\n\ wait for next chunk from upstream as ch\n\ wait for next line from upstream as ln\n\ store st as 200\n\ store ctype as \"application/x-ndjson\"\n\ start streaming response to req with status st and content type ctype as out\n\ write line \"x\" to out\n\ store dead as \"never read\"\n\ display ch\n\ display ln"; let tokens = crate::lexer::lex_wfl_with_positions(input); let program = crate::parser::Parser::new(&tokens).parse().unwrap(); let analyzer = Analyzer::new(); let diagnostics = analyzer.check_unused_variables(&program, 0); // The only unused variable is `dead`; every streaming operand counts as // used (a missing arm would surface `my_url`/`my_method`/`my_body`/ // `upstream`/`st`/`ctype` here too). assert_eq!( diagnostics.len(), 1, "expected only `dead` unused, got: {diagnostics:?}" ); assert!( diagnostics[0].message.contains("dead"), "expected the unused diagnostic to name `dead`, got: {:?}", diagnostics[0].message ); } #[test] fn test_legacy_flush_binding_and_fallback_operands_are_not_reported_unused() { // `replace ... in ...` rewrites the expression AST and discards its // seeded `flush cache` leaf. The explicit legacy-binding metadata must // therefore count that declaration as used independently of the // rewritten target/fallback expression. let input = "create pattern letter_a:\n\ \x20\x20\x20\x20\"a\"\n\ end pattern\n\ store flush cache as 1\n\ store replacement_value as \"z\"\n\ store text_value as \"abc\"\n\ flush cache replace letter_a with replacement_value in text_value\n\ store dead as \"never read\""; let tokens = crate::lexer::lex_wfl_with_positions(input); let program = crate::parser::Parser::new(&tokens).parse().unwrap(); let analyzer = Analyzer::new(); let diagnostics = analyzer.check_unused_variables(&program, 0); assert_eq!( diagnostics.len(), 1, "expected only `dead` unused, got: {diagnostics:?}" ); assert!( diagnostics[0].message.contains("dead"), "the legacy binding and fallback operands must count as used; got: {diagnostics:?}" ); } #[test] fn test_respond_headers_expression_marks_variable_used() { // Regression: a variable referenced only in the // `respond ... and headers ` clause must be marked used, not // falsely reported as unused. RFC 10008 servers build a header map // (Accept-Query, Content-Location) and pass it straight to respond. let program = Program { statements: vec![ Statement::VariableDeclaration { name: "response_headers".to_string(), value: Expression::Literal(Literal::Integer(1), 1, 1), is_constant: false, line: 1, column: 1, }, Statement::RespondStatement { request: Expression::Variable("req".to_string(), 2, 1), content: Expression::Literal(Literal::String(Arc::from("ok")), 2, 1), status: None, content_type: None, headers: Some(Expression::Variable("response_headers".to_string(), 2, 30)), line: 2, column: 1, }, ], }; let analyzer = Analyzer::new(); let diagnostics = analyzer.check_unused_variables(&program, 0); assert!( diagnostics .iter() .all(|d| !d.message.contains("response_headers")), "response_headers used only in `respond ... and headers` must not be flagged unused: {diagnostics:?}" ); } #[test] fn test_inconsistent_returns() { let program = Program { statements: vec![Statement::ActionDefinition { name: "inconsistent".to_string(), parameters: vec![], body: vec![Statement::IfStatement { condition: Expression::Literal(Literal::Boolean(true), 2, 5), then_block: vec![Statement::ReturnStatement { value: Some(Expression::Literal(Literal::Integer(1), 3, 9)), line: 3, column: 5, }], else_block: Some(vec![Statement::DisplayStatement { value: Expression::Literal(Literal::String(Arc::from("No return")), 5, 9), line: 5, column: 5, }]), line: 2, column: 1, }], return_type: Some(Type::Number), line: 1, column: 1, }], }; let analyzer = Analyzer::new(); let file_id = 0; let diagnostics = analyzer.check_inconsistent_returns(&program, file_id); assert_eq!(diagnostics.len(), 1); assert!(diagnostics[0].message.contains("inconsistent")); assert_eq!(diagnostics[0].code, "ANALYZE-RETURN"); } #[test] fn test_loop_variable_usage() { // Test that variables used in different types of loop conditions are correctly marked as used let program = Program { statements: vec![ // Variable declaration Statement::VariableDeclaration { name: "counter".to_string(), value: Expression::Literal(Literal::Integer(1), 1, 1), is_constant: false, line: 1, column: 1, }, // RepeatWhileLoop using the counter variable Statement::RepeatWhileLoop { condition: Expression::BinaryOperation { left: Box::new(Expression::Variable("counter".to_string(), 2, 14)), operator: Operator::LessThanOrEqual, right: Box::new(Expression::Literal(Literal::Integer(5), 2, 36)), line: 2, column: 14, }, body: vec![], line: 2, column: 1, }, ], }; let analyzer = Analyzer::new(); let file_id = 0; let diagnostics = analyzer.check_unused_variables(&program, file_id); // Counter should be marked as used, so no diagnostics should be reported assert_eq!( diagnostics.len(), 0, "Expected no unused variable diagnostics" ); // Test with RepeatUntilLoop let program_until = Program { statements: vec![ Statement::VariableDeclaration { name: "counter".to_string(), value: Expression::Literal(Literal::Integer(1), 1, 1), is_constant: false, line: 1, column: 1, }, Statement::RepeatUntilLoop { condition: Expression::BinaryOperation { left: Box::new(Expression::Variable("counter".to_string(), 2, 14)), operator: Operator::GreaterThan, right: Box::new(Expression::Literal(Literal::Integer(5), 2, 32)), line: 2, column: 14, }, body: vec![], line: 2, column: 1, }, ], }; let diagnostics_until = analyzer.check_unused_variables(&program_until, file_id); assert_eq!( diagnostics_until.len(), 0, "Expected no unused variable diagnostics for RepeatUntilLoop" ); } #[test] fn test_variable_used_in_array_access() { // This test reproduces the false positive for 'last_index' in args_comprehensive.wfl // where a variable is declared and immediately used in array access within nested conditionals let program = Program { statements: vec![ Statement::VariableDeclaration { name: "arg_count".to_string(), value: Expression::Literal(Literal::Integer(5), 1, 1), is_constant: false, line: 1, column: 1, }, Statement::VariableDeclaration { name: "args".to_string(), value: Expression::Literal( Literal::List(vec![ Expression::Literal(Literal::String(Arc::from("a")), 1, 1), Expression::Literal(Literal::String(Arc::from("b")), 1, 1), Expression::Literal(Literal::String(Arc::from("c")), 1, 1), ]), 2, 1, ), is_constant: false, line: 2, column: 1, }, // Triple-nested conditional structure similar to args_comprehensive.wfl Statement::IfStatement { condition: Expression::BinaryOperation { left: Box::new(Expression::Variable("arg_count".to_string(), 3, 10)), operator: Operator::Equals, right: Box::new(Expression::Literal(Literal::Integer(0), 3, 20)), line: 3, column: 10, }, then_block: vec![Statement::DisplayStatement { value: Expression::Literal(Literal::String(Arc::from("No args")), 4, 1), line: 4, column: 1, }], else_block: Some(vec![Statement::IfStatement { condition: Expression::BinaryOperation { left: Box::new(Expression::Variable("arg_count".to_string(), 5, 10)), operator: Operator::Equals, right: Box::new(Expression::Literal(Literal::Integer(1), 5, 20)), line: 5, column: 10, }, then_block: vec![Statement::DisplayStatement { value: Expression::Literal(Literal::String(Arc::from("One arg")), 6, 1), line: 6, column: 1, }], else_block: Some(vec![Statement::IfStatement { condition: Expression::BinaryOperation { left: Box::new(Expression::Variable( "arg_count".to_string(), 7, 10, )), operator: Operator::Equals, right: Box::new(Expression::Literal(Literal::Integer(2), 7, 20)), line: 7, column: 10, }, then_block: vec![Statement::DisplayStatement { value: Expression::Literal( Literal::String(Arc::from("Two args")), 8, 1, ), line: 8, column: 1, }], else_block: Some(vec![ Statement::VariableDeclaration { name: "last_index".to_string(), value: Expression::BinaryOperation { left: Box::new(Expression::Variable( "arg_count".to_string(), 9, 30, )), operator: Operator::Minus, right: Box::new(Expression::Literal( Literal::Integer(1), 9, 40, )), line: 9, column: 30, }, is_constant: false, line: 9, column: 1, }, Statement::DisplayStatement { value: Expression::IndexAccess { collection: Box::new(Expression::Variable( "args".to_string(), 10, 20, )), index: Box::new(Expression::Variable( "last_index".to_string(), 10, 25, )), line: 10, column: 20, }, line: 10, column: 1, }, ]), line: 7, column: 1, }]), line: 5, column: 1, }]), line: 3, column: 1, }, ], }; let analyzer = Analyzer::new(); let file_id = 0; let diagnostics = analyzer.check_unused_variables(&program, file_id); // last_index should NOT be reported as unused since it's used in the IndexAccess // This test currently FAILS because of the bug assert!( !diagnostics.iter().any(|d| d.message.contains("last_index")), "last_index should not be reported as unused when used in array access" ); } // ===== random_seed-in-crypto-context lint (ANALYZE-SECURITY) ===== fn parse_program(input: &str) -> Program { let tokens = crate::lexer::lex_wfl_with_positions(input); crate::parser::Parser::new(&tokens).parse().unwrap() } #[test] fn test_random_seed_flagged_in_crypto_context() { // random_seed next to a crypto builtin is an error: it makes the CSPRNG predictable. let program = parse_program( "store x as random_seed of 42\nstore h as hash_password of \"pw\"\ndisplay h", ); let analyzer = Analyzer::new(); let diagnostics = analyzer.check_insecure_rng_seeding(&program, 0); assert_eq!(diagnostics.len(), 1); assert_eq!(diagnostics[0].code, "ANALYZE-SECURITY"); assert_eq!(diagnostics[0].severity, Severity::Error); assert!(diagnostics[0].message.contains("random_seed")); } #[test] fn test_random_seed_flagged_inside_action_body() { // The walker must reach into action bodies, not only top-level statements. let program = parse_program( "define action called make_token:\n store s as random_seed of 1\n store t as secure_random_bytes of 16\n give back t\nend action", ); let analyzer = Analyzer::new(); let diagnostics = analyzer.check_insecure_rng_seeding(&program, 0); assert_eq!(diagnostics.len(), 1); assert_eq!(diagnostics[0].code, "ANALYZE-SECURITY"); } #[test] fn test_random_seed_allowed_without_crypto() { // Seeding is legitimate in ordinary non-security code (simulations, reproducible demos). let program = parse_program("store s as random_seed of 42\nstore r as random\ndisplay r"); let analyzer = Analyzer::new(); let diagnostics = analyzer.check_insecure_rng_seeding(&program, 0); assert!(diagnostics.is_empty()); } #[test] fn test_crypto_without_random_seed_is_clean() { let program = parse_program("store h as hash_password of \"pw\"\ndisplay h"); let analyzer = Analyzer::new(); let diagnostics = analyzer.check_insecure_rng_seeding(&program, 0); assert!(diagnostics.is_empty()); } #[test] fn test_sha256_checksum_does_not_trigger_lint() { // sha256 is a general-purpose hash (checksums/content-addressing), not an // auth signal, so hashing + seeding for a reproducible run must not fire. let program = parse_program("store c as sha256 of \"data\"\nstore s as random_seed of 1\ndisplay c"); let analyzer = Analyzer::new(); let diagnostics = analyzer.check_insecure_rng_seeding(&program, 0); assert!(diagnostics.is_empty()); } #[test] fn test_wflhash_checksum_does_not_trigger_lint() { let program = parse_program( "store c as wflhash256 of \"data\"\nstore s as random_seed of 1\ndisplay c", ); let analyzer = Analyzer::new(); let diagnostics = analyzer.check_insecure_rng_seeding(&program, 0); assert!(diagnostics.is_empty()); } #[test] fn test_random_seed_flagged_inside_respond_statement() { // A web handler that responds with a freshly generated token and also // seeds the RNG must be flagged: the walker has to descend into `respond`. let program = parse_program( "store s as random_seed of 1\nrespond to req with secure_random_bytes of 16", ); let analyzer = Analyzer::new(); let diagnostics = analyzer.check_insecure_rng_seeding(&program, 0); assert_eq!(diagnostics.len(), 1); assert_eq!(diagnostics[0].code, "ANALYZE-SECURITY"); } #[test] fn rng_security_ingredients_reports_each_half_independently() { // The REPL blocks the seed+crypto combination across separate submissions // by tracking each half on its own, so the ingredient scan must report the // two independently (unlike the file lint, which only fires on both). let seed_only = rng_security_ingredients(&parse_program("store s as random_seed of 42")); assert!(seed_only.seeds_rng()); assert!(!seed_only.uses_security_builtin()); let crypto_only = rng_security_ingredients(&parse_program("store t as secure_random_bytes of 16")); assert!(!crypto_only.seeds_rng()); assert!(crypto_only.uses_security_builtin()); // General-purpose hashes are not "security-sensitive" (matching the lint's // SECURITY_SENSITIVE_BUILTINS), so hashing + seeding is not an ingredient pair. let checksum = rng_security_ingredients(&parse_program( "store c as sha256 of \"data\"\nstore s as random_seed of 1", )); assert!(checksum.seeds_rng()); assert!(!checksum.uses_security_builtin()); // Call sites are captured (used to place the caret at the current line). let both = rng_security_ingredients(&parse_program( "store t as secure_random_bytes of 16\nstore s as random_seed of 1", )); assert!(both.seed_site.is_some()); assert!(both.security_site.is_some()); } }