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/module2-ast/exercises/ast-structure-mapping

AST Structure Mapping

3. Exercise 1: AST Structure Mapping (no tests)

Goal: Build three visualization functions that render ASTs in different formats. This is a warm-up exercise with no automated tests -- you run the executable and inspect the output visually.

Time: ~20 minutes

Files to edit: exercises/ast-structure-mapping/starter/ast_visualizer.ml

Also provided:

  • exercises/ast-structure-mapping/starter/sample_asts.ml -- pre-built AST examples that re-export programs from Shared_ast.Sample_programs
  • exercises/ast-structure-mapping/starter/worksheet.md -- guided hand-drawing exercises (fill in on paper or in the file)

What to implement

#FunctionWhat it does
1dump_expr / dump_stmt / dump_stmts / dump_astIndented tree dump: each node on its own line, children indented 2 more spaces
2inc / count_expr / count_stmt / count_stmts / count_node_typesWalk the AST and count how many of each node type appear; return an association list
3string_of_op / string_of_uop / expr_to_string / pp_stmt / pp_stmts / print_treePretty-print the AST as human-readable pseudo-code

Run the executable

dune exec modules/module2-ast/exercises/ast-structure-mapping/starter/ast_visualizer.exe

There are no automated tests for this exercise. Verify your output visually against the comments in the starter file. The executable runs your three visualizers on three sample programs (simple_arithmetic, branching, loop_example).

Hints

  • dump_ast: Use the indent depth helper to build the padding string. For compound nodes like BinOp, print the parent at the current depth, then recursively print children at depth + 1.
  • count_node_types: Thread an accumulator (string * int) list through the recursion. The inc helper should increment a key if present, or add (key, 1) if not.
  • print_tree: This is the most substantial function. Pattern-match on each statement variant and format it like readable pseudo-code (see the comments in the file for the expected format of each case).