packages feed

tilia-0.2.0.0: src/Tilia/Cpp.hs

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}

-- | Formatting a module with the C preprocessor involved.
--
-- Each configuration is printed on its own and the documents are merged.
-- Working out what the configurations are is "Tilia.Cpp.Directives", whose
-- vocabulary this module re-exports.
module Tilia.Cpp
  ( -- * Formatting
    formatWithCpp,
    usesCpp,
    blankCpp,
    withoutRuledOut,
    everyBranch,
    joinedByCpp,
    contextBeforeHaddock,
    CppError (..),
    describeCppError,

    -- * Splitting
    Guard (..),
    Configurations (..),
    branchLeaves,
    correspondingBranches,
    countLeaves,
    answeredLeaves,
    answeredLinearLeaves,
  )
where

import Control.Applicative ((<|>))
import Control.Monad (join, when)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Except (ExceptT, catchE, except, runExceptT, throwE)
import Control.Monad.Trans.State.Strict (State, evalState, gets, modify')
import Data.Array (bounds, inRange, listArray, (!))
import Data.Foldable (traverse_)
import Data.Generics.Schemes (listify)
import Data.IntMap.Strict (IntMap)
import Data.IntMap.Strict qualified as IntMap
import Data.IntSet qualified as IntSet
import Data.List (findIndex, sort)
import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
import Data.List.NonEmpty qualified as NE
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe
  ( catMaybes,
    fromMaybe,
    isNothing,
    listToMaybe,
    mapMaybe,
    maybeToList,
  )
import Data.Monoid (Any (..))
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as T
import Data.Traversable (for)
import GHC.Conc (par)
import GHC.Hs (GhcPs, HsType (..), LHsType)
import GHC.Types.Name.Occurrence (occNameString)
import GHC.Types.Name.Reader (rdrNameOcc)
import GHC.Types.SrcLoc (GenLocated (..))

import Tilia.Cpp.Directives
import Tilia.Cpp.Expansion (Macro (..))
import Tilia.Cpp.Fragment
  ( bodyOf,
    fragmentLines,
    fragmentText,
    fragmentsOf,
    linesHeld,
    reassembled,
  )
import Tilia.Cpp.Merge (Settled (..), combine, merge)
import Tilia.Cpp.Place
  ( CommentSummary,
    carriedBetween,
    readDifferently,
    restoreUnprinted,
    summarizeComments,
  )
import Tilia.Doc
  ( DeclDelimiterStyle (..),
    Doc (..),
    Layout (..),
    conditionalRange,
    foldChildren,
    mapChildren,
    printDoc,
    printedFrom,
    spine,
  )
import Tilia.Parser
  ( ParsedModule,
    ParserConfig,
    codeLines,
    importLayout,
    parseConfiguration,
    parseModule,
    pmExtensions,
    pmGathered,
    pmModule,
    pmSource,
    readAlike,
  )
import Tilia.Render (RenderConfig (..), renderConfiguration)
import Tilia.Render.Haddock (haddockSpans)
import Tilia.Source
  ( Lines,
    Written (..),
    comments,
    directivePresentOnLine,
    dropping,
    endsInBackslash,
    linesOf,
  )
import Tilia.Span (spanEndLine, spanStartLine, startPoint)
import Tilia.Span.Ghc (spanOf)

----------------------------------------------------------------------------
-- Formatting

-- | Format a module which uses the C preprocessor.
--
-- Each configuration's code is formatted by the ordinary printer, and the
-- resulting documents are merged. The conditionals, the comments, and the
-- directives are then injected into the merged document.
formatWithCpp ::
  -- | What to parse each configuration with.
  ParserConfig ->
  -- | What to print each configuration with.
  RenderConfig ->
  -- | The file this is, for the positions in an error.
  FilePath ->
  -- | The module, directives and all.
  Text ->
  -- | The formatted module, or why not.
  Either CppError Text
formatWithCpp parser render path source = do
  traverse_ (Left . RuledOutBranch) (ruledOutBranch source)
  (document, found) <-
    evalState
      ( runExceptT
          ( formatAllConfigs
              formatter
              (reading formatter (noAnswers source) source)
          )
      )
      (configurationBudget * linesHeld source, Map.empty)
  traverse_ (Left . HaddockReadDifferently) (readDifferently found)
  formatted <-
    printDoc (rcSettings render)
      <$> restoreUnprinted source macros found document
  formatted <$ traverse_ (Left . RuledOutBranch) (ruledOutBranch formatted)
  where
    formatter =
      Formatter
        { formatterParser = parser,
          formatterRender = known,
          formatterPath = path,
          formatterMacroLines = macros
        }
    macros = macroLines source
    known =
      render
        { rcDirectiveLines = maybe [] (sort . concatMap gsOwnLines) groups,
          rcImportBarriers = maybe [] (importBarriers layout) groups,
          rcImportBounds = importBounds,
          rcMacros = Set.fromList (fmap fst defined),
          rcMacroArguments = Set.fromList (macroArguments defined source)
        }
    defined = definedMacros source
    groups = allGroups <$> scanConditionals source
    layout =
      fromMaybe
        IntMap.empty
        (importLayout parser conditional (blankCpp source))
    conditional n =
      any
        (any (\g -> fst (gsWhole g) <= n && n <= snd (gsWhole g)))
        groups
    importBounds = case groups of
      Just gs@(_ : _) ->
        importBoundsAt
          gs
          (IntMap.keys (IntMap.filter id layout))
          (length (T.lines source))
      _ -> const Nothing

-- | The first and the last line an import begins on in every configuration
-- that has the given line, or in every configuration at all.
importBoundsAt ::
  -- | Every conditional of the module, nested ones included.
  [GroupSpec] ->
  -- | The lines an import of some configuration begins on, in order.
  [Int] ->
  -- | How many lines the module has.
  Int ->
  -- | The line, or 'Nothing' for every configuration.
  Maybe Int ->
  Maybe (Int, Int)
importBoundsAt groups starts count = \case
  Just n | inRange (bounds byLine) n -> byLine ! n
  _ -> hull starts
  where
    byLine = listArray (1, count) (fmap (hull . heldWith) [1 .. count])
    heldWith n =
      let taken = [(g, k) | g <- groups, Just k <- [branchOf g n]]
       in [ i
          | i <- starts,
            all (\(g, k) -> maybe True (== k) (branchOf g i)) taken
          ]
    branchOf g n =
      findIndex (\(from, to) -> from <= n && n <= to) (gsBranches g)
    hull = fmap (\ls -> (NE.head ls, NE.last ls)) . nonEmpty

-- | A module's branches, parsed: as one module where they parse together,
-- and otherwise as the branch leaves that parse.
everyBranch ::
  -- | What to parse with.
  ParserConfig ->
  -- | The file this is, for the positions in a parse error.
  FilePath ->
  -- | The module, directives and all.
  Text ->
  -- | 'Nothing' where nothing parses.
  Maybe (NonEmpty ParsedModule)
everyBranch parser path source =
  case parseModule parser path (blankCpp source) of
    Right whole -> Just (pure whole)
    Left _ ->
      nonEmpty
        [ parsed
        | Right texts <-
            [branchLeaves (withoutOpaque (macroLines source)) source],
          Right parsed <- fmap (parseModule parser path) texts
        ]

-- | The first line holding code that cpp joins to the line before it, since
-- it ends in a backslash.
--
-- What cpp joins to a comment becomes part of the comment, and what it
-- joins to a line of a string becomes part of the string, so Tilia does not
-- read such a module as GHC does.
joinedByCpp ::
  -- | What to lex with.
  ParserConfig ->
  -- | The module, directives and all.
  Text ->
  Maybe Int
joinedByCpp parser source
  | any endsInBackslash (T.lines source) =
      fmap minimum . nonEmpty $
        [ n
        | (from, to) <- codeLines parser blanked,
          Just n <- [IntSet.lookupGE from joined],
          n <= to
        ]
  | otherwise = Nothing
  where
    blanked = blankCpp source
    joined =
      IntSet.fromList
        [n + 1 | (n, l) <- zip [1 ..] (T.lines blanked), endsInBackslash l]

-- | The line of the first macro the module defines as a context, as
-- @HasCallStack =>@, that heads a part a Haddock documents, and the macro.
contextBeforeHaddock ::
  -- | The module, directives and all.
  Text ->
  -- | Its branches, parsed.
  NonEmpty ParsedModule ->
  Maybe (Int, Text)
contextBeforeHaddock source branches
  | Set.null contexts = Nothing
  | otherwise =
      listToMaybe
        [ found
        | parsed <- NE.toList branches,
          L _ (HsDocTy _ part _) <- listify documented (pmModule parsed),
          Just found <- [headedBy part]
        ]
  where
    contexts =
      Set.fromList
        [ name
        | (name, Macro Nothing body) <- definedMacros source,
          "=>" `T.isSuffixOf` body
        ]
    documented :: LHsType GhcPs -> Bool
    documented = \case
      L _ HsDocTy{} -> True
      _ -> False
    headedBy (L _ t) = case t of
      HsAppTy _ f _ -> headedBy f
      HsTyVar _ _ (L l n)
        | name <- T.pack (occNameString (rdrNameOcc n)),
          Set.member name contexts ->
            (,name) . spanStartLine <$> spanOf l
      _ -> Nothing

-- | The lines imports must not be sorted across: the directives of every
-- conditional but one that only continues the item above it, such as a
-- @hiding@ clause written behind a condition.
importBarriers ::
  -- | The lines among the imports of every branch, as 'importLayout' gives
  -- them.
  IntMap Bool ->
  -- | Every conditional of the module, nested ones included.
  [GroupSpec] ->
  [Int]
importBarriers layout groups =
  sort [l | g <- groups, not (continuesAnItem g), l <- gsOwnLines g]
  where
    continuesAnItem g =
      let (from, to) = gsWhole g
          held =
            IntMap.elems $
              fst (IntMap.split to (snd (IntMap.split from layout)))
       in not (null held) && not (or held)

-- | Formatting that spends the lines it formats out of the budget left, or
-- fails with a 'CppError', and files what each configuration came to under
-- its text.
type Spending =
  ExceptT CppError (State (Int, Map Text (Doc, CommentSummary)))

-- | Give up on formatting the module.
refuse :: CppError -> Spending a
refuse = throwE

-- | Take lines out of the budget, or give up where fewer are left.
spend :: Int -> Spending ()
spend n = do
  budget <- lift (gets fst)
  when (budget < n) (refuse TooManyConfigurations)
  lift (modify' (\(left, filed) -> (left - n, filed)))

-- | What formatting comes to, or 'Nothing' where it fails for a reason
-- other than the budget running out. What it spent stays spent.
attempt :: Spending a -> Spending (Maybe a)
attempt formatting =
  (Just <$> formatting) `catchE` \case
    TooManyConfigurations -> refuse TooManyConfigurations
    _ -> pure Nothing

-- | What every configuration of a module is parsed and printed with.
data Formatter = Formatter
  { -- | What to parse a configuration with.
    formatterParser :: ParserConfig,
    -- | What to print it with.
    formatterRender :: RenderConfig,
    -- | The file this is, for the positions in a parse error.
    formatterPath :: FilePath,
    -- | The module's macro lines, which every configuration leaves out.
    formatterMacroLines :: [(Int, Text)]
  }

-- | A configuration, with what its conditionals come to worked out once
-- for everything that asks.
data Reading = Reading
  { -- | How it was reached.
    readingReached :: Reached,
    -- | Its text.
    readingSource :: Text,
    -- | Its conditionals.
    readingForest :: Either CppError [GroupSpec],
    -- | Its conditionals split one at a time, those asking the question of
    -- 'readingPragma' together, with the reading of the baseline they are
    -- varied against, where it has any.
    readingApart :: Maybe (Variation, Reading),
    -- | The conditional to split on first, where one holds a pragma that
    -- changes how the rest is parsed.
    readingPragma :: Maybe GroupSpec,
    -- | What it comes to formatted as it is, where it holds no conditional.
    readingFormatted :: Either CppError (Doc, CommentSummary)
  }

-- | Read a configuration.
reading ::
  -- | What to parse and print each configuration with.
  Formatter ->
  -- | How this configuration was reached.
  Reached ->
  -- | Input text.
  Text ->
  Reading
reading formatter reached source =
  Reading
    { readingReached = reached,
      readingSource = source,
      readingForest = forest,
      readingApart = do
        apart <- withForest (\f -> variations (tied f) f source)
        let baseline = without (vaBaselineDropped apart) reached
        pure (apart, reading formatter baseline (vaBaseline apart)),
      readingPragma = pragma,
      readingFormatted =
        formatSingleConfig
          formatter
          reached
          (withoutOpaque (formatterMacroLines formatter) source)
    }
  where
    forest = readConditionals source
    withForest f = either (const Nothing) f forest
    pragma =
      withForest (\f -> splitOnPragma (formatterParser formatter) f source)
    tied f = maybe [] (`sameGuard` f) pragma

-- | What the first configuration 'formatAllConfigs' formats comes to, where
-- it is sure to start with the one every question is answered in with its
-- first branch.
firstFormatted :: Reading -> Maybe (Either CppError (Doc, CommentSummary))
firstFormatted r = case (readingForest r, readingApart r) of
  (Left _, _) -> Nothing
  (Right _, Nothing) -> Just (readingFormatted r)
  (Right _, Just (_, baseline))
    | isNothing (readingPragma r) -> firstFormatted baseline
    | otherwise -> Nothing

-- | Start working out on the side, as far as its outermost constructor,
-- what each configuration formats first.
aheadOf :: [Reading] -> a -> a
aheadOf readings x = foldr par x (mapMaybe firstFormatted readings)

-- | Format every configuration of a module, and merge them into one
-- document, with what they found besides their code.
formatAllConfigs ::
  -- | What to parse and print each configuration with.
  Formatter ->
  -- | The configuration.
  Reading ->
  Spending (Doc, CommentSummary)
formatAllConfigs formatter r = do
  forest <- except (readingForest r)
  case readingApart r of
    Nothing -> do
      done <- lift (gets (Map.lookup source . snd))
      case done of
        Just found -> pure found
        Nothing -> do
          spend (linesHeld source)
          found <- except (readingFormatted r)
          lift (modify' (fmap (Map.insert source found)))
          pure found
    Just (apart, baseline) -> do
      budget <- lift (gets fst)
      let pragma = readingPragma r
          least = max 1 (linesHeld (vaBaseline apart))
          linearly =
            linearCost (budget `div` least) forest * least <= budget
              && all (reachedAsOne forest) pragma
      base <-
        if isNothing pragma || linearly
          then
            attempt (formatAllConfigs formatter baseline)
          else pure Nothing
      fragmented <- case (pragma, base) of
        (Nothing, Just b) ->
          join <$> attempt (inFragments formatter reached forest source b)
        _ -> pure Nothing
      linear <- case (fragmented, base) of
        (Nothing, Just b) | linearly -> oneAtATime apart b
        _ -> pure Nothing
      case fragmented <|> linear of
        Just found -> pure found
        Nothing -> case maybeToList pragma <> forest of
          g : _ -> together formatter reached (configurationsOn g forest source)
          [] ->
            error "Tilia: a module that varies has a conditional to split on"
  where
    reached = readingReached r
    source = readingSource r
    oneAtATime apart base = do
      varied <- attempt (separately formatter reached apart base)
      pure $ do
        (merged, found) <- varied
        d <- combine Broken (fst base) merged
        pure (d, found)

-- | Do the configurations that vary every conditional asking a question as
-- one, holding the others at their first branch, reach each of them?
reachedAsOne ::
  -- | The conditionals at the top level.
  [GroupSpec] ->
  -- | One asking the question.
  GroupSpec ->
  Bool
reachedAsOne forest gs =
  and
    [ gsGuards g /= gsGuards gs
    | o <- forest,
      gsGuards o /= gsGuards gs,
      g <- allGroups (concat (drop 1 (gsNested o)))
    ]

-- | How many configurations varying a module's conditionals one at a time
-- goes through, counted as far as one past the given number.
linearCost :: Int -> [GroupSpec] -> Int
linearCost limit forest = go forest
  where
    go = \case
      [] -> 1
      gss ->
        upTo
          0
          ( go (concatMap (`nestedIn` 0) gss)
              : [ go (nestedIn gs i <> concatMap (`nestedIn` 0) others)
                | (k, gs) <- zip [0 :: Int ..] gss,
                  let others = [o | (j, o) <- zip [0 ..] gss, j /= k],
                  i <- [1 .. gsCount gs - 1]
                ]
          )
    upTo acc = \case
      _ | acc > limit -> acc
      [] -> acc
      x : xs -> upTo (acc + x) xs

-- | A single variation.
data Variation = Variation
  { -- | Every question answered with its first branch.
    vaBaseline :: Text,
    -- | The line ranges that answer leaves out.
    vaBaselineDropped :: [(Int, Int)],
    -- | One question varied, with all the others held at the baseline.
    vaGroups :: [Configurations]
  }

-- | Split a module on every conditional at its top level, one at a time,
-- but on those asking one question together.
variations ::
  -- | The conditionals asking the question, nested ones included, which
  -- each configuration answers alike.
  [GroupSpec] ->
  -- | The conditionals at the top level.
  [GroupSpec] ->
  -- | The module.
  Text ->
  Maybe Variation
variations tied forest source
  | null forest = Nothing
  | otherwise =
      Just
        Variation
          { vaBaseline = held (const 0),
            vaBaselineDropped = gone (const 0),
            vaGroups =
              [ Configurations
                  { cfgGuards = gsGuards gs,
                    cfgTexts = [held (varying k i) | i <- [0 .. gsCount gs - 1]],
                    cfgDropped =
                      [gone (varying k i) | i <- [0 .. gsCount gs - 1]],
                    cfgWholes = Varied (fmap gsWhole unit),
                    cfgConditionals = fmap gsConditional unit
                  }
              | (k, unit@(gs : _)) <- zip [0 ..] units
              ]
          }
  where
    units = case break isTied forest of
      (before, _ : after) ->
        fmap pure before <> [tied] <> [[gs] | gs <- after, not (isTied gs)]
      _ -> fmap pure forest
    isTied gs = gsWhole gs `elem` fmap gsWhole tied
    held at =
      blanking
        (concat [blankingFor gs (at k) | (k, unit) <- numbered, gs <- unit])
        source
    gone at = concat [droppedFor gs (at k) | (k, unit) <- numbered, gs <- unit]
    numbered = zip [0 :: Int ..] units
    varying k i j = if j == k then i else 0

-- | Vary each conditional on its own, holding the others at their first
-- branch.
separately ::
  -- | What to parse and print each configuration with.
  Formatter ->
  -- | How this configuration was reached.
  Reached ->
  -- | The conditionals to vary, and the baseline to hold them against.
  Variation ->
  -- | What the baseline was formatted to.
  (Doc, CommentSummary) ->
  Spending ([(Varied, Doc)], CommentSummary)
separately formatter reached v (baseDoc, baseFound) = do
  groups <-
    aheadOf (catMaybes (concat readings)) . for readings . traverse $
      maybe (pure (baseDoc, mempty)) (formatAllConfigs formatter)
  let merged =
        zipWith
          (mergeOf formatter (reachedLines reached))
          (vaGroups v)
          (fmap (fmap fst) groups)
  pure
    ( foldr (par . snd) merged merged,
      baseFound <> foldMap (foldMap snd) groups
    )
  where
    readings =
      [ [ if t == vaBaseline v
            then Nothing
            else Just (reading formatter (answering c i reached) t)
        | (i, t) <- zip [0 ..] (cfgTexts c)
        ]
      | c <- vaGroups v
      ]

-- | Format each fragment of declarations the outermost conditionals reach
-- on its own, and put the results into what the baseline was formatted to.
--
-- 'Nothing' where the module cannot be taken apart like that.
inFragments ::
  -- | What to parse and print each configuration with.
  Formatter ->
  -- | How this configuration was reached.
  Reached ->
  -- | The outermost conditionals.
  [GroupSpec] ->
  -- | Input text.
  Text ->
  -- | What the baseline was formatted to.
  (Doc, CommentSummary) ->
  Spending (Maybe (Doc, CommentSummary))
inFragments formatter reached forest source (baseDoc, baseFound) =
  case parts of
    Nothing -> pure Nothing
    Just (body, ps) -> do
      let readings =
            [ reading formatter (without gone reached) t
            | (_, (t, gone)) <- ps
            ]
      formatted <-
        aheadOf readings $
          traverse (formatAllConfigs formatter) readings
      pure $ do
        doc <- reassembled body (zip (fmap fst ps) (fmap fst formatted))
        pure
          ( doc,
            baseFound
              <> mconcat
                [ carriedBetween (fragmentLines body f) found
                | ((f, _), (_, found)) <- zip ps formatted
                ]
          )
  where
    parts = do
      body <- bodyOf baseDoc
      ps <-
        traverse
          (\f -> (,) f <$> fragmentText body forest source f)
          (fragmentsOf body forest)
      pure (body, ps)

-- | The outermost conditional around a @LANGUAGE@ or options pragma that
-- changes how the rest of the module is parsed, if there is one.
--
-- Formatting a fragment on its own takes the rest of the module to be
-- parsed alike in every configuration.
splitOnPragma :: ParserConfig -> [GroupSpec] -> Text -> Maybe GroupSpec
splitOnPragma parser forest source =
  listToMaybe
    [ o
    | g <- groups,
      holdsPragma g,
      any (not . readAlike parser baseline . answered g) [1 .. gsCount g - 1],
      o <- forest,
      fst (gsWhole o) <= fst (gsWhole g),
      snd (gsWhole g) <= snd (gsWhole o)
    ]
  where
    groups = allGroups forest
    baseline = blanking (concatMap (`blankingFor` 0) groups) source
    answered g i =
      blanking
        ( blankingFor g i
            <> concat [blankingFor h 0 | h <- groups, gsWhole h /= gsWhole g]
        )
        source
    written = T.lines source
    holdsPragma g =
      let (from, to) = gsWhole g
       in any pragma (take (to - from + 1) (drop (from - 1) written))
    pragma l =
      let u = T.toUpper l
       in "{-#" `T.isInfixOf` u
            && ("LANGUAGE" `T.isInfixOf` u || "OPTIONS" `T.isInfixOf` u)

-- | Vary the conditionals together, one group at a time.
together ::
  -- | What to parse and print each configuration with.
  Formatter ->
  -- | How this configuration was reached.
  Reached ->
  -- | The group to split on, and the branch texts to split it into.
  Configurations ->
  Spending (Doc, CommentSummary)
together formatter reached c
  | differentlyRead parser c = settledOr (fst <$> formatted False)
  | otherwise =
      (fst <$> formatted False) `catchE` \case
        e@(ConfigurationNotParsed answers _)
          | isNothing (implied answers) -> settledOr (refuse e)
        e -> refuse e
  where
    settledOr unsettled = do
      (found, blind) <- formatted True
      if blind then unsettled else pure found
    readingOf = reading formatter
    parser = formatterParser formatter
    texts = cfgTexts c
    formatted settle = do
      let (settledBy, tries) =
            unzip . (if settle then settling else fmap ((,) [] . pure)) $
              [(answering c i reached, t) | (i, t) <- zip [0 ..] texts]
          answers = fmap NE.head tries
      found <- fmap catMaybes . for (zip [0 ..] tries) $ \(i, ts) ->
        if null (unconditionalErrors (snd (NE.head ts)))
          then Just . (,) i <$> firstParsed ts
          else pure Nothing
      docs <-
        except . traverse (complete (fmap (fmap fst) found)) $
          zip [0 ..] (fmap snd answers)
      let settledIn i
            | Just _ <- lookup i found = settledBy !! i
            | otherwise = foldMap ((settledBy !!) . fst) (listToMaybe found)
          settled = settledAcross (fmap settledIn [0 .. length answers - 1])
          ranges = mapMaybe (conditionalRange . settledConditional) settled
          varied = Varied (variedLines (variedBy parser c) <> ranges)
          merged =
            merge
              (reachedLines reached)
              (cfgConditionals c)
              (cfgGuards c)
              varied
              settled
              docs
      pure ((merged, foldMap (snd . snd) found), blindOver ranges merged)
    firstParsed ((r, t) :| rest) =
      formatAllConfigs formatter (readingOf r t) `catchE` \case
        ConfigurationNotParsed answers _
          | isNothing (implied answers),
            next : more <- rest ->
              firstParsed (next :| more)
        e -> refuse e
    blindOver ranges d = case d of
      DCppChoice [] bs _
        | fmap fst bs == fmap guardText (cfgGuards c),
          any (\(a, b) -> any (\(from, to) -> a <= to && from <= b) ranges) $
            printedFrom d ->
            True
      _ -> getAny (foldChildren (Any . blindOver ranges) d)
    complete found (i, t) = case lookup i found of
      Just d -> Right d
      Nothing -> case listToMaybe found >>= errorBranch (cfgWholes c) t . snd of
        Just d -> Right d
        Nothing ->
          Left
            . AbortingAlternative
            . maybe 0 dLine
            . listToMaybe
            . unconditionalErrors
            $ t

-- | The document of a configuration whose varied lines hold nothing but an
-- @#error@: a sibling's, with what it printed from those lines taken out.
errorBranch :: Varied -> Text -> Doc -> Maybe Doc
errorBranch (Varied ranges) source reference =
  foldl step (Just reference) ranges
  where
    sourceLines' = zip [1 ..] (T.lines source)
    errors = unconditionalErrors source
    step acc (from, to) = do
      doc <- acc
      let inside n = from <= n && n <= to
          here = filter (inside . dLine) errors
          errorLine n = any (\d -> dLine d <= n && n <= dLastLine d) here
          onlyErrors =
            all
              (\(n, l) -> not (inside n) || errorLine n || T.null (T.strip l))
              sourceLines'
          contained s = inside (spanStartLine s) && inside (spanEndLine s)
          outside d = case d of
            DLocated s _ | contained s -> mempty
            DCppChoice{}
              | lines'@(_ : _) <- printedFrom d,
                all (\(a, b) -> inside a && inside b) lines' ->
                  mempty
              | otherwise -> d
            _ -> mapChildren outside d
      if not (null here) && onlyErrors then Just (outside doc) else Nothing

-- | Format one configuration's code with the ordinary printer, and gather
-- what else it holds.
formatSingleConfig ::
  -- | What to parse and print it with.
  Formatter ->
  -- | How this configuration was reached.
  Reached ->
  -- | The configuration itself, with no directives left in it.
  Text ->
  Either CppError (Doc, CommentSummary)
formatSingleConfig formatter reached text =
  case parseConfiguration
    (formatterParser formatter)
    (formatterPath formatter)
    (reachedLines reached)
    (reachedLines reached)
    text of
    Left e -> Left (ConfigurationNotParsed (reachedAnswers reached) e)
    Right parsed ->
      let render =
            (formatterRender formatter)
              { rcExtensions = pmExtensions parsed
              }
          (document, loose) = renderConfiguration render parsed
       in Right
            ( apartAtDirectives
                (`directivePresentOnLine` reachedLines reached)
                document,
              summarizeComments
                (fmap startPoint (haddockSpans (pmGathered parsed)))
                loose
                (comments (pmSource parsed))
            )

-- | Leave an empty line between two items of a run with a directive
-- written between them, which sets a conditional apart from what is
-- around it.
apartAtDirectives ::
  -- | Is a directive written on the line?
  (Int -> Bool) ->
  -- | The document.
  Doc ->
  Doc
apartAtDirectives directiveOn d =
  mconcat (zipWith3 apart xs (scanl ending Nothing xs) beginnings)
  where
    xs = spine d
    beginnings = drop 1 (scanr beginning Nothing xs)
    ending previous x = maybe previous (Just . maximum . fmap snd) (lines' x)
    beginning x next = maybe next (Just . minimum . fmap fst) (lines' x)
    lines' = nonEmpty . printedFrom
    apart x above below = case x of
      DDeclDelimiter style
        | style /= DeclSeparate,
          Just a <- above,
          Just b <- below,
          any directiveOn [a + 1 .. b - 1] ->
            DDeclDelimiter DeclSeparate
      DLocated s _
        | not (any directiveOn [spanStartLine s .. spanEndLine s]) -> x
      _ -> mapChildren (apartAtDirectives directiveOn) x

-- | How a configuration was reached, and what to call it.
data Reached = Reached
  { -- | Which branch each question was answered with, outermost first.
    reachedAnswers :: [([Guard], Int)],
    -- | Every line the author wrote, except for those written inside a
    -- branch this configuration did not take.
    reachedLines :: Lines
  }

-- | The configuration nothing has been decided about yet.
noAnswers :: Text -> Reached
noAnswers source =
  Reached
    { reachedAnswers = [],
      reachedLines = linesOf (Written source)
    }

-- | Answer one group's question with the branch at the given index.
answering :: Configurations -> Int -> Reached -> Reached
answering c i reached =
  reached
    { reachedAnswers = reachedAnswers reached <> [(cfgGuards c, i)],
      reachedLines =
        dropping
          (concat (take 1 (drop i (cfgDropped c))))
          (reachedLines reached)
    }

-- | Leave out the branches a baseline does not take, without answering
-- anything: the baseline is every question taken at its first branch, and
-- which question is being varied is not settled until 'answering'.
without :: [(Int, Int)] -> Reached -> Reached
without gone reached =
  reached{reachedLines = dropping gone (reachedLines reached)}

-- | The conditionals each answer settles or rules branches out of, and its
-- configurations with what they rule out left out.
settling ::
  [(Reached, Text)] ->
  -- | The branches each answer can take, and its configurations.
  [([(GroupSpec, [Int])], NonEmpty (Reached, Text))]
settling given =
  [ (more, fmap taking (settled :| [more | length more > length settled]))
  | ((reached, t), candidates) <- zip given found,
    let among ws =
          [ s
          | s@(gs, ks) <- candidates,
            case ks of
              [_] -> Set.member (gsWhole gs) ws
              _ -> length ks < gsCount gs && Set.member (gsWhole gs) whole
          ]
        settled = among open
        more = among (open <> covered)
        taking ss =
          ( reached
              { reachedAnswers =
                  reachedAnswers reached
                    <> [(gsGuards gs, k) | (gs, [k]) <- ss],
                reachedLines =
                  dropping (concatMap ruledOut ss) (reachedLines reached)
              },
            blanking
              ( concatMap ruledOut ss
                  <> [r | (gs, [_]) <- ss, r <- gsOwnRanges gs]
              )
              t
          )
  ]
  where
    found =
      [ if null (unconditionalErrors t)
          then walk (implied (reachedAnswers r)) (scanConditionals t)
          else []
      | (r, t) <- given
      ]
    open = Set.fromList [gsWhole gs | (gs, _ : _ : _) <- concat found]
    whole =
      Set.fromList
        [gsWhole gs | (gs, ks) <- concat found, length ks == gsCount gs]
    covered =
      Set.fromList
        [ gsWhole gs
        | (gs, [_]) <- concat found,
          all (\k -> Set.member (gsWhole gs, k) taken) [0 .. gsCount gs - 1]
        ]
    taken = Set.fromList [(gsWhole gs, k) | (gs, [k]) <- concat found]
    ruledOut (gs, ks) =
      [r | (i, r) <- zip [0 ..] (gsBranches gs), i `notElem` ks]
    walk (Just known) (Just forest) = concatMap (visit known) forest
    walk _ _ = []
    visit known gs =
      let ks = possibleBranches known gs
       in (gs, ks) : concatMap (concatMap (visit known) . nestedIn gs) ks

-- | The conditionals some answer settles or rules branches of out, given
-- the branches each answer can take of them.
settledAcross :: [[(GroupSpec, [Int])]] -> [Settled]
settledAcross perAnswer =
  [ Settled
      { settledConditional = gsConditional gs,
        settledBranches =
          [ lookup (gsWhole gs) [(gsWhole g, ks) | (g, ks) <- ss]
          | ss <- perAnswer
          ]
      }
  | gs <- Map.elems (Map.fromList [(gsWhole g, g) | (g, _) <- concat perAnswer])
  ]

-- | How many times over one call may format the lines of a module.
configurationBudget :: Int
configurationBudget = 64

-- | Merge the documents one group's configurations printed to, with the
-- lines its answer can change.
mergeOf ::
  -- | What the configurations were parsed and printed with.
  Formatter ->
  -- | The module as written.
  Lines ->
  -- | The configurations.
  Configurations ->
  -- | What each of them printed to.
  [Doc] ->
  (Varied, Doc)
mergeOf formatter written c docs =
  ( varied,
    merge
      written
      (cfgConditionals c)
      (cfgGuards c)
      varied
      []
      docs
  )
  where
    varied = variedBy (formatterParser formatter) c

-- | Are a group's configurations read with different extensions?
differentlyRead ::
  -- | What they are parsed with.
  ParserConfig ->
  -- | The configurations.
  Configurations ->
  Bool
differentlyRead parser c =
  or (zipWith (\a b -> not (readAlike parser a b)) texts (drop 1 texts))
  where
    texts = cfgTexts c

-- | The lines a group's answer can change: every line where its
-- configurations are read differently.
variedBy ::
  -- | What they are parsed with.
  ParserConfig ->
  -- | The configurations.
  Configurations ->
  Varied
variedBy parser c
  | differentlyRead parser c = Varied [(1, maxBound)]
  | otherwise = cfgWholes c