Auto-format code in many languages
Formatting code isn't as simple as just adding spaces after every curly brace or newline after every semicolon. A reliable formatter must understand the actual structure of the code, so it doesn't accidentally break things (like splitting a string literal in half).
To do this safely, modern formatters (like Prettier) typically parse the source code into an Abstract Syntax Tree (AST). The AST is a massive JSON object representing every variable, function declaration, and block of logic independently of how it was typed.
Once the AST is successfully built, the formatter completely drops and ignores all the original whitespace from the source file.
It then traverses the tree and prints the code back out from scratch, applying a consistent, highly opinionated set of rules (like indenting exactly 2 spaces inside blocks, or wrapping lines at 80 characters). This guarantees that the final code functions exactly the same mathematically, but with perfectly uniform spacing.
If you try to format code that is missing a closing bracket or has a typo, an AST-based formatter will crash. It cannot build the tree if the code is invalid. This is why formatting often fails in your IDE while you are actively typing a new function.
How does a modern AST-based code formatter handle the existing whitespace in your unformatted code?