Markdown Parsing Strategy: Two-Phase Approach
masterCommonMark-compliant parsers (like goldmark) typically use a two-phase parsing strategy to convert Markdown into a document tree:
Phase 1: Block Structure
Lines of input are consumed to construct the document's block structure (e.g., paragraphs, block quotes, lists).
- Process: The parser iterates through open blocks, checking if the current line satisfies the block's conditions (e.g., a
>for block quotes). - Result: A tree of blocks is created. The last child of a block is usually 'open', allowing subsequent lines to be added to it (lazy continuation).
Phase 2: Inline Structure
Once the block structure is complete, the parser 'walks the tree' and parses the raw text within paragraphs and headings into inline elements (e.g., strings, code spans, links, emphasis).
- Link Resolution: Link reference definitions parsed in Phase 1 are used to resolve links during this phase.