Add Haddock documentation accumulated in the parser state to a parsed HsModule.
Reports badly positioned comments when -Winvalid-haddock is enabled.
:: a typeCtrl KGHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27
Moduleghc-9.10.3GHC2021
This module implements addHaddockToModule, which inserts Haddock comments accumulated during parsing into the AST (#17544).
We process Haddock comments in two phases:
Parse the program (via the Happy parser in Parser.y), generating
an AST, and (quite separately) a list of all the Haddock comments
found in the file. More precisely, the Haddock comments are
accumulated in the hdk_comments field of the PState, the parser
state (see Lexer.x):
data PState = PState { ... , hdk_comments :: [PsLocated HdkComment] }
Each of these Haddock comments has a PsSpan, which gives the BufPos of the beginning and end of the Haddock comment.
Walk over the AST, attaching the Haddock comments to the correct parts of the tree. This step is called addHaddockToModule, and is implemented in this module.
See Note [Adding Haddock comments to the syntax tree].
This approach codifies an important principle:
The presence or absence of a Haddock comment should never change the parsing of a program.
Alternative approaches that did not work properly:
Using RealSrcLoc instead of BufPos. This led to failures in presence of {-# LANGUAGE CPP #-} and other sources of line pragmas. See documentation on BufPos (in GHC.Types.SrcLoc) for the details.
In earlier versions of GHC, the Haddock comments were incorporated into the Parser.y grammar. The parser constructed the AST and attached comments to it in a single pass. See Note [Old solution: Haddock in the grammar] for the details.
Add Haddock documentation accumulated in the parser state to a parsed HsModule.
Reports badly positioned comments when -Winvalid-haddock is enabled.