ghc-lib-parser-9.10.1.20250103: The GHC API, decoupled from GHC versions

Safe Haskell | Ignore
Language | GHC2021

GHC.Parser.PostProcess.Haddock

Description

This module implements `addHaddockToModule`, which inserts Haddock comments accumulated during parsing into the AST (#17544).

We process Haddock comments in two phases:

1. Parse the program (via the Happy parser in `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.

1. 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:

1. 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.
2. 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.

Synopsis

- addHaddockToModule :: Located (HsModule GhcPs) -> P (Located (HsModule GhcPs))

# Documentation

addHaddockToModule :: Located (HsModule GhcPs) -> P (Located (HsModule GhcPs)) #

Add Haddock documentation accumulated in the parser state to a parsed HsModule.

Reports badly positioned comments when -Winvalid-haddock is enabled.