1. Home
  2. Explore
  3. Computer Science
  4. Syntax Tree Project Overview

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Syntax Tree Project Overview

Syntax Tree: A Ruby Parsing and Formatting Toolkit

This guide covers the foundational concepts behind the Syntax Tree project, a standard library formatter and analysis tool for Ruby. It explores parsing, syntax trees, the visitor pattern, building and formatting ASTs, and translating trees into other representations.


What Is a Parser?

A parser transforms plain text into a structured data representation that a programming language (or human) can process. It operates in two main stages:

  • Lexical analysis – Breaks the input into tokens (words, symbols, punctuation). For example, the sentence “Matz is nice so we are nice” yields tokens: Matz (noun), is (verb), nice (adjective), so (conjunction), we (noun), are (verb), nice (adjective), . (period).

  • Semantic analysis – Groups tokens into larger grammatical units based on a grammar definition. A grammar specifies how tokens combine to form higher-level constructs (e.g., verb‑phrase, subject‑phrase, sentence).

Grammar – A set of rules that define valid structures in a language. In programming, the grammar is often defined in files like parse.y (for CRuby).

The process produces a tree structure where leaves are tokens and interior nodes are composite structures.


What Is a Syntax Tree?

A syntax tree (or abstract syntax tree, AST) is an object‑oriented representation of the parsed code. Each node in the tree corresponds to a language construct (e.g., class, def, if, integer literal). Nodes can be:

  • Leaf nodes (tokens) – Wrap a single value from the source code (e.g., an integer 42, a variable name x).

  • Branch nodes – Represent composite constructs with children (e.g., a CallNode with a receiver, method name, and arguments).

In Ruby, a node can be implemented as a plain class:

class VerbPhrase
  attr_reader :verb, :adjective

  def initialize(verb, adjective)
    @verb = verb
    @adjective = adjective
  end

  # visitor pattern support
  def accept(visitor)
    visitor.visit_verb_phrase(self)
  end

  def child_nodes
    [verb, adjective]
  end
end

Each node also supports:

  • Pattern matching – Via deconstruct and deconstruct_keys (Ruby 2.7+), allowing case node in [verb, adjective] => ....

  • accept method – For the visitor pattern.

  • child_nodes method – Returns an array of direct children for tree traversal.

In Syntax Tree, there are 162 node types (as of the talk), down from a higher count due to merging similar constructs (e.g., if modifier and if statement are merged into a single IfNode).


The Visitor Pattern

The visitor pattern decouples operations on a tree from the node classes themselves. It uses double dispatch: the node calls a specific method on the visitor, and the visitor then processes that node type.

How It Works

  1. Each node has an accept(visitor) method that calls visitor.visit_NODE_TYPE(self).

  2. The visitor class defines visit_NODE_TYPE methods for each node type it cares about.

  3. A generic visit(node) method can be used as a fallback – it calls node.accept(self).

  4. The visitor can define a visit_child_nodes helper that calls visit on each child, enabling recursive descent.

Example of a visitor that counts sentences:

class SentenceCounter
  attr_reader :count

  def initialize
    @count = 0
  end

  def visit_sentence(node)
    @count += 1
    visit_child_nodes(node)   # continue traversal
  end

  def visit_child_nodes(node)
    node.child_nodes.each { |child| visit(child) }
  end

  def visit(node)
    node.accept(self)
  end

  # All other visit methods are aliased to visit_child_nodes
end

This pattern allows writing focused visitors that process only the relevant node types without needing a giant case statement.


Building the Syntax Tree in Ruby

Syntax Tree itself is not a parser – it takes the output of a parser (currently Ripper) and builds an immutable object layer on top.

Using Ripper

Ripper is a CRuby standard library that fires events as it parses source code. It works bottom‑up: tokens are dispatched as leaf events, which are then combined into higher‑level events.

Key events include:

  • on_const – a constant token (e.g., Foo)

  • on_ident – an identifier token

  • on_def – a method definition

  • on_class – a class definition

  • on_program – the top‑level program

The challenge: Ripper does not provide location information for nodes. Syntax Tree overcomes this by maintaining a stack of tokens with positions and using keyword tracking to determine node boundaries. For example, when on_class is called, it looks back through the stack to find the matching class keyword and the end position.

Handling Incomplete Ripper Support

Ripper does not cover every Ruby syntax nuance. For instance, lambda local variables (e.g., ->(a; b) { ... }) are not reported. Syntax Tree handles such cases with a sub‑parser that reads the source directly and builds the necessary nodes.

Key insight – Syntax Tree abstracts away the parser choice. Users interact only with the visitor interface, never with Ripper directly.

Comments

Comments are a special case – Ripper emits on_comment events, but they are not attached to the tree by default. Syntax Tree collects all comments into an array during parsing. After building the tree, it performs a binary search over each node’s child_nodes to find the best‑fitting parent for each comment. The heuristic:

  • Favor nodes that immediately follow the comment (on the same line or the next line).

  • Attach the comment to the closest ancestor that makes semantic sense.


Formatting with Prettyprint

Syntax Tree’s formatter is built on the prettyprint algorithm (originally from the paper A Prettier Printer by Wadler). It uses three types of doc nodes:

  • Text nodes – Plain string content.

  • Breakables – Indicate where a newline can be inserted.

  • Groups – Nest other doc nodes; when the line length is exceeded, the outermost group is broken first.

Algorithm Intuition

Given an array, the printer builds doc groups for each element. If the line fits within the configured print width (default 80), things stay flat. When the line would exceed the width, the outermost group is broken, then inner groups as needed.

Example:

[1, 2, 3, 4, 5]
  • If it fits: [1, 2, 3, 4, 5]

  • If broken: [1, 2, 3, 4,\n 5]

  • Further narrowed: [1, 2,\n 3,\n 4,\n 5]

This algorithm is implemented in the prettier_print gem (a simpler replacement for the standard pp library). Syntax Tree extends it with features like:

  • if_break – choose between two representations depending on whether the group fits (e.g., if a then b end vs. b if a).

  • if_flat – use alternative formatting when the group remains on one line.

  • Heredoc handling – the heredoc body only appears when a newline is encountered.

Node‑Specific Formatting

Each node type in Syntax Tree defines its own format method:

class ReturnNode
  def format(q)
    q.text("return")
    q.format_breakable_space
    q.format(expression)
  end
end

The q object is the prettyprinter (an instance of the formatter). The formatter walks the AST, generates the doc tree, and then prints it out.

Comment Preservation

Comments attached to nodes are moved along with the node during formatting. If a node is broken onto multiple lines, its associated comment is placed appropriately.


The Command‑Line Interface (CLI)

Syntax Tree provides a CLI tool with several subcommands. The most notable ones:

syntax_tree ast

Prints the abstract syntax tree of a Ruby file as a visual tree. Useful for inspecting how Ruby parses complex expressions (e.g., def foo(a = b = 1)).

syntax_tree format

Formats a Ruby file according to Syntax Tree’s default rules.

syntax_tree match (⭐ favorite)

Takes a Ruby expression and outputs a pattern‑matching expression that would exactly match the corresponding AST node. For example:

$ syntax_tree match "2 + 2"

Might output:

in Int(2) + Int(2) ... # (simplified)

This expression can be used directly in an in clause inside a case statement.

syntax_tree search

Accepts a pattern‑matching expression (like the output of match) and finds all matching nodes in a given source file. Internally, it:

  1. Parses the pattern using Syntax Tree.

  2. Builds a proc that tries to match each node against the pattern.

Combine match and search to quickly find all occurrences of a specific code pattern.


Language Server Protocol (LSP)

A language server is a process that communicates with an editor via JSON‑RPC. Syntax Tree includes a lightweight LSP that supports:

  • didOpen / didChange / didClose – text document lifecycle.

  • textDocument/formatting – format on save.

  • inlayHint – additional inline information (e.g., type hints).

Example

# Start the language server
syntax_tree lsp

Then configure VS Code (or any LSP‑compatible editor) to connect to it. The server responds to formatting requests by running Syntax Tree’s formatter.

Shopify’s Ruby LSP builds on top of Syntax Tree, adding features like document symbols, folding ranges, selection ranges, and semantic highlighting.


Translating the Syntax Tree

Syntax Tree can convert its own AST into other representations without changing the source code. This is done via visitors that walk the tree and produce a different output.

ruby_parser (Seattle.rb) and whitequark parser (RuboCop)

Visitors exist to translate Syntax Tree nodes into the AST formats used by:

  • ruby_parser – powering tools like flog and flay.

  • whitequark parser – powering RuboCop.

This means you can parse a file with Syntax Tree, then run RuboCop or other static analysis tools on the translated tree. The parser backend can be swapped transparently.

YARV (Yet Another Ruby VM) Bytecode

A recent addition: a visitor that compiles Syntax Tree nodes into instruction sequence objects – the same bytecode used internally by CRuby. Using a secret C API (as revealed by Aaron Patterson), these bytecode objects can be converted back into executable code.

Potential applications:

  • Polyfilling – parse modern Ruby syntax (e.g., pattern matching in Ruby 2.7), mutate the tree to 2.6 semantics, compile to YARV, and execute.

  • Code transformation – modify the AST, then convert to bytecode for execution without rewriting to source.

Back to Source (Mutation Visitor)

Syntax Tree includes a mutation visitor that allows rewriting the tree:

visitor = SyntaxTree::MutationVisitor.new
visitor.mutate(tree, query: "In Int(2)") do |node|
  node.copy(value: 3)
end

The query is a pattern (using the same syntax as match). Inside the block, you can call copy (immutable copy) to produce a new node. The visitor returns a new tree with the changes applied. This is the foundation for auto‑correction linters and automated code mods.

Future direction – Provide a CLI to ship code mods (e.g., a Rails deprecation fixer) that users can run on their projects.


Summary

  • Syntax Tree is an object layer for Ruby ASTs, built on top of a parser (currently Ripper, but swappable).

  • It defines 162 node types, each immutable, supporting visitor pattern and pattern matching.

  • The visitor pattern enables flexible traversal and transformation without modifying node classes.

  • The formatter uses the prettyprint algorithm with node‑specific rules, and handles comments intelligently.

  • The CLI offers AST inspection, formatting, pattern‑match generation, and search.

  • The language server provides format‑on‑save and other IDE features.

  • Translation visitors convert the tree into other parsers’ ASTs, YARV bytecode, or back to source with mutation.

The project aims to provide a stable, portable foundation for Ruby tooling, with a future‑proof design that allows the underlying parser to be replaced without affecting consumer code.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent