-- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com-- SPDX-License-Identifier: MIT{-# LANGUAGE OverloadedRecordDot #-}{-# LANGUAGE RecordWildCards #-}{-# LANGUAGE ScopedTypeVariables #-}module CLI.Helpers whereimport ASTimport CLI.Typesimport CLI.Validators (invalidCLIArguments)import Canonizer (canonize)import Control.Exceptionimport Control.Monad ((>=>))import Data.Functor ((<&>))import Data.List (intercalate)import Data.Maybeimport Deps (SaveStepFunc, saveStep)import Encodingimport Files (ensuredFile)import Functions (execFunctions)import LaTeX (LatexContext (..), defaultMeetLength, defaultMeetPopularity, expressionToLaTeX, rewrittensToLatex)import Locator (locatedExpression)import Loggerimport Parser (parseExpressionThrows)import qualified Printer as Pimport qualified Random as Rimport Rewriter (Rewritten, Rewrittens', stepHeaders)import System.IO (getContents')import Text.Printf (printf)import XMIR (expressionToXMIR, parseXMIRThrows, printXMIR, xmirToPhi)import Yaml (normalizationRules)import qualified Yaml as YjustMeetPopularity :: Maybe Int -> IntjustMeetPopularity = fromMaybe defaultMeetPopularityjustMeetLength :: Maybe Int -> IntjustMeetLength = fromMaybe defaultMeetLength-- Prepare saveStepFuncsaveStepFunc :: Maybe FilePath -> PrintContext -> SaveStepFuncsaveStepFunc stepsDir ctx@PrintCtx{..} = saveStep stepsDir ioToExt (printInFormat ctx) where ioToExt :: String ioToExt | _outputFormat == LATEX = "tex" | otherwise = show _outputFormat-- Read input from file or stdinreadInput :: Maybe FilePath -> IO StringreadInput inputFile' = case inputFile' of Just pth -> do logDebug (printf "Reading from file: '%s'" pth) readFile =<< ensuredFile pth Nothing -> do logDebug "Reading from stdin" getContents' `catch` (\(e :: SomeException) -> throwIO (CouldNotReadFromStdin (show e)))-- Parse expression from String input depending on input IO formatparseInput :: String -> IOFormat -> IO ExpressionparseInput phi PHI = parseExpressionThrows phiparseInput xmir XMIR = parseXMIRThrows xmir >>= xmirToPhiparseInput _ LATEX = invalidCLIArguments "LaTeX cannot be used as input format"-- The LaTeX sequence path canonizes inside 'rewrittensToLatex', after the meet-- compression (see 'canonizedRewrittens' there); the remaining formats have no-- meet pass, so canonization happens here right before rendering.printRewrittens :: PrintContext -> Rewrittens' -> IO StringprintRewrittens ctx@PrintCtx{..} rewrittens@(chain, _) | _outputFormat == LATEX && _sequence = rewrittensToLatex rewrittens (printCtxToLatexCtx ctx) | otherwise = withHeaders <$> mapM render (canonized chain) where render :: Rewritten -> IO String render (expr, _) | _focus == ExRoot = printInFormat ctx expr | otherwise = locatedExpression _focus expr >>= printExpression ctx canonized :: [Rewritten] -> [Rewritten] canonized = if _canonize then canonize else id -- Prefix every step with an empty line and its header (see 'stepHeaders') -- when '--headers' is on. Headers, like the other intermediate-output -- flags, are meaningful only together with '--sequence'. Node counts come -- from the original 'chain', not the canonized one, since canonization -- only renames functions and never changes the AST size. withHeaders :: [String] -> String withHeaders rendered | _headers && _sequence = intercalate "\n" (zipWith prefixed (stepHeaders chain) rendered) | otherwise = intercalate "\n" rendered where prefixed :: String -> String -> String prefixed = printf "\n%s\n%s"printExpression :: PrintContext -> Expression -> IO StringprintExpression ctx@PrintCtx{..} ex = case _outputFormat of PHI -> pure (printPhi ctx ex) XMIR -> throwIO CouldNotPrintExpressionInXMIR LATEX -> pure (expressionToLaTeX ex (printCtxToLatexCtx ctx))-- Convert an expression to its corresponding String formatprintInFormat :: PrintContext -> Expression -> IO StringprintInFormat ctx@PrintCtx{..} expr = case _outputFormat of PHI -> pure (printPhi ctx expr) XMIR -> expressionToXMIR expr _xmirCtx <&> printXMIR LATEX -> pure (expressionToLaTeX expr (printCtxToLatexCtx ctx))-- Render an expression as PHI, dropping every ρ binding when '--hide-rho' is set.printPhi :: PrintContext -> Expression -> StringprintPhi PrintCtx{..} expr = (if _hideRho then P.printExpressionHidingRho' else P.printExpression') expr (_sugar, UNICODE, _line, _margin)printCtxToLatexCtx :: PrintContext -> LatexContextprintCtxToLatexCtx PrintCtx{..} = LatexContext _sugar _line _margin _nonumber _compress _canonize _meetPopularity _meetLength _focus _expression _label _meetPrefix _headers-- Get rules for rewriting depending on provided flagsgetRules :: Bool -> Bool -> [FilePath] -> IO [Y.Rule]getRules normalize shuffle rules = do ordered <- if normalize then do let rules' = normalizationRules logDebug (printf "The --normalize option is provided, %d built-it normalization rules are used" (length rules')) pure rules' else if null rules then do logDebug "No --rule and no --normalize options are provided, no rules are used" pure [] else do logDebug (printf "Using rules from files: [%s]" (intercalate ", " rules)) yamls <- mapM ensuredFile rules mapM (Y.yamlRule >=> validateRewriteRule) yamls if shuffle then do logDebug "The --shuffle option is provided, rules are used in random order" R.shuffle ordered else pure ordered-- Pass a user-supplied rewriting rule through unchanged, or fail fast if it-- references a build-term function which needs the dataization context: those-- work only for dataization and morphing, never for plain rewriting.validateRewriteRule :: Y.Rule -> IO Y.RulevalidateRewriteRule rule = let used = maybe [] (map Y.function) rule.where_ in case filter (`elem` execFunctions) used of [] -> pure rule (fn : _) -> invalidCLIArguments (printf "Function '%s' in rule '%s' is available only for dataization and morphing, not for rewriting" fn rule.name)-- Output contentprintOut :: Maybe FilePath -> String -> IO ()printOut target content = case target of Nothing -> do logDebug "The option '--target' is not specified, printing to console..." putStrLn content Just file -> do logDebug (printf "The option '--target' is specified, printing to '%s'..." file) writeFile file content logDebug (printf "The command result was saved in '%s'" file)