-- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com-- SPDX-License-Identifier: MITmodule CLI.Parsers whereimport CLI.Typesimport Data.Char (isDigit, toLower, toUpper)import Data.List (intercalate)import Data.Version (showVersion)import Deps (Acyclic, Duration (..), certainty)import LaTeX (defaultMeetLength, defaultMeetPopularity)import Lining (LineFormat (..))import Loggerimport Margin (defaultMargin)import Mustimport Options.Applicativeimport Parser (Form (..))import Paths_phino (version)import Sugar (SugarType (..))import Text.Printf (printf)import Text.Read (readMaybe)validateIntOption :: (Int -> Bool) -> String -> Int -> ReadM IntvalidateIntOption cmp msg num | cmp num = return num | otherwise = readerError msgboundedIntOption :: ReadM IntboundedIntOption = do num <- auto :: ReadM Integer if num < toInteger (minBound :: Int) || num > toInteger (maxBound :: Int) then readerError (printf "value must be between %d and %d" (minBound :: Int) (maxBound :: Int)) else return (fromInteger num)optLogLevel :: Parser LogLeveloptLogLevel = option parseLogLevel ( long "log-level" <> metavar "LEVEL" <> help ("Log level (" <> intercalate ", " (map show [DEBUG, INFO, ERROR, NONE]) <> ")") <> value ERROR <> showDefault ) where parseLogLevel :: ReadM LogLevel parseLogLevel = eitherReader $ \lvl -> case map toUpper lvl of "DEBUG" -> Right DEBUG "INFO" -> Right INFO "ERROR" -> Right ERROR "ERR" -> Right ERROR "NONE" -> Right NONE _ -> Left $ "unknown log-level: " <> lvloptLogLines :: Parser IntoptLogLines = option (boundedIntOption >>= validateIntOption (>= -1) "--log-lines must be >= -1") (long "log-lines" <> metavar "LINES" <> help "Amount of lines printed to console per each log operation (0 - print nothing, -1 - no limits)" <> value 25 <> showDefault)optRule :: Parser [FilePath]optRule = many (strOption (long "rule" <> metavar "[FILE]" <> help "Path to custom rule"))optInputFormat :: Parser IOFormatoptInputFormat = option (parseIOFormat "input") (long "input" <> metavar "FORMAT" <> help "Expression input format (phi, xmir)" <> value PHI <> showDefault)parseIOFormat :: String -> ReadM IOFormatparseIOFormat type' = eitherReader $ \format -> case (map toLower format, type') of ("xmir", _) -> Right XMIR ("phi", _) -> Right PHI ("latex", "output") -> Right LATEX _ -> Left (printf "The value '%s' can't be used for '--%s' option, use --help to check possible values" format type')optMonoform :: Parser FormoptMonoform = flag POLYFORM MONOFORM (long "monoform" <> help "Reject a π-expression that spells some symbols in ASCII and others in Unicode, such as -> inside β¦ β§")optOutputFormat :: Parser IOFormatoptOutputFormat = option (parseIOFormat "output") (long "output" <> metavar "FORMAT" <> help (printf "Result and intermediate (see %s option(s)) expressions output format (phi, xmir, latex)" _intermediateOptions) <> value PHI <> showDefault)argInputFile :: Parser (Maybe FilePath)argInputFile = optional (argument str (metavar "FILE" <> help "Path to input file"))optMaxDepth :: Parser IntoptMaxDepth = option (boundedIntOption >>= validateIntOption (> 0) "--max-depth must be positive") (long "max-depth" <> metavar "DEPTH" <> help "Maximum number of rewriting iterations per rule" <> value 25 <> showDefault)optMaxCycles :: Parser IntoptMaxCycles = option (boundedIntOption >>= validateIntOption (> 0) "--max-cycles must be positive") (long "max-cycles" <> metavar "CYCLES" <> help "Maximum number of rewriting cycles across all rules" <> value 25 <> showDefault)optMaxSteps :: Parser IntoptMaxSteps = option (boundedIntOption >>= validateIntOption (> 0) "--max-steps must be positive") (long "max-steps" <> metavar "STEPS" <> help "Maximum number of nested morphing and dataization steps" <> value 1000 <> showDefault)optMaxFirings :: Parser (Maybe Int)optMaxFirings = optional ( option (boundedIntOption >>= validateIntOption (> 0) "--max-firings must be positive") (long "max-firings" <> metavar "FIRINGS" <> help "Maximum number of Ξ» functions the whole run may fire, unlimited unless given") )durationOption :: ReadM DurationdurationOption = do given <- str case readMaybe given :: Maybe Integer of Just _ -> Duration given . fromIntegral <$> (boundedIntOption >>= validateIntOption (> 0) "--max-seconds must be positive") Nothing -> case readMaybe given :: Maybe Double of Just span' | isNaN span' || isInfinite span' -> readerError (printf "--max-seconds must be a finite number, not '%s'" given) | span' >= fromIntegral (maxBound :: Int) -> readerError (printf "value must be between %d and %d" (minBound :: Int) (maxBound :: Int)) | span' > 0 -> return (Duration given span') | otherwise -> readerError "--max-seconds must be positive" Nothing -> readerError (printf "cannot parse '%s' as a number of seconds" given)optMaxSeconds :: Parser (Maybe Duration)optMaxSeconds = optional ( option durationOption (long "max-seconds" <> metavar "SECONDS" <> help "Maximum number of seconds the whole run may take, such as 2 or 0.5, unlimited unless given") )optMaxNodes :: Parser (Maybe Int)optMaxNodes = optional ( option (boundedIntOption >>= validateIntOption (> 0) "--max-nodes must be positive") (long "max-nodes" <> metavar "NODES" <> help "Maximum number of nodes the term of the run may grow to, unlimited unless given") )optMaxMemory :: Parser (Maybe Int)optMaxMemory = optional ( option (eitherReader bytes >>= validateIntOption (> 0) "--max-memory must be positive") (long "max-memory" <> metavar "BYTES" <> help "Maximum size of the live heap the run may grow to, such as 512M or 8G, unlimited unless given") ) where bytes :: String -> Either String Int bytes spelling = case span isDigit spelling of (digits@(_ : _), unit) -> maybe malformed (bounded . (read digits *)) (lookup (map toUpper unit) (zip ["", "K", "M", "G", "T"] (iterate (* 1024) 1))) _ -> malformed bounded :: Integer -> Either String Int bounded num | num > toInteger (maxBound :: Int) = Left (printf "--max-memory must not exceed %d bytes" (maxBound :: Int)) | otherwise = Right (fromInteger num) malformed :: Either String Int malformed = Left "--max-memory must be a number of bytes, optionally ending with K, M, G or T"optMargin :: Parser IntoptMargin = option (boundedIntOption >>= validateIntOption (> 0) "--margin must be positive") (long "margin" <> help "The maximum right margin for the printed π-expressions" <> value defaultMargin <> showDefault)optMeetPopularity :: Parser (Maybe Int)optMeetPopularity = optional ( option ( boundedIntOption >>= validateIntOption (> 0) "--meet-popularity must be positive" >>= validateIntOption (<= 100) "--meet-popularity must be <= 100" ) ( long "meet-popularity" <> metavar "PERCENTAGE" <> help (printf "The minimum popularity of an expression in order to be suitable for \\phinoMeet{}, in percentage (default: %d)" defaultMeetPopularity) ) )optMeetLength :: Parser (Maybe Int)optMeetLength = optional ( option (boundedIntOption >>= validateIntOption (> 0) "--meet-length must be positive") ( long "meet-length" <> metavar "NODES" <> help (printf "The minimum length of an expression that fits into \\phinoMeet{}, in AST nodes (default: %d)" defaultMeetLength) ) )optDepthSensitive :: Parser BooloptDepthSensitive = switch (long "depth-sensitive" <> help "Fail if rewriting is not finished after reaching max attempts (see --max-cycles or --max-depth)")optNonumber :: Parser BooloptNonumber = switch (long "nonumber" <> help "Turn off equation auto numbering in LaTeX rendering (see --output option)")optSequence :: Parser BooloptSequence = switch (long "sequence" <> help "Result output contains all intermediate π-expressions concatenated with EOL")optHeaders :: Parser BooloptHeaders = switch ( long "headers" <> help "Prefix every intermediate step (see --sequence) with a header line: step number, the rule that produced it, and AST node count before and after that rule" )optCanonize :: Parser BooloptCanonize = switch (long "canonize" <> help "Rename all functions attached to Ξ» binding with Fn1, Fn2, etc.")optExpression :: Parser (Maybe String)optExpression = optional (strOption (long "expression" <> metavar "NAME" <> help "Name for 'phiExpression' element when rendering to LaTeX (see --output option)"))optLabel :: Parser (Maybe String)optLabel = optional (strOption (long "label" <> metavar "NAME" <> help "Name for 'label' element when rendering to LaTeX (see --output option)"))optMeetPrefix :: Parser (Maybe String)optMeetPrefix = optional (strOption (long "meet-prefix" <> metavar "PREFIX" <> help "Prefix to be inserted before index in \\phinoMeet{} and \\phinoAgain{} LaTeX functions, e.g. \\phinoMeet{foo:1}"))optBreakpoint :: Parser (Maybe FilePath)optBreakpoint = optional (strOption (long "breakpoint" <> metavar "FILE" <> help "The name of the first unmatched rule which leads to stopping entire rewriting process and returning original expression"))optHide :: Parser [String]optHide = many ( strOption ( long "hide" <> metavar "FQN" <> help "Location of object to exclude from result and intermediate expressions after rewriting. Must be a valid dispatch expression; e.g. Q.org.eolang" ) )optShow :: Parser [String]optShow = many ( strOption ( long "show" <> metavar "FQN" <> help "Location of object to include to result and intermediate expressions after rewriting. \ \Must be a valid dispatch expression; e.g. Q.org.eolang. Unlike --hide, can be used only once" ) )optLocator :: Parser StringoptLocator = strOption (long "locator" <> metavar "FQN" <> help "Location of object to rewrite, dataize or morph. Must be a valid dispatch expression; e.g. Q.foo.bar" <> value "Q" <> showDefault)optFocus :: Parser StringoptFocus = strOption ( long "focus" <> metavar "FQN" <> help "Location of only object to be printed in entire expression. Must be a valid dispatch expression; e.g. Q.foo.bar" <> value "Q" <> showDefault )optNormalize :: Parser BooloptNormalize = switch (long "normalize" <> help "Use built-in normalization rules")optMorph :: Parser BooloptMorph = switch (long "morph" <> help "Explain built-in morphing rules")optDataize :: Parser BooloptDataize = switch (long "dataize" <> help "Explain built-in dataization rules")optContextualize :: Parser BooloptContextualize = switch (long "contextualize" <> help "Explain built-in contextualization rules")optTarget :: Parser (Maybe FilePath)optTarget = optional (strOption (long "target" <> short 't' <> metavar "FILE" <> help "File to save output to"))optStepsDir :: Parser (Maybe FilePath)optStepsDir = optional (strOption (long "steps-dir" <> metavar "FILE" <> help "Directory to save intermediate steps during rewriting/dataizing"))optPartial :: Parser BooloptPartial = switch (long "partial" <> help "Partial evaluation: compute what the known inputs decide and, instead of failing on a Ξ» function that cannot fire (no entry of the --symbolic file answers it), leave it in place and print the residual π-program")optAcyclic :: Parser (Maybe Acyclic)optAcyclic = optional (option parseAcyclic (long "acyclic" <> metavar "MODE" <> help "Stop reducing as soon as the reduction enters a formation it is already inside (fires its Ξ» function or dataizes its Ο body again) instead of going round until --max-steps runs out, answering a copy of an object binding Ο with a fresh symbol and leaving any other term in place the way --partial leaves a Ξ» function that cannot fire; 'proven' takes it for the same one up to a renaming of symbols, 'plausible' also when it holds the earlier one under wrappers it gained, such as a growing accumulator")) where parseAcyclic :: ReadM Acyclic parseAcyclic = eitherReader $ \mode -> case filter ((== map toLower mode) . certainty) [minBound .. maxBound] of found : _ -> Right found [] -> Left (printf "The value '%s' can't be used for '--acyclic' option, use --help to check possible values" mode)optMaxLoops :: Parser IntoptMaxLoops = option (boundedIntOption >>= validateIntOption (>= 0) "--max-loops must be >= 0") (long "max-loops" <> metavar "LOOPS" <> help "Number of times the reduction may enter again a formation like one it is already inside before --acyclic cuts it, so that a recursion stopping after that many rounds is not cut" <> value 0 <> showDefault)optSymbolic :: Parser (Maybe FilePath)optSymbolic = optional ( strOption ( long "symbolic" <> metavar "FILE" <> help "Path to the YAML file of Ξ» functions this run may fire, each entry keyed by a regular expression \ \over Ξ» names under \"Ξ»\", naming the operands it brings down to data under \"dataize\", the ones \ \it reduces to a normal form under \"morph\", the ones it reduces to a normal form and takes the \ \Ο of while it is a formation binding Ο alone under \"undress\", the terms it fires through πΌ \ \under \"evaluate\", \ \the copies one of whose arguments reads to a bare symbol it answers with a fresh symbol under \ \\"defer\", the terms it keeps with every Ο applied to a dispatch dropped under \"stay\", the terms \ \it rewrites with rules spelled as in a rule file under \"rewrite\", the terms it keeps with \ \every datum they hold turned into a fresh symbol under \"symbolize\", the pair of terms whose \ \bare symbol it casts into the shape of the other under \"cast\", the Ξ» functions that only \ \raise, whose objects pass every line as they are and join as β₯, under \"terminators\", and \ \answering with the term under \"π\", or joining under \"join\" the two sides of a datum of \ \\"dataize\" into one term, with a fresh symbol where they differ" ) )optInside :: Parser (Maybe String)optInside = optional ( strOption ( long "inside" <> metavar "EXPRESSION" <> help "The π-expression to dataize or morph inside the input expression, which is taken as the universe \ \Ξ¦: a synthetic binding holding it is prepended to the universe and the locator is aimed at that \ \binding. Cannot be used together with --locator" ) )optProtocol :: Parser (Maybe FilePath)optProtocol = optional ( strOption ( long "protocol" <> metavar "FILE" <> help "File to record every Ξ» function fired during the run as XML, for a program to read: the run at \ \the top, one block per firing under it, and inside each block the operands it bound and the term \ \it answered with, with a firing nested in the reduction of an operand one level deeper again" ) )optMinutes :: Parser (Maybe FilePath)optMinutes = optional ( strOption ( long "minutes" <> metavar "FILE" <> help "File to record the same tree as --protocol does, as indented text for a person to read; \ \given together with --protocol, one run writes both files" ) )optProfile :: Parser BooloptProfile = switch ( long "profile" <> help "Close every record of the --minutes file with a comment holding the milliseconds since the record \ \above and since the start, the depth of the record, the firings so far, the live heap and the peak memory, \ \so a slow or memory-hungry spot shows next to the lines that caused it" )optAbridged :: Parser (Maybe Int)optAbridged = optional ( flag' 64 ( long "abridged" <> help "Shorten every π-expression written to the --protocol and --minutes files: a formation longer \ \than the width keeps its Ο, Ξ and Ξ» bindings and folds the rest into a count, as '+34', an \ \application longer than the width keeps its head and folds its arguments the same way, while \ \every byte string it writes stays whole; the width is 64 characters unless given as --abridged=WIDTH" ) <|> option (boundedIntOption >>= validateIntOption (> 0) "--abridged must be positive") (long "abridged" <> metavar "WIDTH" <> internal) )optAbridgedData :: Parser BooloptAbridgedData = switch ( long "abridged-data" <> help "Cut every byte string longer than eight bytes that the --abridged protocol writes to its first \ \two bytes and its last two with the count of the bytes between them, as '00-00-..(45b)..-FF-EE'" )optShuffle :: Parser BooloptShuffle = switch (long "shuffle" <> help "Shuffle rules before applying")optSeed :: Parser IntoptSeed = option boundedIntOption ( long "seed" <> metavar "SEED" <> help "Seed for the random generator that mints fresh synthetic names, making output reproducible across runs" <> value 0 <> showDefault )optSugar :: Parser SugarTypeoptSugar = flag SALTY SWEET (long "sweet" <> help (printf "Print result and intermediate (see %s option(s)) π-expressions using syntax sugar" _intermediateOptions))optCheat :: Parser BooloptCheat = switch (long "cheat" <> help "Let normalization take shortcuts its rules do not spell, such as dropping a Ο applied to a term that already ends with one; the steps then differ from what the rules prescribe")optHideRho :: Parser BooloptHideRho = switch (long "hide-rho" <> help "Remove every Ο binding from result and intermediate π-expressions for cleaner output")optSugar' :: Parser SugarTypeoptSugar' = flag SALTY SWEET (long "sweet" <> help "Print result π-expression using syntax sugar")optLineFormat :: Parser LineFormatoptLineFormat = flag MULTILINE SINGLELINE (long "flat" <> help (printf "Print result and intermediate (see %s option(s)) π-expressions in one line" _intermediateOptions))optLineFormat' :: Parser LineFormatoptLineFormat' = flag MULTILINE SINGLELINE (long "flat" <> help "Print result π-expression in one line")optMust :: Parser MustoptMust = option auto ( long "must" <> metavar "RANGE" <> help "Must-rewrite range (e.g., '3', '..5', '3..', '3..5'). Stops execution if number of rewriting cycles is not in range. Use 0 to disable." <> value MtDisabled <> showDefaultWith show )optOmitListing :: Parser BooloptOmitListing = switch (long "omit-listing" <> help "Omit full expression listing in XMIR output")optOmitComments :: Parser BooloptOmitComments = switch (long "omit-comments" <> help "Omit comments in XMIR output")optCompress :: Parser BooloptCompress = switch (long "compress" <> help "Compress expressions in LaTeX output using \\phinoMeet{} and \\phinoAgain{} functions")_intermediateOptions :: String_intermediateOptions = intercalate ", " ["--sequence", "--steps-dir"]explainParser :: Parser CommandexplainParser = CmdExplain <$> ( OptsExplain <$> optLogLevel <*> optLogLines <*> optRule <*> optNormalize <*> optMorph <*> optDataize <*> optContextualize <*> optShuffle <*> optSeed <*> optTarget )dataizeParser :: Parser CommanddataizeParser = CmdDataize <$> ( OptsDataize <$> optLogLevel <*> optLogLines <*> optInputFormat <*> optMonoform <*> optOutputFormat <*> optSugar <*> optHideRho <*> optLineFormat <*> optOmitListing <*> optOmitComments <*> optNonumber <*> optSequence <*> optHeaders <*> optCanonize <*> optDepthSensitive <*> optCheat <*> optShuffle <*> optSeed <*> switch (long "quiet" <> help "Don't print the result of dataization") <*> optPartial <*> optAcyclic <*> optMaxLoops <*> optCompress <*> optMaxDepth <*> optMaxCycles <*> optMaxSteps <*> optMaxFirings <*> optMaxSeconds <*> optMaxNodes <*> optMaxMemory <*> optMargin <*> optMeetPopularity <*> optMeetLength <*> optHide <*> optShow <*> optLocator <*> optFocus <*> optExpression <*> optLabel <*> optMeetPrefix <*> optInside <*> optStepsDir <*> optProtocol <*> optMinutes <*> optProfile <*> optAbridged <*> optAbridgedData <*> optSymbolic <*> argInputFile )morphParser :: Parser CommandmorphParser = CmdMorph <$> ( OptsMorph <$> optLogLevel <*> optLogLines <*> optInputFormat <*> optMonoform <*> optOutputFormat <*> optSugar <*> optHideRho <*> optLineFormat <*> optOmitListing <*> optOmitComments <*> optNonumber <*> optSequence <*> optHeaders <*> optCanonize <*> optDepthSensitive <*> optCheat <*> optShuffle <*> optSeed <*> switch (long "quiet" <> help "Don't print the result of morphing") <*> optPartial <*> optAcyclic <*> optMaxLoops <*> optCompress <*> optMaxDepth <*> optMaxCycles <*> optMaxSteps <*> optMaxFirings <*> optMaxSeconds <*> optMaxNodes <*> optMaxMemory <*> optMargin <*> optMeetPopularity <*> optMeetLength <*> optHide <*> optShow <*> optLocator <*> optFocus <*> optExpression <*> optLabel <*> optMeetPrefix <*> optInside <*> optStepsDir <*> optProtocol <*> optMinutes <*> optProfile <*> optAbridged <*> optAbridgedData <*> optSymbolic <*> argInputFile )rewriteParser :: Parser CommandrewriteParser = CmdRewrite <$> ( OptsRewrite <$> optLogLevel <*> optLogLines <*> optInputFormat <*> optMonoform <*> optOutputFormat <*> optSugar <*> optHideRho <*> optLineFormat <*> optMust <*> optNormalize <*> optShuffle <*> optSeed <*> optOmitListing <*> optOmitComments <*> optDepthSensitive <*> optCheat <*> switch (long "preserve-order" <> help "Match the bindings of every formation of a --rule pattern by their position, allowing two binding metas in one formation, as hone-maven-plugin needs") <*> optNonumber <*> switch (long "in-place" <> help "Edit file in-place instead of printing to output") <*> switch (long "update" <> help "Skip rewriting if --target file is newer than the input file") <*> optSequence <*> optHeaders <*> optCanonize <*> optCompress <*> optMaxDepth <*> optMaxCycles <*> optMargin <*> optMeetPopularity <*> optMeetLength <*> optRule <*> optHide <*> optShow <*> optLocator <*> optFocus <*> optExpression <*> optLabel <*> optMeetPrefix <*> optBreakpoint <*> optTarget <*> optStepsDir <*> argInputFile )mergeParser :: Parser CommandmergeParser = CmdMerge <$> ( OptsMerge <$> optLogLevel <*> optLogLines <*> optInputFormat <*> optMonoform <*> option (parseIOFormat "output") (long "output" <> metavar "FORMAT" <> help (printf "Result expression output format (phi, xmir, latex)") <> value PHI <> showDefault) <*> optSugar' <*> optLineFormat' <*> optOmitListing <*> optOmitComments <*> optMargin <*> optTarget <*> many (argument str (metavar "[FILE]" <> help "Paths to input files")) <*> optSeed )matchParser :: Parser CommandmatchParser = CmdMatch <$> ( OptsMatch <$> optLogLevel <*> optLogLines <*> optMonoform <*> optSugar' <*> optLineFormat' <*> optional (strOption (long "pattern" <> metavar "EXPRESSION" <> help "Pattern expression to match against")) <*> optional (strOption (long "when" <> metavar "CONDITION" <> help "Predicate for matched substitutions")) <*> argInputFile <*> optSeed )sodgParser :: Parser CommandsodgParser = CmdSodg <$> ( OptsSodg <$> optLogLevel <*> optLogLines <*> optInputFormat <*> switch (long "drop-tests" <> help "Drop the unit tests of every object, the attributes named pπ΅β¦, nπ΅β¦, +β¦ or -β¦, with all they hold") <*> argInputFile )compileParser :: Parser CommandcompileParser = CmdCompile <$> ( OptsCompile <$> optLogLevel <*> optLogLines <*> optRule <*> strOption (long "target" <> short 't' <> metavar "FILE" <> value "compiled/generated/Compiled.hs" <> showDefault <> help "File to write the Haskell module to") )commandParser :: Parser CommandcommandParser = hsubparser ( command "rewrite" (info rewriteParser (progDesc "Rewrite the π-expression")) <> command "dataize" (info dataizeParser (progDesc "Dataize the π-expression")) <> command "morph" (info morphParser (progDesc "Morph the π-expression")) <> command "explain" (info explainParser (progDesc "Explain rules in LaTeX format")) <> command "merge" (info mergeParser (progDesc "Merge π-expressions into single one by merging their top level formations")) <> command "match" (info matchParser (progDesc "Match π-expression against provided pattern and build matched substitutions")) <> command "sodg" (info sodgParser (progDesc "Print the SODG commands that build the graph of the π-expression")) <> command "compile" (info compileParser (progDesc "Compile the rules into a Haskell module a build with the flag 'compiled' links in")) )optPin :: Parser (Maybe Pin)optPin = optional (PinVersion <$> literal <|> PinFile <$> file) where literal :: Parser String literal = strOption ( long "pin" <> metavar "VERSION" <> help "Fail if this version doesn't match the version of phino" ) file :: Parser FilePath file = strOption ( long "pin-file" <> metavar "FILE" <> help "Fail if the version written in this file doesn't match the version of phino" )cliArgsParser :: Parser CliArgscliArgsParser = CliArgs <$> optPin <*> commandParserparserInfo :: ParserInfo CliArgsparserInfo = info (cliArgsParser <**> helper <**> simpleVersioner (showVersion version)) (fullDesc <> header "Phino - CLI Manipulator of π-Calculus Expressions")