canontra-0.4.0.0: src/Canontra/Normalize/Normalize.hs
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{- |
Module : Canontra.Normalize.Normalize
Description : Polyglot AST normalization pass v4.
Normalizer v4 strips away multi-scope docstrings, comments, redundant passes,
and formatting trivia across Python, JavaScript, TypeScript, Go, and Rust
while strictly preserving semantic literals, arithmetic operator semantics,
and execution control flow. Provides 'CanonicalProgram' for single-pass
pipeline fusion across all fingerprint tiers.
-}
module Canontra.Normalize.Normalize
( CanonicalProgram (..)
, toCanonicalProgram
, normalizeProgram
, normalizeModule
, normalizeDeclaration
, normalizeModuleDeclarations
, isProvablyPureDeclaration
, declIdentifier
, normalizeFunction
, normalizeStmt
, normalizeExpr
, isReflectionDocstring
, preservesDocstrings
, cleanStmtSuite
, cleanStmtSuiteWithPreserve
, stripLeadingDocstring
) where
import Control.DeepSeq (NFData)
import Data.List (partition, sort, sortBy)
import Data.Ord (comparing)
import Data.Text (Text)
import qualified Data.Text as T
import Canontra.Analysis.CFGCanonical (normalizeBranchModule)
import Canontra.IR.Declaration
import Canontra.IR.Dependency
import Canontra.IR.Expression
import Canontra.IR.Program
import Canontra.Normalize.Algebraic (normalizeAlgebraicExpr, normalizeAlgebraicModule)
import Canontra.Normalize.Alpha (canonicalizeAlphaModuleForLang)
-- | Witness wrapper indicating a 'Program' has already completed full
-- canonical normalization (trivia stripping, declaration ordering, branch
-- normalization, alpha-renaming, and algebraic normal form).
newtype CanonicalProgram = CanonicalProgram
{ unCanonicalProgram :: Program
} deriving stock (Eq, Show)
deriving newtype (NFData)
-- | Normalize a raw 'Program' exactly once into a 'CanonicalProgram'.
toCanonicalProgram :: Program -> CanonicalProgram
toCanonicalProgram = CanonicalProgram . normalizeProgram
normalizeProgram :: Program -> Program
normalizeProgram (Program modules lang) =
let normModules = map (normalizeModuleForLang lang) modules
in Program (sortBy (comparing modName) normModules) lang
normalizeModule :: Module -> Module
normalizeModule = normalizeModuleForLang ""
normalizeModuleForLang :: Text -> Module -> Module
normalizeModuleForLang lang (Module _ imps decls stmts) =
let normImps = sort (map normalizeImport imps)
normDecls = normalizeModuleDeclarationsCore decls
strippedStmts = stripLeadingDocstring stmts
normStmts = cleanStmtSuite (map normalizeStmtCore strippedStmts)
in normalizeAlgebraicModule
. canonicalizeAlphaModuleForLang lang
. normalizeBranchModule
$ Module "" normImps normDecls normStmts
-- | Check if a declaration is provably pure and free of module-level side effects.
isProvablyPureDeclaration :: Declaration -> Bool
isProvablyPureDeclaration = \case
DeclFunction fn -> null (fnDecorators fn) -- Simple functions without decorators are pure
DeclInterface _ -> True
DeclTypeAlias _ _ -> True
DeclTrait _ -> True
_ -> False
-- | Unique canonical sorting key for declarations.
declIdentifier :: Declaration -> Text
declIdentifier = \case
DeclFunction fn -> "fn:" <> fnName fn
DeclClass cls -> "cls:" <> clsName cls
DeclStruct st -> "st:" <> stName st
DeclVariable v _ -> "var:" <> v
DeclInterface iface -> "if:" <> ifName iface
DeclTrait tr -> "tr:" <> trName tr
DeclImpl imp -> "imp:" <> impTarget imp
DeclReceiver rc fn -> "rc:" <> rcTypeName rc <> "." <> fnName fn
DeclTypeAlias alias _ -> "alias:" <> alias
-- | Normalize module declarations: pure declarations are canonically sorted;
-- stateful or decorated declarations preserve source execution order.
normalizeModuleDeclarations :: [Declaration] -> [Declaration]
normalizeModuleDeclarations = normalizeModuleDeclarationsWith normalizeDeclaration
normalizeModuleDeclarationsCore :: [Declaration] -> [Declaration]
normalizeModuleDeclarationsCore = normalizeModuleDeclarationsWith normalizeDeclarationCore
normalizeModuleDeclarationsWith :: (Declaration -> Declaration) -> [Declaration] -> [Declaration]
normalizeModuleDeclarationsWith normDecl decls =
let (pureDecls, statefulDecls) = partition isProvablyPureDeclaration decls
sortedPure = sortBy (comparing declIdentifier) (map normDecl pureDecls)
normStateful = map normDecl statefulDecls
in sortedPure ++ normStateful
normalizeImport :: ImportDecl -> ImportDecl
normalizeImport imp = case imp of
ImportModule modName alias -> ImportModule modName alias
ImportFrom modName (ImportSymbols syms) -> ImportFrom modName (ImportSymbols (sort syms))
ImportFrom modName ImportAll -> ImportFrom modName ImportAll
normalizeDeclaration :: Declaration -> Declaration
normalizeDeclaration = normalizeDeclarationWith normalizeStmt
normalizeDeclarationCore :: Declaration -> Declaration
normalizeDeclarationCore = normalizeDeclarationWith normalizeStmtCore
normalizeDeclarationWith :: (Stmt -> Stmt) -> Declaration -> Declaration
normalizeDeclarationWith normSt decl =
let normFn = normalizeClassFunctionWith normSt False
in case decl of
DeclFunction fn -> DeclFunction (normFn fn)
DeclClass (Class name bases methods decs) ->
let classPreserve = preservesDocstrings decs
normMethods = map (normalizeClassFunctionWith normSt classPreserve) methods
in DeclClass (Class name bases normMethods (sort decs))
DeclStruct (Struct name fields methods vis) ->
let normFields = map (\(f, t) -> (f, fmap T.strip t)) fields
normMethods = map normFn methods
in DeclStruct (Struct name normFields normMethods vis)
DeclInterface (Interface name methods bases) ->
let normMethods = map normFn methods
in DeclInterface (Interface name normMethods (sort bases))
DeclReceiver rc fn ->
DeclReceiver rc (normFn fn)
DeclTrait (Trait name methods supers) ->
let normMethods = map normFn methods
in DeclTrait (Trait name normMethods (sort supers))
DeclImpl (Impl mTr tgt methods) ->
let normMethods = map normFn methods
in DeclImpl (Impl mTr tgt normMethods)
DeclVariable v mTy -> DeclVariable v (fmap T.strip mTy)
DeclTypeAlias a mTy -> DeclTypeAlias a (fmap T.strip mTy)
-- | Check if a docstring is marked for runtime reflection preservation
isReflectionDocstring :: Text -> Bool
isReflectionDocstring doc =
let stripped = T.strip doc
in T.isInfixOf ":preserve:" stripped
|| T.isInfixOf "@preserve" stripped
|| T.isPrefixOf ":doc:" stripped
|| T.isInfixOf ":doc:" stripped
-- | Check if a declaration is marked for runtime reflection docstring preservation
preservesDocstrings :: [Text] -> Bool
preservesDocstrings decs =
any (\d -> d `elem` ["@preserve_docstring", "@reflect", "@doc", "preserve_docstring", "reflect", "doc"]) decs
normalizeFunction :: Function -> Function
normalizeFunction = normalizeClassFunctionWith normalizeStmt False
normalizeClassFunctionWith :: (Stmt -> Stmt) -> Bool -> Function -> Function
normalizeClassFunctionWith normSt classPreserve (Function name params retType decs body isAsync) =
let normParams = map normalizeParam params
normRetType = fmap T.strip retType
normDecs = sort decs
preserve = classPreserve || preservesDocstrings decs
strippedBody = if preserve then body else stripLeadingDocstring body
normBody = cleanStmtSuiteWithPreserve preserve (map normSt strippedBody)
in Function name normParams normRetType normDecs normBody isAsync
normalizeParam :: Parameter -> Parameter
normalizeParam (Parameter name kind defVal mType) =
Parameter name kind (fmap T.strip defVal) (fmap T.strip mType)
normalizeStmt :: Stmt -> Stmt
normalizeStmt = normalizeStmtWith normalizeExpr
normalizeStmtCore :: Stmt -> Stmt
normalizeStmtCore = normalizeStmtWith normalizeExprCore
normalizeStmtWith :: (Expr -> Expr) -> Stmt -> Stmt
normalizeStmtWith normE stmt = case stmt of
StmtAssign targets expr ->
StmtAssign (map normE targets) (normE expr)
StmtAnnAssign target ty maybeVal ->
StmtAnnAssign (normE target) (normE ty) (fmap normE maybeVal)
StmtAugAssign target op expr ->
StmtAugAssign (normE target) op (normE expr)
StmtExpr expr ->
StmtExpr (normE expr)
StmtReturn maybeExpr ->
StmtReturn (fmap normE maybeExpr)
StmtIf cond body elseSuite ->
StmtIf (normE cond) (cleanStmtSuite (map normSt (stripLeadingDocstring body))) (cleanStmtSuite (map normSt (stripLeadingDocstring elseSuite)))
StmtWhile cond body elseSuite ->
StmtWhile (normE cond) (cleanStmtSuite (map normSt (stripLeadingDocstring body))) (cleanStmtSuite (map normSt (stripLeadingDocstring elseSuite)))
StmtFor target iter body elseSuite ->
StmtFor (normE target) (normE iter) (cleanStmtSuite (map normSt (stripLeadingDocstring body))) (cleanStmtSuite (map normSt (stripLeadingDocstring elseSuite)))
StmtAsyncFor target iter body elseSuite ->
StmtAsyncFor (normE target) (normE iter) (cleanStmtSuite (map normSt (stripLeadingDocstring body))) (cleanStmtSuite (map normSt (stripLeadingDocstring elseSuite)))
StmtTry body handlers elseSuite finalSuite ->
let normHandlers = map (\(clause, alias, hBody) ->
(fmap normE clause, alias, cleanStmtSuite (map normSt (stripLeadingDocstring hBody)))) handlers
in StmtTry (cleanStmtSuite (map normSt (stripLeadingDocstring body))) normHandlers (cleanStmtSuite (map normSt (stripLeadingDocstring elseSuite))) (cleanStmtSuite (map normSt (stripLeadingDocstring finalSuite)))
StmtWith items body ->
StmtWith (map (\(e, a) -> (normE e, fmap normE a)) items) (cleanStmtSuite (map normSt (stripLeadingDocstring body)))
StmtAsyncWith items body ->
StmtAsyncWith (map (\(e, a) -> (normE e, fmap normE a)) items) (cleanStmtSuite (map normSt (stripLeadingDocstring body)))
StmtAssert expr maybeMsg ->
StmtAssert (normE expr) (fmap normE maybeMsg)
StmtRaise maybeExpr maybeCause ->
StmtRaise (fmap normE maybeExpr) (fmap normE maybeCause)
StmtBreak -> StmtBreak
StmtContinue -> StmtContinue
StmtPass -> StmtPass
StmtDelete exprs -> StmtDelete (map normE exprs)
StmtGlobal vars -> StmtGlobal (sort vars)
StmtNonlocal vars -> StmtNonlocal (sort vars)
StmtMatch expr cases ->
StmtMatch (normE expr) (map normMatchCase cases)
StmtGo expr ->
StmtGo (normE expr)
StmtDefer expr ->
StmtDefer (normE expr)
StmtChanSend ch val ->
StmtChanSend (normE ch) (normE val)
StmtSelect cases ->
StmtSelect (map (\(sc, b) -> (normSelectCase sc, cleanStmtSuite (map normSt (stripLeadingDocstring b)))) cases)
StmtLoop body ->
StmtLoop (cleanStmtSuite (map normSt (stripLeadingDocstring body)))
StmtSwitch expr cases defStmts ->
StmtSwitch (normE expr)
(map (\(c, b) -> (normE c, cleanStmtSuite (map normSt (stripLeadingDocstring b)))) cases)
(cleanStmtSuite (map normSt (stripLeadingDocstring defStmts)))
where
normSt = normalizeStmtWith normE
normSelectCase = \case
SelectSend ch val -> SelectSend (normE ch) (normE val)
SelectRecv mV ch -> SelectRecv mV (normE ch)
SelectDefault -> SelectDefault
normMatchCase (MatchCase pat guard body) =
MatchCase (normE pat) (fmap normE guard) (cleanStmtSuite (map normSt (stripLeadingDocstring body)))
normalizeExpr :: Expr -> Expr
normalizeExpr = normalizeAlgebraicExpr . normalizeExprCore
normalizeExprCore :: Expr -> Expr
normalizeExprCore expr = case expr of
ExprId ident -> ExprId ident
ExprLit lit -> ExprLit lit
ExprBinary op e1 e2 -> ExprBinary op (normalizeExprCore e1) (normalizeExprCore e2)
ExprUnary op e -> ExprUnary op (normalizeExprCore e)
ExprCall target args kwArgs ->
let normArgs = map normalizeExprCore args
normKwArgs = sortBy (comparing fst) (map (\(k, v) -> (k, normalizeExprCore v)) kwArgs)
in ExprCall (normalizeExprCore target) normArgs normKwArgs
ExprAttr target attr -> ExprAttr (normalizeExprCore target) attr
ExprSubscript target idx -> ExprSubscript (normalizeExprCore target) (normalizeExprCore idx)
ExprSlice ms me mst -> ExprSlice (fmap normalizeExprCore ms) (fmap normalizeExprCore me) (fmap normalizeExprCore mst)
ExprList items -> ExprList (map normalizeExprCore items)
ExprTuple items -> ExprTuple (map normalizeExprCore items)
ExprDict items -> ExprDict (map (\(k, v) -> (normalizeExprCore k, normalizeExprCore v)) items)
ExprSet items -> ExprSet (map normalizeExprCore items)
ExprLambda params body -> ExprLambda (map normalizeParam params) (normalizeExprCore body)
ExprTernary cond trueExpr falseExpr -> ExprTernary (normalizeExprCore cond) (normalizeExprCore trueExpr) (normalizeExprCore falseExpr)
ExprListComp item comps -> ExprListComp (normalizeExprCore item) (map normalizeCompCore comps)
ExprDictComp k v comps -> ExprDictComp (normalizeExprCore k) (normalizeExprCore v) (map normalizeCompCore comps)
ExprSetComp item comps -> ExprSetComp (normalizeExprCore item) (map normalizeCompCore comps)
ExprGenerator item comps -> ExprGenerator (normalizeExprCore item) (map normalizeCompCore comps)
ExprWalrus name val -> ExprWalrus name (normalizeExprCore val)
ExprAwait e -> ExprAwait (normalizeExprCore e)
ExprYield me -> ExprYield (fmap normalizeExprCore me)
ExprYieldFrom e -> ExprYieldFrom (normalizeExprCore e)
ExprFormattedString parts -> ExprFormattedString (map normalizeFStringPartCore parts)
ExprStarred e -> ExprStarred (normalizeExprCore e)
ExprKwStarred e -> ExprKwStarred (normalizeExprCore e)
ExprOptChain e prop -> ExprOptChain (normalizeExprCore e) prop
ExprNullish e1 e2 -> ExprNullish (normalizeExprCore e1) (normalizeExprCore e2)
ExprChanRecv ch -> ExprChanRecv (normalizeExprCore ch)
ExprTryOp e -> ExprTryOp (normalizeExprCore e)
ExprMacroCall name args -> ExprMacroCall name (map normalizeExprCore args)
ExprJSX tagElem attrs children ->
let normAttrs = sortBy (comparing fst) (map (\(k, v) -> (k, normalizeExprCore v)) attrs)
normChildren = map normalizeExprCore children
in ExprJSX tagElem normAttrs normChildren
normalizeFStringPartCore :: FStringPart -> FStringPart
normalizeFStringPartCore = \case
FStringText t -> FStringText t
FStringExpr e conv fmt -> FStringExpr (normalizeExprCore e) conv fmt
normalizeCompCore :: CompFor -> CompFor
normalizeCompCore (CompFor target iter ifs) =
CompFor (normalizeExprCore target) (normalizeExprCore iter) (map normalizeExprCore ifs)
-- | Strip leading string literal statement (docstring) from a statement list
stripLeadingDocstring :: [Stmt] -> [Stmt]
stripLeadingDocstring [] = []
stripLeadingDocstring (StmtExpr (ExprLit (LitString s)) : rest)
| isReflectionDocstring s = StmtExpr (ExprLit (LitString s)) : rest
| otherwise = rest
stripLeadingDocstring stmts = stmts
-- | Drops lone docstring expressions throughout block and eliminates redundant passes
cleanStmtSuite :: [Stmt] -> [Stmt]
cleanStmtSuite = cleanStmtSuiteWithPreserve False
cleanStmtSuiteWithPreserve :: Bool -> [Stmt] -> [Stmt]
cleanStmtSuiteWithPreserve preserve rawStmts =
let nonDoc = if preserve then rawStmts else filter (not . isDocstringStmt) rawStmts
elimPass = if length nonDoc > 1 then filter (not . isPass) nonDoc else nonDoc
in if null elimPass then [StmtPass] else elimPass
where
isDocstringStmt (StmtExpr (ExprLit (LitString s))) = not (isReflectionDocstring s)
isDocstringStmt _ = False
isPass StmtPass = True
isPass _ = False