packages feed

phino-0.0.132 / src / CLI / Parsers.hs

-- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com-- SPDX-License-Identifier: MITmodule CLI.Parsers whereimport Atoms (runtimeNames)import CLI.Typesimport Data.Char (toLower, toUpper)import Data.List (intercalate)import Data.Version (showVersion)import LaTeX (defaultMeetLength, defaultMeetPopularity)import Lining (LineFormat (..))import Loggerimport Margin (defaultMargin)import Mustimport Options.Applicativeimport Paths_phino (version)import Sugar (SugarType (..))import Text.Printf (printf)validateIntOption :: (Int -> Bool) -> String -> Int -> ReadM IntvalidateIntOption cmp msg num  | cmp num = return num  | otherwise = readerError msgoptLogLevel :: Parser LogLeveloptLogLevel =  option    parseLogLevel    ( long "log-level"        <> metavar "LEVEL"        <> help ("Log level (" <> intercalate ", " (map show [DEBUG, ERROR, NONE]) <> ")")        <> value ERROR        <> showDefault    )  where    parseLogLevel :: ReadM LogLevel    parseLogLevel = eitherReader $ \lvl -> case map toUpper lvl of      "DEBUG" -> Right DEBUG      "ERROR" -> Right ERROR      "ERR" -> Right ERROR      "NONE" -> Right NONE      _ -> Left $ "unknown log-level: " <> lvloptLogLines :: Parser IntoptLogLines =  option    (auto >>= 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')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    (auto >>= 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    (auto >>= 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    (auto >>= validateIntOption (> 0) "--max-steps must be positive")    (long "max-steps" <> metavar "STEPS" <> help "Maximum number of nested morphing and dataization steps" <> value 1000 <> showDefault)optMargin :: Parser IntoptMargin =  option    (auto >>= 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        ( auto            >>= 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        (auto >>= 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 an atom that cannot fire (its Ξ» function is not in the --atoms registry), leave it in place and print the residual πœ‘-program")-- 𝕄 stops at the first formation it reaches and hands its bindings back as-- they were written, so what a program holds but nothing demands is never-- reduced. This walks into them (see 'deepened').optDeep :: Parser BooloptDeep = switch (long "deep" <> help "Don't stop at the first formation: enter its bindings too, recursively, firing every Ξ» function the --atoms registry serves and standing its answer in the place of what it computed, while everything else stays as it was written")-- Which Ξ» functions this run may fire. phino implements none of them itself-- (see 'Atoms'), so without this option every atom a program names gets stuck.optAtoms :: Parser (Maybe FilePath)optAtoms =  optional    ( strOption        ( long "atoms"            <> metavar "FILE"            <> help              ( printf                  "Path to the JSON registry of Ξ» functions this run may fire, whose keys are regular expressions over Ξ» names, tried top to bottom, each mapped to the runtime that runs it (%s), the script or the executable it runs and, with \"serve\", whether one process of it is to serve the whole run"                  (intercalate ", " runtimeNames)              )        )    )-- The external face of the trick phino plays internally to reduce a-- sub-expression against a universe: prepend a synthetic binding holding it to-- that universe and aim the locator at the binding. An atom script started for-- the fire needs it to reduce the parts of the formation it was given, so it-- does not have to splice them into the text of the universe by hand; one kept-- for the run asks phino over the channel it answers on instead (see 'Atoms').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"        )    )optEvaluations :: Parser (Maybe FilePath)optEvaluations = optional (strOption (long "evaluations" <> metavar "FILE" <> help "File to record every atom fired during dataizing, as one tab-separated line per firing: the Ξ» function name, its argument formation and its result (requires --output=phi)"))optShuffle :: Parser BooloptShuffle = switch (long "shuffle" <> help "Shuffle rules before applying")optSeed :: Parser IntoptSeed =  option    auto    ( 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))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 rules applied 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            <*> optOutputFormat            <*> optSugar            <*> optHideRho            <*> optLineFormat            <*> optOmitListing            <*> optOmitComments            <*> optNonumber            <*> optSequence            <*> optHeaders            <*> optCanonize            <*> optDepthSensitive            <*> optShuffle            <*> optSeed            <*> switch (long "quiet" <> help "Don't print the result of dataization")            <*> optPartial            <*> optCompress            <*> optMaxDepth            <*> optMaxCycles            <*> optMaxSteps            <*> optMargin            <*> optMeetPopularity            <*> optMeetLength            <*> optHide            <*> optShow            <*> optLocator            <*> optFocus            <*> optExpression            <*> optLabel            <*> optMeetPrefix            <*> optInside            <*> optStepsDir            <*> optEvaluations            <*> optAtoms            <*> argInputFile        )morphParser :: Parser CommandmorphParser =  CmdMorph    <$> ( OptsMorph            <$> optLogLevel            <*> optLogLines            <*> optInputFormat            <*> optOutputFormat            <*> optSugar            <*> optHideRho            <*> optLineFormat            <*> optOmitListing            <*> optOmitComments            <*> optNonumber            <*> optSequence            <*> optHeaders            <*> optCanonize            <*> optDepthSensitive            <*> optShuffle            <*> optSeed            <*> switch (long "quiet" <> help "Don't print the result of morphing")            <*> optPartial            <*> optDeep            <*> optCompress            <*> optMaxDepth            <*> optMaxCycles            <*> optMaxSteps            <*> optMargin            <*> optMeetPopularity            <*> optMeetLength            <*> optHide            <*> optShow            <*> optLocator            <*> optFocus            <*> optExpression            <*> optLabel            <*> optMeetPrefix            <*> optInside            <*> optStepsDir            <*> optEvaluations            <*> optAtoms            <*> argInputFile        )rewriteParser :: Parser CommandrewriteParser =  CmdRewrite    <$> ( OptsRewrite            <$> optLogLevel            <*> optLogLines            <*> optInputFormat            <*> optOutputFormat            <*> optSugar            <*> optHideRho            <*> optLineFormat            <*> optMust            <*> optNormalize            <*> optShuffle            <*> optSeed            <*> optOmitListing            <*> optOmitComments            <*> optDepthSensitive            <*> 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            <*> 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            <*> 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        )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"))    )optPin :: Parser (Maybe String)optPin =  optional    ( strOption        ( long "pin"            <> metavar "VERSION"            <> help "Fail if this version 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")