1use std::collections::{HashMap, HashSet, VecDeque};
19use std::path::PathBuf;
20
21use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
22use crate::diagnostics::{
23 Applicability, Diagnostic, DiagnosticsCollector, Help, Phase, Severity, Suggestion,
24};
25use crate::symbol::LocalEntry;
26use crate::types::BaseVarType;
27
28pub fn run_lints(
29 scripts: &[CompiledScript],
30 source_cache: Option<crate::SourceProvider<'_>>,
31) -> DiagnosticsCollector {
32 let chunk_diags = crate::parallel_chunks(scripts, move |chunk| {
40 let mut diags = DiagnosticsCollector::new();
41 for script in chunk {
42 check_unused_locals(script, source_cache, &mut diags);
43 check_unreachable_code(script, source_cache, &mut diags);
44 }
45 diags
46 });
47 let mut diags = DiagnosticsCollector::new();
48 for d in chunk_diags {
49 diags.merge(d);
50 }
51 diags
52}
53
54fn check_unused_locals(
63 script: &CompiledScript,
64 source_cache: Option<crate::SourceProvider<'_>>,
65 diagnostics: &mut DiagnosticsCollector,
66) {
67 let mut int_reads: HashSet<i32> = HashSet::new();
69 let mut string_reads: HashSet<i32> = HashSet::new();
70 let mut long_reads: HashSet<i32> = HashSet::new();
71 let mut array_touched: HashSet<i32> = HashSet::new();
73
74 let mut int_first_write_line: HashMap<i32, usize> = HashMap::new();
76 let mut string_first_write_line: HashMap<i32, usize> = HashMap::new();
77 let mut long_first_write_line: HashMap<i32, usize> = HashMap::new();
78 let mut array_first_def_line: HashMap<i32, usize> = HashMap::new();
79
80 for (i, instr) in script.instructions.iter().enumerate() {
81 let id = match &instr.operand {
82 Operand::Int(v) => *v,
83 _ => continue,
84 };
85 let line = resolve_line(&script.instructions, i);
86 match instr.opcode {
87 Opcode::PushIntLocal => {
88 int_reads.insert(id);
89 }
90 Opcode::PopIntLocal => {
91 int_first_write_line.entry(id).or_insert(line);
92 }
93 Opcode::PushStringLocal => {
94 string_reads.insert(id);
95 }
96 Opcode::PopStringLocal => {
97 string_first_write_line.entry(id).or_insert(line);
98 }
99 Opcode::PushLongLocal => {
100 long_reads.insert(id);
101 }
102 Opcode::PopLongLocal => {
103 long_first_write_line.entry(id).or_insert(line);
104 }
105 Opcode::PushArrayInt | Opcode::PopArrayInt => {
106 array_touched.insert(id);
107 }
108 Opcode::DefineArray => {
109 array_first_def_line.entry(id).or_insert(line);
110 }
111 _ => {}
112 }
113 }
114
115 let mut header_line_cache: Option<usize> = None;
122
123 let mut int_slot_counter: i32 = 0;
126 let mut string_slot_counter: i32 = 0;
127 let mut long_slot_counter: i32 = 0;
128 let mut array_slot_counter: i32 = 0;
129
130 for entry in script.local_table.entries() {
131 let LocalEntry {
132 name,
133 var_type,
134 is_param,
135 is_array,
136 } = entry;
137 let is_param = *is_param;
138 let is_array = *is_array;
139 let suppress = name.starts_with('_');
140
141 if is_array {
142 let slot = array_slot_counter;
143 array_slot_counter += 1;
144 if suppress || array_touched.contains(&slot) {
145 continue;
146 }
147 let line = array_first_def_line.get(&slot).copied().unwrap_or_else(|| {
148 *header_line_cache.get_or_insert_with(|| compute_header_line(script, source_cache))
149 });
150 emit_unused_local(
151 script,
152 source_cache,
153 diagnostics,
154 name,
155 "array",
156 is_param,
157 line,
158 );
159 continue;
160 }
161
162 match var_type.base_type() {
167 BaseVarType::Integer => {
168 let slot = int_slot_counter;
169 int_slot_counter += 1;
170 if suppress || int_reads.contains(&slot) {
171 continue;
172 }
173 let line = int_first_write_line.get(&slot).copied().unwrap_or_else(|| {
174 *header_line_cache
175 .get_or_insert_with(|| compute_header_line(script, source_cache))
176 });
177 emit_unused_local(
178 script,
179 source_cache,
180 diagnostics,
181 name,
182 "int",
183 is_param,
184 line,
185 );
186 }
187 BaseVarType::String => {
188 let slot = string_slot_counter;
189 string_slot_counter += 1;
190 if suppress || string_reads.contains(&slot) {
191 continue;
192 }
193 let line = string_first_write_line
194 .get(&slot)
195 .copied()
196 .unwrap_or_else(|| {
197 *header_line_cache
198 .get_or_insert_with(|| compute_header_line(script, source_cache))
199 });
200 emit_unused_local(
201 script,
202 source_cache,
203 diagnostics,
204 name,
205 "string",
206 is_param,
207 line,
208 );
209 }
210 BaseVarType::Long => {
211 let slot = long_slot_counter;
212 long_slot_counter += 1;
213 if suppress || long_reads.contains(&slot) {
214 continue;
215 }
216 let line = long_first_write_line
217 .get(&slot)
218 .copied()
219 .unwrap_or_else(|| {
220 *header_line_cache
221 .get_or_insert_with(|| compute_header_line(script, source_cache))
222 });
223 emit_unused_local(
224 script,
225 source_cache,
226 diagnostics,
227 name,
228 "long",
229 is_param,
230 line,
231 );
232 }
233 }
234 }
235}
236
237fn emit_unused_local(
238 script: &CompiledScript,
239 source_cache: Option<crate::SourceProvider<'_>>,
240 diagnostics: &mut DiagnosticsCollector,
241 raw_name: &str,
242 ty: &str,
243 is_param: bool,
244 line: usize,
245) {
246 let name = format!("${}", raw_name);
249 let (message, help_text) = if is_param {
250 (
251 format!(
252 "Parameter `{}` ({}) is declared but never read in this script body.",
253 name, ty
254 ),
255 format!(
256 "If `{0}` is intentionally part of the signature (e.g. to \
257 match a label family), prefix its name with an underscore \
258 or remove it from the header if no caller relies on the \
259 position.",
260 name
261 ),
262 )
263 } else {
264 (
265 format!("Local `{}` ({}) is assigned but never read.", name, ty),
266 format!(
267 "Remove the `def_{}` / assignment, or use `{}` before it \
268 gets overwritten.",
269 ty, name
270 ),
271 )
272 };
273
274 let _ = source_cache;
280 let help = Help {
281 message: help_text,
282 suggestions: Vec::new(),
283 applicability: Applicability::MaybeIncorrect,
284 };
285
286 let mut diag = Diagnostic {
287 file: PathBuf::from(&script.source_path),
288 line,
289 column: 0,
290 message,
291 severity: Severity::Warning,
292 phase: Phase::PointerCheck, help: Vec::new(),
294 };
295 diag.help.push(help);
296 diagnostics.add(diag);
297}
298
299fn check_unreachable_code(
309 script: &CompiledScript,
310 source_cache: Option<crate::SourceProvider<'_>>,
311 diagnostics: &mut DiagnosticsCollector,
312) {
313 let instrs = &script.instructions;
314 if instrs.is_empty() {
315 return;
316 }
317
318 let mut instr_to_node: Vec<u32> = vec![u32::MAX; instrs.len()];
324 let mut node_instr: Vec<usize> = Vec::new();
325 for (i, instr) in instrs.iter().enumerate() {
326 if instr.opcode == Opcode::LineNumber {
327 continue;
328 }
329 instr_to_node[i] = node_instr.len() as u32;
330 node_instr.push(i);
331 }
332 if node_instr.is_empty() {
333 return;
334 }
335
336 let mut reachable = vec![false; node_instr.len()];
345 reachable[0] = true;
346 let mut queue: VecDeque<usize> = VecDeque::from([0]);
347 while let Some(order_idx) = queue.pop_front() {
348 let instr = &instrs[node_instr[order_idx]];
349
350 let is_terminal = matches!(
351 instr.opcode,
352 Opcode::Branch | Opcode::Return | Opcode::Jump | Opcode::JumpWithParams
353 );
354
355 match instr.opcode {
357 Opcode::Branch
358 | Opcode::BranchNot
359 | Opcode::BranchEquals
360 | Opcode::BranchLessThan
361 | Opcode::BranchGreaterThan
362 | Opcode::BranchLessThanOrEquals
363 | Opcode::BranchGreaterThanOrEquals
364 | Opcode::LongBranchNot
365 | Opcode::LongBranchEquals
366 | Opcode::LongBranchLessThan
367 | Opcode::LongBranchGreaterThan
368 | Opcode::LongBranchLessThanOrEquals
369 | Opcode::LongBranchGreaterThanOrEquals
370 | Opcode::ObjBranchEquals
371 | Opcode::ObjBranchNot
372 | Opcode::BranchIfTrue
373 | Opcode::BranchIfFalse => {
374 if let Operand::JumpTarget(target) = &instr.operand
375 && let Some(tnode) = resolve_target(*target, instrs, &instr_to_node)
376 && !reachable[tnode]
377 {
378 reachable[tnode] = true;
379 queue.push_back(tnode);
380 }
381 }
382 Opcode::Switch => {
383 if let Operand::SwitchTable(tbl_idx) = &instr.operand {
384 let cases = &script.switch_tables[*tbl_idx as usize];
385 for &(_, target) in cases.iter() {
386 if let Some(tnode) = resolve_target(target, instrs, &instr_to_node)
387 && !reachable[tnode]
388 {
389 reachable[tnode] = true;
390 queue.push_back(tnode);
391 }
392 }
393 }
394 }
395 _ => {}
396 }
397
398 if !is_terminal && order_idx + 1 < node_instr.len() {
400 let m = order_idx + 1;
401 if !reachable[m] {
402 reachable[m] = true;
403 queue.push_back(m);
404 }
405 }
406 }
407
408 let mut reported_lines: HashSet<usize> = HashSet::new();
411 for (i, instr) in instrs.iter().enumerate() {
412 let line = match (instr.opcode, &instr.operand) {
413 (Opcode::LineNumber, Operand::Int(n)) => *n as usize,
414 _ => continue,
415 };
416 let mut j = i + 1;
417 let tnode = loop {
418 if j >= instrs.len() {
419 break None;
420 }
421 if instrs[j].opcode != Opcode::LineNumber {
422 let n = instr_to_node[j];
423 break if n == u32::MAX {
424 None
425 } else {
426 Some(n as usize)
427 };
428 }
429 j += 1;
430 };
431 let tnode = match tnode {
432 Some(n) => n,
433 None => continue,
434 };
435 if reachable[tnode] {
436 continue;
437 }
438 if !reported_lines.insert(line) {
439 continue;
440 }
441 emit_unreachable(script, source_cache, diagnostics, line);
442 }
443}
444
445fn emit_unreachable(
446 script: &CompiledScript,
447 source_cache: Option<crate::SourceProvider<'_>>,
448 diagnostics: &mut DiagnosticsCollector,
449 line: usize,
450) {
451 let message = "Unreachable code: this line cannot be executed because control \
452 flow never reaches it (a preceding `return`, `@jump`, or \
453 unconditional branch prevents fallthrough)."
454 .to_string();
455
456 let mut suggestions: Vec<Suggestion> = Vec::new();
457 if let Some(cache) = source_cache
458 && let Some(src) = cache.get(&script.source_path)
459 && nth_source_line(&src, line).is_some()
460 {
461 suggestions.push(Suggestion {
462 file: PathBuf::from(&script.source_path),
463 line_range: (line, line),
464 replacement: String::new(), label: Some("remove the unreachable statement".to_string()),
466 });
467 }
468
469 let help = Help {
470 message: "Remove the dead statement, or move it before the \
471 preceding terminal instruction if it was meant to run."
472 .to_string(),
473 suggestions,
474 applicability: Applicability::MaybeIncorrect,
475 };
476
477 let mut diag = Diagnostic {
478 file: PathBuf::from(&script.source_path),
479 line,
480 column: 0,
481 message,
482 severity: Severity::Warning,
483 phase: Phase::PointerCheck,
484 help: Vec::new(),
485 };
486 diag.help.push(help);
487 diagnostics.add(diag);
488}
489
490fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
495 for i in (0..=instr_idx).rev() {
496 if instructions[i].opcode == Opcode::LineNumber
497 && let Operand::Int(line) = instructions[i].operand
498 {
499 return line as usize;
500 }
501 }
502 0
503}
504
505fn nth_source_line(src: &str, line_no: usize) -> Option<&str> {
506 if line_no == 0 {
507 return None;
508 }
509 src.lines().nth(line_no - 1)
510}
511
512fn resolve_target(
513 mut target: usize,
514 instrs: &[Instruction],
515 instr_to_node: &[u32],
516) -> Option<usize> {
517 while target < instrs.len() && instrs[target].opcode == Opcode::LineNumber {
518 target += 1;
519 }
520 if target < instrs.len() {
521 let n = instr_to_node[target];
522 if n != u32::MAX {
523 return Some(n as usize);
524 }
525 }
526 None
527}
528
529fn compute_header_line(
535 script: &CompiledScript,
536 source_cache: Option<crate::SourceProvider<'_>>,
537) -> usize {
538 let short_name = script
539 .name
540 .trim_start_matches('[')
541 .trim_end_matches(']')
542 .split_once(',')
543 .map(|(_, n)| n)
544 .unwrap_or(script.name.as_str());
545 let first_body_line = script
546 .instructions
547 .iter()
548 .find_map(|i| match (i.opcode, &i.operand) {
549 (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
550 _ => None,
551 })
552 .unwrap_or(1);
553 source_cache
554 .and_then(|c| c.get(&script.source_path))
555 .and_then(|src| find_header_line(&src, &script.trigger, short_name))
556 .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1))
557}
558
559fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
562 let prefix = format!("[{},{}]", trigger, name);
563 let prefix_with_params = format!("[{},{}](", trigger, name);
564 for (i, line) in src.lines().enumerate() {
565 let trimmed = line.trim_start();
566 if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
567 return Some(i + 1);
568 }
569 }
570 None
571}
572
573#[cfg(test)]
578mod tests {
579 use super::*;
580 use crate::bytecode::{Instruction, Opcode, Operand};
581 use crate::symbol::LocalEntry;
582 use crate::types::Type;
583
584 fn empty_script(name: &str) -> CompiledScript {
585 let mut s = CompiledScript::new(format!("[label,{}]", name), 0);
586 s.trigger = "label".to_string();
587 s.source_path = "/virt/test.rs2".to_string();
588 s
589 }
590
591 fn push_local_entry(
592 s: &mut CompiledScript,
593 name: &str,
594 var_type: Type,
595 is_param: bool,
596 is_array: bool,
597 ) {
598 s.local_table.all.push(LocalEntry {
599 name: name.to_string(),
600 var_type,
601 is_param,
602 is_array,
603 });
604 }
605
606 #[test]
611 fn unused_int_local_is_reported() {
612 let mut script = empty_script("foo");
614 push_local_entry(&mut script, "x", Type::Int, false, false);
615 script.instructions = vec![
616 Instruction::new(Opcode::LineNumber, Operand::Int(2)),
617 Instruction::push_int(5),
618 Instruction::pop_int_local(0),
619 Instruction::simple(Opcode::Return),
620 ];
621
622 let scripts = [script];
623 let mut diags = DiagnosticsCollector::new();
624 check_unused_locals(&scripts[0], None, &mut diags);
625
626 let warnings: Vec<_> = diags
627 .diagnostics()
628 .iter()
629 .filter(|d| d.severity == Severity::Warning)
630 .collect();
631 assert_eq!(warnings.len(), 1, "expected one unused-local warning");
632 assert!(
633 warnings[0].message.contains("$x"),
634 "message should name $x: {}",
635 warnings[0].message
636 );
637 assert_eq!(warnings[0].line, 2);
638 }
639
640 #[test]
641 fn read_then_written_int_local_is_ok() {
642 let mut script = empty_script("foo");
644 push_local_entry(&mut script, "x", Type::Int, false, false);
645 push_local_entry(&mut script, "y", Type::Int, false, false);
646 script.instructions = vec![
647 Instruction::new(Opcode::LineNumber, Operand::Int(2)),
648 Instruction::push_int(5),
649 Instruction::pop_int_local(0),
650 Instruction::new(Opcode::LineNumber, Operand::Int(3)),
651 Instruction::push_int_local(0), Instruction::pop_int_local(1), Instruction::simple(Opcode::Return),
654 ];
655
656 let mut diags = DiagnosticsCollector::new();
657 check_unused_locals(&script, None, &mut diags);
658 let warnings: Vec<_> = diags
659 .diagnostics()
660 .iter()
661 .filter(|d| d.severity == Severity::Warning)
662 .collect();
663 assert_eq!(warnings.len(), 1, "only $y should warn");
664 assert!(warnings[0].message.contains("$y"));
665 }
666
667 #[test]
668 fn unused_parameter_is_reported_with_param_wording() {
669 let mut script = empty_script("foo");
670 script.trigger = "label".to_string();
671 push_local_entry(&mut script, "unused", Type::Int, true, false);
672 script.int_arg_count = 1;
673 script.int_local_count = 1;
674 script.instructions = vec![
675 Instruction::new(Opcode::LineNumber, Operand::Int(1)),
676 Instruction::simple(Opcode::Return),
677 ];
678
679 let mut diags = DiagnosticsCollector::new();
680 check_unused_locals(&script, None, &mut diags);
681 let warnings: Vec<_> = diags
682 .diagnostics()
683 .iter()
684 .filter(|d| d.severity == Severity::Warning)
685 .collect();
686 assert_eq!(warnings.len(), 1);
687 assert!(
688 warnings[0].message.contains("Parameter"),
689 "message should use parameter wording: {}",
690 warnings[0].message
691 );
692 }
693
694 #[test]
695 fn string_and_long_locals_tracked_independently() {
696 let mut script = empty_script("foo");
697 push_local_entry(&mut script, "s", Type::String, false, false);
698 push_local_entry(&mut script, "l", Type::Long, false, false);
699 let hi = script.intern_str("hi".to_string());
700 script.instructions = vec![
701 Instruction::new(Opcode::LineNumber, Operand::Int(1)),
702 Instruction::new(Opcode::PushConstantString, Operand::Str(hi)),
703 Instruction::pop_string_local(0),
704 Instruction::push_long(42),
705 Instruction::pop_long_local(0),
706 Instruction::simple(Opcode::Return),
707 ];
708
709 let mut diags = DiagnosticsCollector::new();
710 check_unused_locals(&script, None, &mut diags);
711 let warnings: Vec<_> = diags
712 .diagnostics()
713 .iter()
714 .filter(|d| d.severity == Severity::Warning)
715 .collect();
716 assert_eq!(warnings.len(), 2, "both $s and $l should warn");
717 let names: Vec<&str> = warnings.iter().map(|d| d.message.as_str()).collect();
718 assert!(names.iter().any(|m| m.contains("$s")));
719 assert!(names.iter().any(|m| m.contains("$l")));
720 }
721
722 #[test]
723 fn unused_array_is_reported() {
724 let mut script = empty_script("foo");
725 push_local_entry(&mut script, "arr", Type::Int, false, true);
726 script.instructions = vec![
727 Instruction::new(Opcode::LineNumber, Operand::Int(2)),
728 Instruction::push_int(5),
729 Instruction::new(Opcode::DefineArray, Operand::Int(0)),
730 Instruction::simple(Opcode::Return),
731 ];
732
733 let mut diags = DiagnosticsCollector::new();
734 check_unused_locals(&script, None, &mut diags);
735 let warnings: Vec<_> = diags
736 .diagnostics()
737 .iter()
738 .filter(|d| d.severity == Severity::Warning)
739 .collect();
740 assert_eq!(warnings.len(), 1);
741 assert!(warnings[0].message.contains("$arr"));
742 assert!(warnings[0].message.contains("array"));
743 }
744
745 #[test]
746 fn touched_array_does_not_warn() {
747 let mut script = empty_script("foo");
749 push_local_entry(&mut script, "arr", Type::Int, false, true);
750 script.instructions = vec![
751 Instruction::new(Opcode::LineNumber, Operand::Int(1)),
752 Instruction::push_int(3),
753 Instruction::new(Opcode::DefineArray, Operand::Int(0)),
754 Instruction::push_int(1),
755 Instruction::push_int(0),
756 Instruction::new(Opcode::PopArrayInt, Operand::Int(0)),
757 Instruction::push_int(0),
758 Instruction::new(Opcode::PushArrayInt, Operand::Int(0)),
759 Instruction::new(Opcode::PopIntDiscard, Operand::Int(0)),
760 Instruction::simple(Opcode::Return),
761 ];
762
763 let mut diags = DiagnosticsCollector::new();
764 check_unused_locals(&script, None, &mut diags);
765 let warnings: Vec<_> = diags
766 .diagnostics()
767 .iter()
768 .filter(|d| d.severity == Severity::Warning)
769 .collect();
770 assert_eq!(warnings.len(), 0, "touched array should not warn");
771 }
772
773 #[test]
778 fn dead_code_after_return_is_reported() {
779 let mut script = empty_script("foo");
781 let hi = script.intern_str("hi".to_string());
782 let bye = script.intern_str("bye".to_string());
783 script.instructions = vec![
784 Instruction::new(Opcode::LineNumber, Operand::Int(2)),
785 Instruction::new(Opcode::PushConstantString, Operand::Str(hi)),
786 Instruction::new(Opcode::Command, Operand::Int(0)), Instruction::new(Opcode::LineNumber, Operand::Int(3)),
788 Instruction::simple(Opcode::Return),
789 Instruction::new(Opcode::LineNumber, Operand::Int(4)),
790 Instruction::new(Opcode::PushConstantString, Operand::Str(bye)),
791 Instruction::new(Opcode::Command, Operand::Int(0)),
792 Instruction::simple(Opcode::Return),
793 ];
794
795 let mut diags = DiagnosticsCollector::new();
796 check_unreachable_code(&script, None, &mut diags);
797 let warnings: Vec<_> = diags
798 .diagnostics()
799 .iter()
800 .filter(|d| d.severity == Severity::Warning)
801 .collect();
802 assert_eq!(warnings.len(), 1);
803 assert_eq!(warnings[0].line, 4);
804 assert!(warnings[0].message.contains("Unreachable"));
805 }
806
807 #[test]
808 fn dead_code_after_jump_is_reported() {
809 let mut script = empty_script("foo");
811 let never = script.intern_str("never".to_string());
812 script.instructions = vec![
813 Instruction::new(Opcode::LineNumber, Operand::Int(2)),
814 Instruction::new(Opcode::JumpWithParams, Operand::Int(999)),
815 Instruction::new(Opcode::LineNumber, Operand::Int(3)),
816 Instruction::new(Opcode::PushConstantString, Operand::Str(never)),
817 Instruction::new(Opcode::Command, Operand::Int(0)),
818 Instruction::simple(Opcode::Return),
819 ];
820
821 let mut diags = DiagnosticsCollector::new();
822 check_unreachable_code(&script, None, &mut diags);
823 let warnings: Vec<_> = diags
824 .diagnostics()
825 .iter()
826 .filter(|d| d.severity == Severity::Warning)
827 .collect();
828 assert_eq!(warnings.len(), 1);
829 assert_eq!(warnings[0].line, 3);
830 }
831
832 #[test]
833 fn reachable_code_after_conditional_branch_is_ok() {
834 let mut script = empty_script("foo");
836 let yes = script.intern_str("yes".to_string());
837 script.instructions = vec![
838 Instruction::new(Opcode::LineNumber, Operand::Int(1)),
839 Instruction::push_int(1),
840 Instruction::push_int(1),
841 Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(6)),
842 Instruction::new(Opcode::Branch, Operand::JumpTarget(9)),
843 Instruction::new(Opcode::LineNumber, Operand::Int(2)),
844 Instruction::new(Opcode::PushConstantString, Operand::Str(yes)),
845 Instruction::new(Opcode::Command, Operand::Int(0)),
846 Instruction::new(Opcode::LineNumber, Operand::Int(3)),
847 Instruction::simple(Opcode::Return),
848 ];
849
850 let mut diags = DiagnosticsCollector::new();
851 check_unreachable_code(&script, None, &mut diags);
852 let warnings: Vec<_> = diags
853 .diagnostics()
854 .iter()
855 .filter(|d| d.severity == Severity::Warning)
856 .collect();
857 assert_eq!(
858 warnings.len(),
859 0,
860 "conditional-branch body is reachable; got: {:?}",
861 warnings.iter().map(|d| &d.message).collect::<Vec<_>>()
862 );
863 }
864
865 #[test]
866 fn compiler_emitted_branch_without_linenumber_does_not_warn() {
867 let mut script = empty_script("foo");
871 script.instructions = vec![
872 Instruction::new(Opcode::LineNumber, Operand::Int(1)),
873 Instruction::push_int(1),
874 Instruction::push_int(1),
875 Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(5)),
876 Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
877 Instruction::new(Opcode::LineNumber, Operand::Int(2)),
878 Instruction::simple(Opcode::Return),
879 Instruction::new(Opcode::Branch, Operand::JumpTarget(8)), Instruction::simple(Opcode::Return),
881 ];
882
883 let mut diags = DiagnosticsCollector::new();
884 check_unreachable_code(&script, None, &mut diags);
885 let warnings: Vec<_> = diags
886 .diagnostics()
887 .iter()
888 .filter(|d| d.severity == Severity::Warning)
889 .collect();
890 assert_eq!(
891 warnings.len(),
892 0,
893 "compiler-emitted unreachable Branch must not warn; got: {:?}",
894 warnings.iter().map(|d| &d.message).collect::<Vec<_>>()
895 );
896 }
897}