You build a code visual tree by parsing source text into a concrete syntax tree (a CST that keeps comments, whitespace, and punctuation), then converting that CST into a layout-ready model with parent links, depth values, and per-node geometry, and finally drawing it with boxes and connectors on an SVG canvas, or printing it as ASCII when the tree is small. The first condition, and the one that most often derails weeks of work, is using a parser that preserves every token; ordinary abstract syntax trees throw away layout details, so a diagram built from an AST will look tidy but won't match the original file character for character.

The steps below assume you're writing a small web tool or a script. The same pipeline applies if you're generating an image in Python or drawing branches in a terminal, so treat each stage as a contract you can test on its own before moving on.

Prerequisites and the shape of the pipeline

You need three things before you start: a runtime (Node.js 18 or newer, or Python 3.10 with a binding to a parser library), a parser that outputs a lossless tree, and a way to inspect the output. Pick one parser and commit to it early, because swapping mid-project is expensive.

For most languages there are two families of tools. Tree-sitter is the widely used incremental parser generator; it produces named and anonymous nodes, keeps whitespace and comments as real nodes, and ships grammars for dozens of languages. Language-native tooling is the other family: the TypeScript compiler API exposes a syntax tree with getChildren() and getFullText(); Python's ast module does not preserve formatting but libcst or parso do; Java's JavaParser offers a lossless syntax model through JavaParser.parse and node position data.

There's a common shortcut that's fine for prototypes: parse into an abstract tree, then synthesize boxes from node types without token text. You get a presentable diagram on day one, and you hit a wall the moment you want to show a comment, compare a diff of the tree, or preserve exact source spans. If your goal is anything more than a screenshot, build the CST pipeline.

One more prerequisite is a mental model of the tree you're drawing. Nodes fall into three groups you'll treat differently when drawing: structural nodes (expressions, statements, declarations), token nodes (identifiers, literals, operators, keywords), and trivia (whitespace, newlines, comments). Tokens and trivia are usually leaf boxes; structure nodes are containers that get a border and children.

Step 1: Produce a lossless concrete syntax tree

Write the smallest possible script that parses one file and prints the root node's kind and its children's kinds. For Tree-sitter in JavaScript this is roughly a call to parser.parse(source), then a walk from tree.rootNode collecting type and childCount. Success looks like a printed tree whose leaf count equals the token count of the file plus trivia, and whose span ends at byte offset equal to the file length. If the end offset is short, your parser is dropping trailing trivia; if there are error nodes (isError is true), the file failed to parse and you need to see the recovery nodes before proceeding.

Run this check on three files: a tiny hello-world, a real 200-line function from your codebase, and a deliberately broken file. The broken file should produce ERROR nodes, and you should know how your chosen parser marks them. That knowledge matters later because a visual tree that hides parse errors is quietly lying to the viewer.

If you're using a wrapped library, confirm it exposes child-by-index access and a byte or character range for each node. Some bindings only offer the AST-style filtered view, which silently removes punctuation. Check by counting children of a call expression node: an AST-like wrapper might report two (callee and arguments), while a CST reports five including the parentheses and the commas.

Step 2: Normalize into a single node record shape

Before drawing, flatten the parser's objects into one array of records with identical fields. This step pays for itself the first time you change parsers or add a second language.

Each record should carry: an id that's stable for one render, the parser's node kind as type, a text field that's either the token text or the full source slice for containers, start and end offsets, the parent id (or null at the root), a depth integer, and a computed isLeaf boolean. Containers can have empty or very long text; you'll use text only on leaves, and let containers render as their type name plus a small label.

Depth is computed by walking from the root with a counter, not by trusting any field the parser provides. A depth-correct tree is a precondition for layout, so assert it: for every record except the root, depth === parent.depth + 1. A violation means your walk crossed a tree edge after leaf filtering, which is exactly the bug that produces two children on different rows attached to the same parent box.

Decide here whether you'll hide trivia. A common rule is to keep comments visible and drop pure whitespace nodes, since whitespace boxes inflate the canvas. If you keep whitespace, label empty text explicitly as spaces or newlines, or the box looks broken.

Step 3: Choose a layout algorithm

Layout is where "just draw a tree" becomes the actual work. The three methods below produce visually different results, and the right one depends on whether you care about compactness, stability across edits, or the shape of the code.

The classic horizontal tree, often called Reingold-Tilford or tidy tree layout, places each subtree in its own horizontal slot and centers a parent over its children. It's compact and easy to read, and it's what most tree viewers show. It's also the worst choice for wide, deep expression trees, because deep nesting forces children far apart and the canvas grows quickly.

The layered or Sugiyama-style layout puts each depth level on its own horizontal band and orders boxes within the band to reduce crossings. This suits code trees well because statement sequences at one depth read left to right like the source.

A third option is to mirror the source: place each node's box at its original start offset on a horizontal axis and use depth as the vertical axis. You get a vertically extruded outline of the file that's instantly recognizable and handles trivia naturally. The cost is horizontal space, since a 4,000-character line spans a very wide canvas.

For a first working version, pick the tidy tree in vertical orientation: parent above children, children spread horizontally, connectors as bezier curves or elbow paths. You'll revisit this if the source you care about has long flat argument lists, where the mirrored layout wins.

Geometry decisions you must make before coding: box width from a monospace text width estimate (character count times average glyph width), a fixed box height, horizontal gap between sibling subtrees, and vertical gap between depth levels. Fixed values like 24 px height, 20 px level gap, and 12 px sibling gap are a fine starting point; you'll tune them after seeing real output.

Step 4: Compute positions with a bottom-up pass

The reliable way to lay out a tidy tree is two passes. The first pass runs post-order: each leaf gets a width equal to its box width; each container gets a width equal to the sum of its children's widths plus the gaps. The second pass runs pre-order: assign the root a starting x, then give each child a cursor that advances by its width plus gap, centering the parent over its children's span.

Sketch the width rule in plain arithmetic. For a node with children c1 through cn and gap g, width(node) = sum(width(ci)) + g times (n minus 1). A leaf's width is its box width. Then x(child) is set by walking the children in order, each starting where the previous ended plus g, and y is depth times (boxHeight plus verticalGap). The parent's x is the midpoint of its first child's left edge and last child's right edge.

Two edge cases break naive implementations. Unary and single-child nodes produce a chain of centered boxes on the same x column, which looks like a vertical line; decide whether to offset them slightly or leave them. Very deep trees overflow the recursion stack in a recursive implementation, so use an explicit stack or accept that trees past a few thousand depth will crash. For anything you build for real code, make the traversal iterative.

A sanity check after this pass: no two boxes overlap on the same row, every parent's center lies within the horizontal span of its children, and the total canvas width equals the root's width. If siblings touch, your gap isn't applied; if parents drift off-center, your midpoint math is averaging the wrong edges.

Step 5: Draw boxes and connectors

Rendering is the easy part once positions exist. With SVG, you create one group per node containing a rect and a text element, then one path per parent-child edge. Set the rect's x and y to the node's top-left corner, the width to its computed width, and give the text a baseline offset so it sits vertically centered. For leaves, textContent is the token text; for containers, use the node type, since showing a whole expression's source in a box is unreadable.

Connectors should end at the parent's bottom edge midpoint and start at the child's top edge midpoint. An orthogonal elbow path, dropping vertically from the parent, running horizontally, then dropping into the child, reads better than a diagonal for dense trees. If you use curves, set the control points so the line leaves the parent vertically; a straight cubic with control points at half the vertical gap does this without trigonometry.

Get text width right before you chase aesthetics. Measuring with canvas measureText gives real widths; estimating at 0.6 times the font size for monospace is close enough and vastly faster. Mismatched measurement is the usual cause of text overflowing boxes, so draw a few nodes with long identifiers and check.

For an ASCII fallback, the same geometry works with a character grid: multiply x by a cell width and y by a line height, and draw branch characters where paths cross row boundaries. The output is enough for debugging a layout pass before any SVG exists, and it's what lets tests assert on structure rather than pixels.

Step 6: Let users navigate large trees

Real code trees don't fit on a screen. Three features carry most of the value, and none of them require new parsing.

Click-to-collapse hides a subtree and re-runs the layout passes with that node treated as a leaf, so siblings close the gap rather than leaving a hole. Bi-directional highlighting, where clicking a token in the tree scrolls the source pane to its start offset and vice versa, is the feature that makes the tool feel connected to the file. And zoom with pan, usually implemented as an SVG viewBox transform, handles the rest.

Keep the collapse state keyed by a stable identifier, not array index, or the tree will reshuffle on every edit. A parent path string such as program.0.1.2 works, as does storing the record's original id if you regenerate ids deterministically from offsets.

Performance boundaries worth knowing: tens of thousands of DOM nodes will make scroll and zoom sluggish in any browser, so collapse large subtrees by default past a depth threshold or past a node count. Recomputing layout on every keystroke in a live editor is a common mistake; debounce, and re-layout only the changed subtree when the parser supports incremental edits.

Step 7: Test against success and stop conditions

You can verify the whole pipeline without eyeballing screenshots. Three automated checks catch nearly everything.

First, token conservation: collect every leaf's text in order and concatenate; if you kept trivia, the result must equal the source file exactly. This single test catches dropped comments, merged operators, and off-by-one offsets.

Second, depth invariants: every non-root record's parent id exists, and depth equals the parent's depth plus one.

Third, layout invariants: sibling boxes don't overlap, and every parent's center is inside its children's span. Run these three on a corpus of a dozen real files across a couple of languages, and you've validated more than most viewers do.

Know when to stop and call in expertise. Implementing a parser grammar for your own language, fixing exponential parse-time blowups on deeply nested expressions, or debugging trees that differ from an IDE's view of correctness are all beyond a drawing exercise. If a production build consumes untrusted source, treat the parser as a security boundary: run it in a worker with a timeout and a depth cap, since pathological input can hang or crash a naive pipeline. That's a signal to bring in someone who has shipped a language service, not a cue to keep patching.

What changes across Tree-sitter, TypeScript, and Python

Keeping the pipeline stages separate lets you swap languages without redesigning the drawing code, but the record-building step differs in ways that will surprise you.

Tree-sitter's namedChild and child accessors count different children; child includes anonymous nodes like punctuation, which is what a CST diagram needs, while namedChild skips them. In Tree-sitter, comments usually appear as named nodes, so they survive either walk. Offsets are byte offsets into UTF-8, not character offsets, so converting to JS string indices requires encoding-aware math or working with bytes from the start.

TypeScript's compiler API gives every node a pos and end measured in characters over the original string, and getChildren() yields tokens including punctuation, so concatenating getFullText() over leaves equals the source slice. You do not need to reconstruct trivia separately; it's inside the parent spans.

Python's built-in ast is not lossless: it discards comments, blank lines, and parentheses. If you draw from ast, token conservation will fail by design, and you should either accept a structural diagram or switch to a preservation library. This is the clearest example of why the parser choice is step zero rather than an implementation detail.

A worked example on four lines

Consider a four-line function: def double(x): then an indented return x * 2, then a blank line, then a one-line comment. Counting tokens for a Tree-sitter-style CST gives a module node containing one function definition; that function contains def, an identifier double, a parameter list wrapping one identifier, :, a block, a return keyword, a binary expression, and a comment node. The return statement holds the expression with three children (identifier, operator, literal), and the block holds the comment as its second child.

Layout arithmetic on this tree is short enough to check by hand. Suppose every box is 20 px wide, sibling gap is 10 px, and leaf boxes for the identifier double, x, and 2 are 60, 12, and 12 px. The binary expression spans 12 plus 10 plus 12 = 34 px plus the box widths means the expression's own width is 34 px; the return statement with one child inherits that 34; the block's width is the return plus 10 plus the 20 px comment box, giving 64. The parameter list around x is a single-child container at 12 px. This is exactly the kind of arithmetic your width pass encodes, and doing it once by hand tells you whether your code's numbers are plausible.

The diagram shows something real when you look at it: the comment lives beside the return statement at the same depth, and the binary expression's operator sits between its operands, which is why token-type leaves need to be visible. If whitespace nodes are kept, they show as thin siblings and make the block look cluttered; hiding them but keeping comments is the compromise most tools reach.

Limits, version caveats, and what the diagram can't tell you

A visual tree shows structure at one moment for one file. It does not show type information, name resolution, or scope, because those require a semantic analysis pass on top of the parse. It also doesn't show parse ambiguity or error recovery unless you specifically render error nodes in a distinct style, and it hides the difference between a syntactically valid construct and a semantically wrong one. Teams often expect the tree to explain bugs; it explains shape, and shape is frequently enough, but not always.

Parser versions matter for the record fields. Tree-sitter grammars update independently of the runtime, and node type names change between grammar versions, so a diagram tool pinned to one grammar version may mislabel nodes from a newer grammar. The TypeScript API evolves across minor releases too; properties exposed on syntax nodes have shifted over time. Pin your parser version in the project lockfile and record it next to your fixtures, so a suddenly unfamiliar node kind traces to a dependency bump rather than a bug in your walk.

There's also a dimension the layout doesn't capture: horizontal position in a mirrored tree is source offset, but horizontal ordering in a tidy tree is child order, and children aren't always in source order across all grammars. If you switch from tidy to mirrored layout, re-verify your offsets rather than assuming the two agree.

Adding value fast: three features that cost little

Build a JSON export of the record array before building features; it makes regression testing and sharing bug reports trivial, and it lets teammates render trees with their own tools.

Then add diff rendering: parse two versions of a file and color leaf tokens present in one and absent from the other. Because leaf text and offsets are already in the model, the diff is a map lookup, not a new algorithm.

Finally, add a compact subtree view for a selected node, showing it in the same tree drawing but with the rest of the file collapsed. Engineers reach for this when debugging macro expansions and generated code, where the interesting structure is local and the surrounding file is noise.

Worked through in this order, the tool goes from a single-file script to something usable in an afternoon, and each stage has a check that tells you it works before the next one depends on it.