packages feed

lynceus-0.0.1.0: src/Lynceus/Options.hs

{-# LANGUAGE LambdaCase #-}

-- |
-- Module      :  Lynceus.Options
-- Copyright   :  © 2026–present Mark Karpov
-- License     :  BSD 3 clause
--
-- Maintainer  :  Mark Karpov <markkarpov92@gmail.com>
-- Stability   :  experimental
-- Portability :  portable
--
-- The options of a run and the command line that sets them.
module Lynceus.Options
  ( Options (..),
    defaultOptions,
    parseArguments,
    usage,
  )
where

import Control.Monad (foldM)
import Data.List (dropWhileEnd)
import Data.Text (Text)
import Data.Text qualified as T
import System.Console.GetOpt
import Text.Printf (printf)
import Text.Read (readMaybe)

-- | How the benchmarks were asked to run.
data Options = Options
  { -- | How many runs to measure after the one that warms up.
    optRuns :: Int,
    -- | Run only the benchmarks whose group or name holds this.
    optMatch :: Maybe Text,
    -- | How far one benchmark's allocations or instructions may move from
    -- the record, as a fraction.
    optTolerance :: Double,
    -- | How far the allocations or instructions of all the benchmarks of a
    -- group may move together, as a fraction.
    optGroupTolerance :: Double,
    -- | Where to save the time and instructions of every benchmark.
    optSave :: Maybe FilePath,
    -- | What an earlier run saved, to compare this one with.
    optBaseline :: Maybe FilePath
  }
  deriving (Eq, Show)

-- | The options of a run that is given none.
defaultOptions :: Options
defaultOptions =
  Options
    { optRuns = 1,
      optMatch = Nothing,
      optTolerance = 0.005,
      optGroupTolerance = 0.0005,
      optSave = Nothing,
      optBaseline = Nothing
    }

-- | What one command line argument asks for.
data Setting
  = Help
  | Set (Options -> Either String Options)

-- | Parse the command line on top of the given options, giving 'Nothing'
-- where it asks for help.
parseArguments :: Options -> [String] -> Either String (Maybe Options)
parseArguments options args =
  case getOpt Permute (descriptions options) args of
    (settings, [], [])
      | any isHelp settings -> Right Nothing
      | otherwise -> Just <$> foldM applied options settings
    (_, extra, errors) ->
      Left
        (concat errors <> concatMap (\a -> "unexpected " <> a <> "\n") extra)
  where
    isHelp = \case
      Help -> True
      Set _ -> False
    applied o = \case
      Help -> Right o
      Set f -> f o

-- | The usage text, giving the given options as the defaults.
usage :: Options -> String
usage options =
  usageInfo
    "Measure what the benchmarks cost and check it against the record.\n\n\
    \Usage: BENCHMARK [OPTIONS]\n"
    (descriptions options)

-- | The options of the command line, with the given options as the
-- defaults.
descriptions :: Options -> [OptDescr Setting]
descriptions defaults =
  [ Option
      []
      ["runs"]
      (ReqArg (\s -> Set (\o -> (\n -> o{optRuns = n}) <$> positive s)) "N")
      ( "How many runs to measure after the one that warms up"
          <> defaulting (show (optRuns defaults))
      ),
    Option
      []
      ["match"]
      (ReqArg (\s -> Set (\o -> Right o{optMatch = Just (T.pack s)})) "TEXT")
      "Run only the benchmarks whose group or name holds TEXT",
    Option
      []
      ["tolerance"]
      ( ReqArg
          (\s -> Set (\o -> (\x -> o{optTolerance = x}) <$> percent s))
          "PERCENT"
      )
      ( "How far one benchmark may move from the record"
          <> defaulting (percentage (optTolerance defaults))
      ),
    Option
      []
      ["group-tolerance"]
      ( ReqArg
          (\s -> Set (\o -> (\x -> o{optGroupTolerance = x}) <$> percent s))
          "PERCENT"
      )
      ( "How far the benchmarks of a group may move together"
          <> defaulting (percentage (optGroupTolerance defaults))
      ),
    Option
      []
      ["save"]
      (ReqArg (\s -> Set (\o -> Right o{optSave = Just s})) "FILE")
      "Save the time and instructions of every benchmark to FILE",
    Option
      []
      ["baseline"]
      (ReqArg (\s -> Set (\o -> Right o{optBaseline = Just s})) "FILE")
      "Compare with what an earlier run saved to FILE",
    Option [] ["help"] (NoArg Help) "Show this help text"
  ]
  where
    positive s = case readMaybe s of
      Just n | n > 0 -> Right n
      _ -> Left ("not a positive number of runs: " <> s <> "\n")
    percent s = case readMaybe s of
      Just x | x >= 0 -> Right (x / 100)
      _ -> Left ("not a percentage: " <> s <> "\n")
    defaulting value = " (default: " <> value <> ")"
    percentage x =
      dropWhileEnd (== '.') (dropWhileEnd (== '0') (printf "%.4f" (100 * x)))