Work on this exercise locally

This web app is a reference guide — you can read instructions, browse starter code, and view tests here. To actually complete the exercise, you need to work in your local development environment.

1Clone the repo: git clone https://github.com/weihaoqu/program-analysis-bootcamp-student
2Edit the starter file in your editor (VS Code, Vim, etc.) — replace failwith "TODO" with your implementation.
3Run the tests: dune runtest modules/module6-tools-integration/exercises/dead-code-detector

Dead Code Detector

3. Exercise 2: Dead Code Detector (20 tests)

Goal: Detect dead code patterns using purely AST-level analysis: unreachable code after Return, unused variables, and unused function parameters.

Time: ~25 minutes

File to edit: exercises/dead-code-detector/starter/dead_code.ml

Also provided (do not edit): exercises/dead-code-detector/starter/finding_types.ml

Dependencies: shared_ast (for AST types)

What to implement (in order)

#FunctionHint
1has_return stmtsCheck if any top-level stmt in the list is a Return
2stmts_after_return stmtsWalk the list; once you hit a Return, return everything after it
3collect_used_vars_expr eRecursively collect Var x names into a StringSet. IntLit/BoolLit contribute nothing. BinOp unions both sides. Call unions all args.
4collect_used_vars_stmts stmtsUnion used vars from each statement. For Assign(_, e) collect from e. For If/While collect from condition + bodies. For Return (Some e) collect from e.
5collect_assigned_vars stmtsCollect all x from Assign(x, _) statements, recursing into If/While/Block bodies
6find_unreachable_code funcIf stmts_after_return func.body is non-empty, emit a CodeQuality/Medium finding
7find_unused_variables funcAssigned but never read variables get CodeQuality/Low findings. Variables starting with _ are exempt.
8find_unused_parameters funcParameters never read in the body get CodeQuality/Info findings. Parameters starting with _ are exempt.
9analyze_function funcConcatenate results of all three detectors for one function
10analyze_program progList.concat_map analyze_function prog

Run tests

dune runtest modules/module6-tools-integration/exercises/dead-code-detector/

Starter output (all 20 tests error):

EEEEEEEEEEEEEEEEEEEE

Hints:

  • Use StringSet.mem, StringSet.union, StringSet.singleton, and StringSet.diff for variable tracking.
  • The _-prefix exemption check: String.length name > 0 && name.[0] = '_'.
  • Use fresh_id () to generate unique IDs for each finding.
  • Finding location should be the function name (func.name).