packages feed

canontra-0.4.0.0: src/Canontra/Normalize/Algebraic.hs

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}

{- |
Module      : Canontra.Normalize.Algebraic
Description : Pure commutative, associative, and relational algebraic canonicalizer.

Canonicalizes provably pure, side-effect-free expressions:
  - Commutative & associative binary operators (+, *, &, |, ^, ==, !=)
  - Relational dual operators (b > a -> a < b, b >= a -> a <= b)
  - Unordered collection literals (ExprSet and pure ExprDict)
-}
module Canontra.Normalize.Algebraic
  ( normalizeAlgebraicProgram
  , normalizeAlgebraicModule
  , normalizeAlgebraicDecl
  , normalizeAlgebraicStmt
  , normalizeAlgebraicExpr
  , normalizeBinaryExpr
  , normalizeCollectionLiteral
  , isProvablyPureExpr
  , isNonTrappingPureExpr
  , containsFloatOperand
  , isCommutativeOp
  , hashExprB
  ) where

import Data.Bits (xor)
import qualified Data.ByteString as BS
import Data.List (sortBy)
import Data.Ord (comparing)
import Data.Word (Word64)

import Canontra.Canonical.Serialize (canonicalizeExpr)
import Canontra.IR.Declaration
  ( Class (..)
  , Declaration (..)
  , Function (..)
  , Impl (..)
  , Struct (..)
  , Trait (..)
  )
import Canontra.IR.Expression
  ( CompFor (..)
  , Expr (..)
  , FStringPart (..)
  , Lit (..)
  , MatchCase (..)
  , Op (..)
  , SelectCase (..)
  , Stmt (..)
  )
import Canontra.IR.Program
  ( Module (..)
  , Program (..)
  )

-- | Compute a deterministic 64-bit FNV-1a hash of an 'Expr' for canonical ordering.
hashExprB :: Expr -> Word64
hashExprB = fst . exprCanonicalKey

-- | Compute both the 64-bit FNV-1a hash and exact canonical ByteString once
-- for Schwartzian sorting with collision-proof deterministic tie-breaking.
{-# INLINE exprCanonicalKey #-}
exprCanonicalKey :: Expr -> (Word64, BS.ByteString)
exprCanonicalKey e =
  let !bs = canonicalizeExpr e
      !h = fnv1aHash64 bs
  in (h, bs)

{-# INLINE fnv1aHash64 #-}
fnv1aHash64 :: BS.ByteString -> Word64
fnv1aHash64 =
  BS.foldl'
    (\ !h !b -> (h `xor` fromIntegral b) * 1099511628211)
    14695981039346656037

-- | Check whether an expression is provably pure (free of function calls,
-- method invocations, walrus assignments, await, yield, or macro invocations).
isProvablyPureExpr :: Expr -> Bool
isProvablyPureExpr = \case
  ExprLit _             -> True
  ExprId _              -> True
  ExprBinary _ e1 e2    -> isProvablyPureExpr e1 && isProvablyPureExpr e2
  ExprUnary _ e         -> isProvablyPureExpr e
  ExprTuple es          -> all isProvablyPureExpr es
  ExprList es           -> all isProvablyPureExpr es
  ExprSet es            -> all isProvablyPureExpr es
  ExprDict pairs        -> all (\(k, v) -> isProvablyPureExpr k && isProvablyPureExpr v) pairs
  ExprAttr e _          -> isProvablyPureExpr e
  ExprOptChain e _      -> isProvablyPureExpr e
  ExprNullish e1 e2     -> isProvablyPureExpr e1 && isProvablyPureExpr e2
  ExprSubscript e1 e2   -> isProvablyPureExpr e1 && isProvablyPureExpr e2
  ExprTernary c t f     -> isProvablyPureExpr c && isProvablyPureExpr t && isProvablyPureExpr f
  _                     -> False

-- | Check whether an expression is provably pure AND cannot trap on division/modulo/attr/subscript.
-- Used to guard short-circuit boolean commutativity and De Morgan canonicalization.
isNonTrappingPureExpr :: Expr -> Bool
isNonTrappingPureExpr = \case
  ExprLit _             -> True
  ExprId _              -> True
  ExprUnary _ e         -> isNonTrappingPureExpr e
  ExprBinary op e1 e2   ->
    not (op `elem` [OpDiv, OpFloorDiv, OpMod, OpPow])
      && isNonTrappingPureExpr e1
      && isNonTrappingPureExpr e2
  _                     -> False

-- | Check whether an expression contains any IEEE-754 floating-point literal,
-- preventing associative re-association while still permitting 2-operand commutativity.
containsFloatOperand :: Expr -> Bool
containsFloatOperand = \case
  ExprLit (LitFloat _)  -> True
  ExprUnary _ e         -> containsFloatOperand e
  ExprBinary _ e1 e2    -> containsFloatOperand e1 || containsFloatOperand e2
  ExprTernary c t f     -> containsFloatOperand c || containsFloatOperand t || containsFloatOperand f
  ExprTuple es          -> any containsFloatOperand es
  ExprList es           -> any containsFloatOperand es
  _                     -> False

-- | Check whether an expression is a string, bytes, or sequence literal for
-- which '+' represents non-commutative concatenation rather than addition.
isConcatenationOperand :: Expr -> Bool
isConcatenationOperand = \case
  ExprLit (LitString _)   -> True
  ExprLit (LitBytes _)    -> True
  ExprFormattedString _   -> True
  ExprList _              -> True
  ExprTuple _             -> True
  ExprBinary OpAdd a b    -> isConcatenationOperand a || isConcatenationOperand b
  _                       -> False

-- | True for commutative binary operators.
isCommutativeOp :: Op -> Bool
isCommutativeOp = \case
  OpAdd    -> True
  OpMul    -> True
  OpBitAnd -> True
  OpBitOr  -> True
  OpBitXor -> True
  OpEq     -> True
  OpNotEq  -> True
  _        -> False

-- | True for operators that are both associative and commutative on pure expressions.
isAssociativeCommutativeOp :: Op -> Bool
isAssociativeCommutativeOp = \case
  OpAdd    -> True
  OpMul    -> True
  OpBitAnd -> True
  OpBitOr  -> True
  OpBitXor -> True
  _        -> False

-- | Apply algebraic normalization across an entire 'Program'.
normalizeAlgebraicProgram :: Program -> Program
normalizeAlgebraicProgram (Program modules lang) =
  Program (map normalizeAlgebraicModule modules) lang

-- | Apply algebraic normalization across a 'Module'.
normalizeAlgebraicModule :: Module -> Module
normalizeAlgebraicModule (Module name imps decls stmts) =
  Module
    name
    imps
    (map normalizeAlgebraicDecl decls)
    (map normalizeAlgebraicStmt stmts)

-- | Apply algebraic normalization to a 'Declaration'.
normalizeAlgebraicDecl :: Declaration -> Declaration
normalizeAlgebraicDecl = \case
  DeclFunction fn ->
    DeclFunction (normalizeFunction fn)
  DeclClass cls ->
    DeclClass cls { clsMethods = map normalizeFunction (clsMethods cls) }
  DeclStruct st ->
    DeclStruct st { stMethods = map normalizeFunction (stMethods st) }
  DeclTrait tr ->
    DeclTrait tr { trMethods = map normalizeFunction (trMethods tr) }
  DeclImpl imp ->
    DeclImpl imp { impMethods = map normalizeFunction (impMethods imp) }
  DeclReceiver rc fn ->
    DeclReceiver rc (normalizeFunction fn)
  other -> other
  where
    normalizeFunction fn =
      fn { fnBody = map normalizeAlgebraicStmt (fnBody fn) }

-- | Apply algebraic normalization to a 'Stmt'.
normalizeAlgebraicStmt :: Stmt -> Stmt
normalizeAlgebraicStmt = \case
  StmtAssign targets val ->
    StmtAssign (map normalizeAlgebraicExpr targets) (normalizeAlgebraicExpr val)
  StmtAugAssign target op val ->
    StmtAugAssign (normalizeAlgebraicExpr target) op (normalizeAlgebraicExpr val)
  StmtAnnAssign target ann mVal ->
    StmtAnnAssign (normalizeAlgebraicExpr target) ann (fmap normalizeAlgebraicExpr mVal)
  StmtReturn mExpr ->
    StmtReturn (fmap normalizeAlgebraicExpr mExpr)
  StmtExpr expr ->
    StmtExpr (normalizeAlgebraicExpr expr)
  StmtIf cond thenB elseB ->
    StmtIf
      (normalizeAlgebraicExpr cond)
      (map normalizeAlgebraicStmt thenB)
      (map normalizeAlgebraicStmt elseB)
  StmtWhile cond body elseB ->
    StmtWhile
      (normalizeAlgebraicExpr cond)
      (map normalizeAlgebraicStmt body)
      (map normalizeAlgebraicStmt elseB)
  StmtFor target iter body elseB ->
    StmtFor
      (normalizeAlgebraicExpr target)
      (normalizeAlgebraicExpr iter)
      (map normalizeAlgebraicStmt body)
      (map normalizeAlgebraicStmt elseB)
  StmtAsyncFor target iter body elseB ->
    StmtAsyncFor
      (normalizeAlgebraicExpr target)
      (normalizeAlgebraicExpr iter)
      (map normalizeAlgebraicStmt body)
      (map normalizeAlgebraicStmt elseB)
  StmtWith items body ->
    StmtWith
      [ (normalizeAlgebraicExpr ctx, fmap normalizeAlgebraicExpr mVar)
      | (ctx, mVar) <- items
      ]
      (map normalizeAlgebraicStmt body)
  StmtAsyncWith items body ->
    StmtAsyncWith
      [ (normalizeAlgebraicExpr ctx, fmap normalizeAlgebraicExpr mVar)
      | (ctx, mVar) <- items
      ]
      (map normalizeAlgebraicStmt body)
  StmtTry tryB handlers elseB finB ->
    StmtTry
      (map normalizeAlgebraicStmt tryB)
      [ (fmap normalizeAlgebraicExpr mExc, mAlias, map normalizeAlgebraicStmt hBody)
      | (mExc, mAlias, hBody) <- handlers
      ]
      (map normalizeAlgebraicStmt elseB)
      (map normalizeAlgebraicStmt finB)
  StmtRaise mExc mCause ->
    StmtRaise (fmap normalizeAlgebraicExpr mExc) (fmap normalizeAlgebraicExpr mCause)
  StmtAssert test mMsg ->
    StmtAssert (normalizeAlgebraicExpr test) (fmap normalizeAlgebraicExpr mMsg)
  StmtDelete targets ->
    StmtDelete (map normalizeAlgebraicExpr targets)
  StmtMatch subject cases ->
    StmtMatch
      (normalizeAlgebraicExpr subject)
      [ MatchCase
          (normalizeAlgebraicExpr pat)
          (fmap normalizeAlgebraicExpr mGuard)
          (map normalizeAlgebraicStmt body)
      | MatchCase pat mGuard body <- cases
      ]
  StmtSwitch subject cases defStmts ->
    StmtSwitch
      (normalizeAlgebraicExpr subject)
      [ (normalizeAlgebraicExpr cExpr, map normalizeAlgebraicStmt cStmts)
      | (cExpr, cStmts) <- cases
      ]
      (map normalizeAlgebraicStmt defStmts)
  StmtSelect clauses ->
    StmtSelect
      [ (normalizeComm comm, map normalizeAlgebraicStmt body)
      | (comm, body) <- clauses
      ]
  StmtChanSend ch val ->
    StmtChanSend (normalizeAlgebraicExpr ch) (normalizeAlgebraicExpr val)
  StmtGo expr ->
    StmtGo (normalizeAlgebraicExpr expr)
  StmtDefer expr ->
    StmtDefer (normalizeAlgebraicExpr expr)
  StmtLoop body ->
    StmtLoop (map normalizeAlgebraicStmt body)
  other -> other
  where
    normalizeComm = \case
      SelectSend ch val -> SelectSend (normalizeAlgebraicExpr ch) (normalizeAlgebraicExpr val)
      SelectRecv mV ch  -> SelectRecv mV (normalizeAlgebraicExpr ch)
      SelectDefault     -> SelectDefault

-- | Recursively canonicalize an 'Expr' bottom-up using algebraic identities.
-- Computes expression purity bottom-up in O(N) total time instead of O(N^2) rescans,
-- and uses Schwartzian transform with canonical byte tie-breaking for sorting.
normalizeAlgebraicExpr :: Expr -> Expr
normalizeAlgebraicExpr = fst . normalizeAlgebraicExprWithPurity

normalizeAlgebraicExprWithPurity :: Expr -> (Expr, Bool)
normalizeAlgebraicExprWithPurity = \case
  ExprLit lit -> (ExprLit lit, True)
  ExprId ident -> (ExprId ident, True)
  ExprBinary op lhs rhs ->
    let !(lhs', pL) = normalizeAlgebraicExprWithPurity lhs
        !(rhs', pR) = normalizeAlgebraicExprWithPurity rhs
        !res = normalizeBinaryExprWithPurity op (lhs', pL) (rhs', pR)
    in (res, pL && pR)
  ExprUnary op operand ->
    let !(op', pO) = normalizeAlgebraicExprWithPurity operand
        !res = case (op, op') of
                 (OpNot, ExprUnary OpNot inner) -> inner
                 (OpNot, ExprBinary OpAnd a b)
                   | isNonTrappingPureExpr a && isNonTrappingPureExpr b ->
                       normalizeBinaryExprWithPurity OpOr (negatePure a, True) (negatePure b, True)
                 (OpNot, ExprBinary OpOr a b)
                   | isNonTrappingPureExpr a && isNonTrappingPureExpr b ->
                       normalizeBinaryExprWithPurity OpAnd (negatePure a, True) (negatePure b, True)
                 _ -> ExprUnary op op'
    in (res, pO)
    where
      negatePure (ExprUnary OpNot inner) = inner
      negatePure x                        = ExprUnary OpNot x
  ExprCall callee args kwArgs ->
    let !callee' = normalizeAlgebraicExpr callee
        !args' = map normalizeAlgebraicExpr args
        !kwArgs' = [(k, normalizeAlgebraicExpr v) | (k, v) <- kwArgs]
    in (ExprCall callee' args' kwArgs', False)
  ExprLambda params body ->
    (ExprLambda params (normalizeAlgebraicExpr body), False)
  ExprTernary cond thenE elseE ->
    let !(c', pC) = normalizeAlgebraicExprWithPurity cond
        !(t', pT) = normalizeAlgebraicExprWithPurity thenE
        !(e', pE) = normalizeAlgebraicExprWithPurity elseE
    in (ExprTernary c' t' e', pC && pT && pE)
  ExprList items ->
    let !normed = map normalizeAlgebraicExprWithPurity items
    in (ExprList (map fst normed), all snd normed)
  ExprTuple items ->
    let !normed = map normalizeAlgebraicExprWithPurity items
    in (ExprTuple (map fst normed), all snd normed)
  ExprSet items ->
    let !normed = map normalizeAlgebraicExprWithPurity items
        !pureAll = all snd normed
        !items' = map fst normed
        !res = if pureAll
                 then ExprSet (sortBySchwartzian items')
                 else ExprSet items'
    in (res, pureAll)
  ExprDict pairs ->
    let !normed = [(normalizeAlgebraicExprWithPurity k, normalizeAlgebraicExprWithPurity v) | (k, v) <- pairs]
        !pureAll = all (\((_, pk), (_, pv)) -> pk && pv) normed
        !pairs' = [((k', v')) | ((k', _), (v', _)) <- normed]
        !res = if pureAll
                 then
                   let decorated = [((exprCanonicalKey k, exprCanonicalKey v), (k, v)) | (k, v) <- pairs']
                   in ExprDict (map snd (sortBy (comparing fst) decorated))
                 else ExprDict pairs'
    in (res, pureAll)
  ExprListComp elt comps ->
    (ExprListComp (normalizeAlgebraicExpr elt) (map normalizeComp comps), False)
  ExprSetComp elt comps ->
    (ExprSetComp (normalizeAlgebraicExpr elt) (map normalizeComp comps), False)
  ExprGenerator elt comps ->
    (ExprGenerator (normalizeAlgebraicExpr elt) (map normalizeComp comps), False)
  ExprDictComp kExpr vExpr comps ->
    ( ExprDictComp
        (normalizeAlgebraicExpr kExpr)
        (normalizeAlgebraicExpr vExpr)
        (map normalizeComp comps)
    , False
    )
  ExprAttr obj attr ->
    let !(obj', pO) = normalizeAlgebraicExprWithPurity obj
    in (ExprAttr obj' attr, pO)
  ExprOptChain obj attr ->
    let !(obj', pO) = normalizeAlgebraicExprWithPurity obj
    in (ExprOptChain obj' attr, pO)
  ExprNullish lhs rhs ->
    let !(lhs', pL) = normalizeAlgebraicExprWithPurity lhs
        !(rhs', pR) = normalizeAlgebraicExprWithPurity rhs
    in (ExprNullish lhs' rhs', pL && pR)
  ExprSubscript obj idx ->
    let !(obj', pO) = normalizeAlgebraicExprWithPurity obj
        !(idx', pI) = normalizeAlgebraicExprWithPurity idx
    in (ExprSubscript obj' idx', pO && pI)
  ExprSlice mLower mUpper mStep ->
    ( ExprSlice
        (fmap normalizeAlgebraicExpr mLower)
        (fmap normalizeAlgebraicExpr mUpper)
        (fmap normalizeAlgebraicExpr mStep)
    , False
    )
  ExprAwait operand ->
    (ExprAwait (normalizeAlgebraicExpr operand), False)
  ExprYield mOperand ->
    (ExprYield (fmap normalizeAlgebraicExpr mOperand), False)
  ExprYieldFrom operand ->
    (ExprYieldFrom (normalizeAlgebraicExpr operand), False)
  ExprStarred operand ->
    (ExprStarred (normalizeAlgebraicExpr operand), False)
  ExprKwStarred operand ->
    (ExprKwStarred (normalizeAlgebraicExpr operand), False)
  ExprWalrus name val ->
    (ExprWalrus name (normalizeAlgebraicExpr val), False)
  ExprFormattedString parts ->
    (ExprFormattedString (map normalizeFPart parts), False)
  ExprChanRecv ch ->
    (ExprChanRecv (normalizeAlgebraicExpr ch), False)
  ExprTryOp operand ->
    (ExprTryOp (normalizeAlgebraicExpr operand), False)
  ExprJSX tag attrs children ->
    ( ExprJSX
        tag
        [(k, normalizeAlgebraicExpr v) | (k, v) <- attrs]
        (map normalizeAlgebraicExpr children)
    , False
    )
  ExprMacroCall name args ->
    (ExprMacroCall name (map normalizeAlgebraicExpr args), False)
  where
    normalizeComp (CompFor tgt iter ifs) =
      CompFor
        (normalizeAlgebraicExpr tgt)
        (normalizeAlgebraicExpr iter)
        (map normalizeAlgebraicExpr ifs)
    normalizeFPart = \case
      FStringText txt -> FStringText txt
      FStringExpr e mC mS -> FStringExpr (normalizeAlgebraicExpr e) mC mS

-- | Schwartzian decorate-sort-undecorate over 'Expr' with FNV-1a + canonical byte tie-break.
sortBySchwartzian :: [Expr] -> [Expr]
sortBySchwartzian xs =
  let decorated = [(exprCanonicalKey e, e) | e <- xs]
  in map snd (sortBy (comparing fst) decorated)

-- | Normalize a binary expression (assuming children are already normalized):
--   1. Relational duals: @b > a -> a < b@, @b >= a -> a <= b@ (when pure)
--   2. Associative + commutative flattening and sorting for @+, *, &, |, ^@ (when pure)
--   3. Commutative sorting for @==, !=@ (when pure)
normalizeBinaryExpr :: Op -> Expr -> Expr -> Expr
normalizeBinaryExpr op e1 e2 =
  normalizeBinaryExprWithPurity op (e1, isProvablyPureExpr e1) (e2, isProvablyPureExpr e2)

normalizeBinaryExprWithPurity :: Op -> (Expr, Bool) -> (Expr, Bool) -> Expr
normalizeBinaryExprWithPurity op (e1, p1) (e2, p2) = case op of
  OpGt
    | p1 && p2 -> ExprBinary OpLt e2 e1
    | otherwise -> ExprBinary OpGt e1 e2

  OpGtE
    | p1 && p2 -> ExprBinary OpLtE e2 e1
    | otherwise -> ExprBinary OpGtE e1 e2

  _
    | (op == OpAdd || op == OpMul)
        && canCommute op e1 p1 e2 p2
        && (containsFloatOperand e1 || containsFloatOperand e2) ->
        -- IEEE-754 float safety: allow 2-operand commutativity only, never re-associate (a + b) + c
        if exprCanonicalKey e1 <= exprCanonicalKey e2
          then ExprBinary op e1 e2
          else ExprBinary op e2 e1
    | (op == OpAnd || op == OpOr)
        && p1 && p2
        && isNonTrappingPureExpr e1
        && isNonTrappingPureExpr e2 ->
        let terms = flattenPureBool op e1 ++ flattenPureBool op e2
            sortedTerms = sortBySchwartzian terms
        in case sortedTerms of
             (t:ts) -> foldl (ExprBinary op) t ts
             []     -> ExprBinary op e1 e2
    | isAssociativeCommutativeOp op && canCommute op e1 p1 e2 p2 ->
        let terms = flattenAssocOp op e1 ++ flattenAssocOp op e2
            sortedTerms = sortBySchwartzian terms
        in case sortedTerms of
             (t:ts) -> foldl (ExprBinary op) t ts
             []     -> ExprBinary op e1 e2
    | isCommutativeOp op && canCommute op e1 p1 e2 p2 ->
        if exprCanonicalKey e1 <= exprCanonicalKey e2
          then ExprBinary op e1 e2
          else ExprBinary op e2 e1
    | otherwise ->
        ExprBinary op e1 e2
  where
    canCommute OpAdd a pa b pb =
      pa && pb && not (isConcatenationOperand a) && not (isConcatenationOperand b)
    canCommute _ _ pa _ pb = pa && pb

    flattenAssocOp targetOp expr = case expr of
      ExprBinary innerOp a b
        | innerOp == targetOp
            && canCommute targetOp a True b True
            && not (containsFloatOperand a || containsFloatOperand b) ->
            flattenAssocOp targetOp a ++ flattenAssocOp targetOp b
      _ -> [expr]

    flattenPureBool targetOp expr = case expr of
      ExprBinary innerOp a b
        | innerOp == targetOp && isNonTrappingPureExpr a && isNonTrappingPureExpr b ->
            flattenPureBool targetOp a ++ flattenPureBool targetOp b
      _ -> [expr]

-- | Normalize unordered collection literals ('ExprSet' and 'ExprDict') by sorting
-- elements/entries by their canonical FNV-1a structural hash (with byte tie-break)
-- when all elements are pure.
normalizeCollectionLiteral :: Expr -> Expr
normalizeCollectionLiteral = \case
  ExprSet items
    | all isProvablyPureExpr items ->
        ExprSet (sortBySchwartzian items)
    | otherwise ->
        ExprSet items
  ExprDict pairs
    | all (\(k, v) -> isProvablyPureExpr k && isProvablyPureExpr v) pairs ->
        let decorated = [((exprCanonicalKey k, exprCanonicalKey v), (k, v)) | (k, v) <- pairs]
        in ExprDict (map snd (sortBy (comparing fst) decorated))
    | otherwise ->
        ExprDict pairs
  other -> other