canontra 0.3.0.0 → 0.4.0.0
raw patch · 50 files changed
+7222/−1753 lines, 50 filesdep ~containersPVP ok
version bump matches the API change (PVP)
Dependency ranges changed: containers
API changes (from Hackage documentation)
- Canontra.Repository.Parallel: instance GHC.Show.Show a => GHC.Show.Show (Canontra.Repository.Parallel.DequeState a)
+ Canontra.Analysis.CFGCanonical: computeDominanceFrontiers :: ControlFlowGraph -> Map BlockId BlockId -> Map BlockId (Set BlockId)
+ Canontra.Analysis.CFGCanonical: computeDominators :: ControlFlowGraph -> Map BlockId BlockId
+ Canontra.Analysis.DFG: collectModifiedVars :: [Stmt] -> Set Text
+ Canontra.Analysis.DFG: computeLoopPhiVars :: ScopeStack -> [Stmt] -> Set Text -> [(Text, NodeId)]
+ Canontra.Analysis.DFG: mergeBranchDefs :: ScopeStack -> ScopeStack -> ScopeStack -> NodeId -> ([DFGNode], [DFGEdge], ScopeStack, NodeId)
+ Canontra.Analysis.DFG: mergeMultiBranchDefs :: ScopeStack -> [ScopeStack] -> NodeId -> ([DFGNode], [DFGEdge], ScopeStack, NodeId)
+ Canontra.Analysis.TypeContract: Immut :: Mutability
+ Canontra.Analysis.TypeContract: Mut :: Mutability
+ Canontra.Analysis.TypeContract: TypePtr :: !StructuralType -> StructuralType
+ Canontra.Analysis.TypeContract: TypeRef :: !Mutability -> !StructuralType -> StructuralType
+ Canontra.Analysis.TypeContract: TypeTuple :: ![StructuralType] -> StructuralType
+ Canontra.Analysis.TypeContract: data Mutability
+ Canontra.Analysis.TypeContract: instance Control.DeepSeq.NFData Canontra.Analysis.TypeContract.Mutability
+ Canontra.Analysis.TypeContract: instance Data.Aeson.Types.FromJSON.FromJSON Canontra.Analysis.TypeContract.Mutability
+ Canontra.Analysis.TypeContract: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Analysis.TypeContract.Mutability
+ Canontra.Analysis.TypeContract: instance GHC.Classes.Eq Canontra.Analysis.TypeContract.Mutability
+ Canontra.Analysis.TypeContract: instance GHC.Classes.Ord Canontra.Analysis.TypeContract.Mutability
+ Canontra.Analysis.TypeContract: instance GHC.Generics.Generic Canontra.Analysis.TypeContract.Mutability
+ Canontra.Analysis.TypeContract: instance GHC.Show.Show Canontra.Analysis.TypeContract.Mutability
+ Canontra.Analysis.TypeContract: isStructuralSubtype :: StructuralType -> StructuralType -> Bool
+ Canontra.Analysis.WholeRepoGraph: CallFlowSite :: !CallerNode -> !CalleeTarget -> ![[Text]] -> ![(Text, [Text])] -> CallFlowSite
+ Canontra.Analysis.WholeRepoGraph: FileGraphSummary :: !FilePath -> !Text -> ![Text] -> ![(Text, Text, Text)] -> ![GlobalSymbol] -> ![CallEdge] -> ![CallFlowSite] -> FileGraphSummary
+ Canontra.Analysis.WholeRepoGraph: [cfsCallee] :: CallFlowSite -> !CalleeTarget
+ Canontra.Analysis.WholeRepoGraph: [cfsCaller] :: CallFlowSite -> !CallerNode
+ Canontra.Analysis.WholeRepoGraph: [cfsKwArgs] :: CallFlowSite -> ![(Text, [Text])]
+ Canontra.Analysis.WholeRepoGraph: [cfsPosArgs] :: CallFlowSite -> ![[Text]]
+ Canontra.Analysis.WholeRepoGraph: [fgsCallEdges] :: FileGraphSummary -> ![CallEdge]
+ Canontra.Analysis.WholeRepoGraph: [fgsFilePath] :: FileGraphSummary -> !FilePath
+ Canontra.Analysis.WholeRepoGraph: [fgsFlowSites] :: FileGraphSummary -> ![CallFlowSite]
+ Canontra.Analysis.WholeRepoGraph: [fgsImportedMods] :: FileGraphSummary -> ![Text]
+ Canontra.Analysis.WholeRepoGraph: [fgsModuleName] :: FileGraphSummary -> !Text
+ Canontra.Analysis.WholeRepoGraph: [fgsReExports] :: FileGraphSummary -> ![(Text, Text, Text)]
+ Canontra.Analysis.WholeRepoGraph: [fgsSymbols] :: FileGraphSummary -> ![GlobalSymbol]
+ Canontra.Analysis.WholeRepoGraph: buildWholeRepoCallGraphFromSummaries :: [FileGraphSummary] -> WholeRepoCallGraph
+ Canontra.Analysis.WholeRepoGraph: buildWholeRepoDataFlowFromSummaries :: [FileGraphSummary] -> WholeRepoDataFlowGraph
+ Canontra.Analysis.WholeRepoGraph: data CallFlowSite
+ Canontra.Analysis.WholeRepoGraph: data FileGraphSummary
+ Canontra.Analysis.WholeRepoGraph: extractFileGraphSummary :: FilePath -> Program -> FileGraphSummary
+ Canontra.Analysis.WholeRepoGraph: instance Control.DeepSeq.NFData Canontra.Analysis.WholeRepoGraph.CallFlowSite
+ Canontra.Analysis.WholeRepoGraph: instance Control.DeepSeq.NFData Canontra.Analysis.WholeRepoGraph.FileGraphSummary
+ Canontra.Analysis.WholeRepoGraph: instance GHC.Classes.Eq Canontra.Analysis.WholeRepoGraph.CallFlowSite
+ Canontra.Analysis.WholeRepoGraph: instance GHC.Classes.Eq Canontra.Analysis.WholeRepoGraph.FileGraphSummary
+ Canontra.Analysis.WholeRepoGraph: instance GHC.Classes.Ord Canontra.Analysis.WholeRepoGraph.CallFlowSite
+ Canontra.Analysis.WholeRepoGraph: instance GHC.Classes.Ord Canontra.Analysis.WholeRepoGraph.FileGraphSummary
+ Canontra.Analysis.WholeRepoGraph: instance GHC.Generics.Generic Canontra.Analysis.WholeRepoGraph.CallFlowSite
+ Canontra.Analysis.WholeRepoGraph: instance GHC.Generics.Generic Canontra.Analysis.WholeRepoGraph.FileGraphSummary
+ Canontra.Analysis.WholeRepoGraph: instance GHC.Show.Show Canontra.Analysis.WholeRepoGraph.CallFlowSite
+ Canontra.Analysis.WholeRepoGraph: instance GHC.Show.Show Canontra.Analysis.WholeRepoGraph.FileGraphSummary
+ Canontra.CLI.Commands: CmdSnap :: SnapAction -> FilePath -> Bool -> Command
+ Canontra.CLI.Commands: SnapDiff :: !Text -> !Text -> !Bool -> SnapAction
+ Canontra.CLI.Commands: SnapGC :: !Int -> SnapAction
+ Canontra.CLI.Commands: SnapGuard :: !Text -> !Text -> ![Text] -> SnapAction
+ Canontra.CLI.Commands: SnapInit :: SnapAction
+ Canontra.CLI.Commands: SnapLog :: !Int -> SnapAction
+ Canontra.CLI.Commands: SnapMark :: !Maybe Text -> !Maybe Text -> !Bool -> SnapAction
+ Canontra.CLI.Commands: SnapRewind :: !Text -> ![FilePath] -> !Bool -> SnapAction
+ Canontra.CLI.Commands: data SnapAction
+ Canontra.CLI.Commands: instance GHC.Classes.Eq Canontra.CLI.Commands.SnapAction
+ Canontra.CLI.Commands: instance GHC.Show.Show Canontra.CLI.Commands.SnapAction
+ Canontra.Cache.SlabV7: SlabV7Entry :: !FileMetadata -> !FingerprintBundle -> !Maybe FileGraphSummary -> SlabV7Entry
+ Canontra.Cache.SlabV7: SlabV7Handle :: !FilePath -> !ByteString -> !Ptr Word8 -> !ForeignPtr Word8 -> !Word32 -> !Word32 -> !Ptr Word8 -> !Ptr CacheRecordV6 -> !Maybe WholeRepoBundle -> !Maybe CSRGraph -> !Maybe CSRGraph -> SlabV7Handle
+ Canontra.Cache.SlabV7: [sv7BasePtr] :: SlabV7Handle -> !Ptr Word8
+ Canontra.Cache.SlabV7: [sv7Bundle] :: SlabV7Entry -> !FingerprintBundle
+ Canontra.Cache.SlabV7: [sv7ByteString] :: SlabV7Handle -> !ByteString
+ Canontra.Cache.SlabV7: [sv7FilePath] :: SlabV7Handle -> !FilePath
+ Canontra.Cache.SlabV7: [sv7FileTablePtr] :: SlabV7Handle -> !Ptr CacheRecordV6
+ Canontra.Cache.SlabV7: [sv7ForeignPtr] :: SlabV7Handle -> !ForeignPtr Word8
+ Canontra.Cache.SlabV7: [sv7Meta] :: SlabV7Entry -> !FileMetadata
+ Canontra.Cache.SlabV7: [sv7RadixTablePtr] :: SlabV7Handle -> !Ptr Word8
+ Canontra.Cache.SlabV7: [sv7RecordCapacity] :: SlabV7Handle -> !Word32
+ Canontra.Cache.SlabV7: [sv7RecordCount] :: SlabV7Handle -> !Word32
+ Canontra.Cache.SlabV7: [sv7RepoBundle] :: SlabV7Handle -> !Maybe WholeRepoBundle
+ Canontra.Cache.SlabV7: [sv7RepoCallCSR] :: SlabV7Handle -> !Maybe CSRGraph
+ Canontra.Cache.SlabV7: [sv7RepoDataCSR] :: SlabV7Handle -> !Maybe CSRGraph
+ Canontra.Cache.SlabV7: [sv7Summary] :: SlabV7Entry -> !Maybe FileGraphSummary
+ Canontra.Cache.SlabV7: closeSlabV7 :: SlabV7Handle -> IO ()
+ Canontra.Cache.SlabV7: data SlabV7Entry
+ Canontra.Cache.SlabV7: data SlabV7Handle
+ Canontra.Cache.SlabV7: decodeFileGraphSummary :: ByteString -> Int -> Maybe (FileGraphSummary, Int)
+ Canontra.Cache.SlabV7: decodeSlabV7Binary :: ByteString -> Maybe (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph))
+ Canontra.Cache.SlabV7: decodeSlabV7Resilient :: ByteString -> (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph), [Word32])
+ Canontra.Cache.SlabV7: encodeFileGraphSummary :: FileGraphSummary -> Builder
+ Canontra.Cache.SlabV7: encodeSlabV7Binary :: [SlabV7Entry] -> Maybe (WholeRepoBundle, CSRGraph, CSRGraph) -> ByteString
+ Canontra.Cache.SlabV7: instance Control.DeepSeq.NFData Canontra.Cache.SlabV7.SlabV7Entry
+ Canontra.Cache.SlabV7: instance Control.DeepSeq.NFData Canontra.Cache.SlabV7.SlabV7Handle
+ Canontra.Cache.SlabV7: instance GHC.Base.Applicative Canontra.Cache.SlabV7.Decoder
+ Canontra.Cache.SlabV7: instance GHC.Base.Functor Canontra.Cache.SlabV7.Decoder
+ Canontra.Cache.SlabV7: instance GHC.Base.Monad Canontra.Cache.SlabV7.Decoder
+ Canontra.Cache.SlabV7: instance GHC.Classes.Eq Canontra.Cache.SlabV7.SlabV7Entry
+ Canontra.Cache.SlabV7: instance GHC.Classes.Eq Canontra.Cache.SlabV7.SlabV7Handle
+ Canontra.Cache.SlabV7: instance GHC.Generics.Generic Canontra.Cache.SlabV7.SlabV7Entry
+ Canontra.Cache.SlabV7: instance GHC.Generics.Generic Canontra.Cache.SlabV7.SlabV7Handle
+ Canontra.Cache.SlabV7: instance GHC.Show.Show Canontra.Cache.SlabV7.SlabV7Entry
+ Canontra.Cache.SlabV7: instance GHC.Show.Show Canontra.Cache.SlabV7.SlabV7Handle
+ Canontra.Cache.SlabV7: lookupSlabV7BinaryBS :: FilePath -> FileMetadata -> ByteString -> Maybe (FingerprintBundle, Maybe FileGraphSummary)
+ Canontra.Cache.SlabV7: lookupSlabV7Warm :: SlabV7Handle -> FilePath -> FileMetadata -> IO (Maybe (FingerprintBundle, Maybe FileGraphSummary))
+ Canontra.Cache.SlabV7: openSlabV7 :: FilePath -> IO (Maybe SlabV7Handle)
+ Canontra.Cache.SlabV7: readAnySlabCacheForV7 :: ByteString -> Maybe (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph))
+ Canontra.Cache.SlabV7: readSlabV7File :: FilePath -> IO (Maybe (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph)))
+ Canontra.Cache.SlabV7: readSlabV7FileResilient :: FilePath -> IO (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph), [Word32])
+ Canontra.Cache.SlabV7: verifySlabV7HeaderCRC :: ByteString -> Bool
+ Canontra.Cache.SlabV7: writeSlabV7File :: FilePath -> [SlabV7Entry] -> Maybe (WholeRepoBundle, CSRGraph, CSRGraph) -> IO ()
+ Canontra.Canonical.FastScan: instance Control.DeepSeq.NFData Canontra.Canonical.FastScan.ScanResult
+ Canontra.Canonical.FastScan: instance GHC.Generics.Generic Canontra.Canonical.FastScan.ScanResult
+ Canontra.Canonical.FusedStream: fusedHashNormalizedProgram :: CanonicalProgram -> Fingerprint
+ Canontra.Canonical.FusedStream: fusedStreamNormalizedProgram :: CanonicalProgram -> Builder
+ Canontra.Fingerprint.Bundle: computeBundleFromCanonical :: ByteString -> Program -> CanonicalProgram -> FingerprintBundle
+ Canontra.Fingerprint.CallGraph: computeFCGNormalized :: CanonicalProgram -> Fingerprint
+ Canontra.Fingerprint.ControlFlow: computeFCFNormalized :: CanonicalProgram -> Fingerprint
+ Canontra.Fingerprint.DataFlow: computeFDFNormalized :: CanonicalProgram -> Fingerprint
+ Canontra.Fingerprint.Structural: computeF1Normalized :: CanonicalProgram -> Fingerprint
+ Canontra.Harness.Guard: GuardViolation :: !FilePath -> !Text -> !Text -> ![Text] -> ![Text] -> GuardViolation
+ Canontra.Harness.Guard: SnapGuardReport :: !Text -> !Text -> !Text -> ![Text] -> ![Text] -> !Bool -> ![GuardViolation] -> ![FilePath] -> !Double -> SnapGuardReport
+ Canontra.Harness.Guard: TierF0 :: GuardTier
+ Canontra.Harness.Guard: TierF1 :: GuardTier
+ Canontra.Harness.Guard: TierF2 :: GuardTier
+ Canontra.Harness.Guard: TierF3 :: GuardTier
+ Canontra.Harness.Guard: TierF4 :: GuardTier
+ Canontra.Harness.Guard: TierFCF :: GuardTier
+ Canontra.Harness.Guard: TierFCG :: GuardTier
+ Canontra.Harness.Guard: TierFDF :: GuardTier
+ Canontra.Harness.Guard: TierFT :: GuardTier
+ Canontra.Harness.Guard: [gvMutatedTiers] :: GuardViolation -> ![Text]
+ Canontra.Harness.Guard: [gvPath] :: GuardViolation -> !FilePath
+ Canontra.Harness.Guard: [gvSeverity] :: GuardViolation -> !Text
+ Canontra.Harness.Guard: [gvStatus] :: GuardViolation -> !Text
+ Canontra.Harness.Guard: [gvViolatedTiers] :: GuardViolation -> ![Text]
+ Canontra.Harness.Guard: [sgrAgainstSnapId] :: SnapGuardReport -> !Text
+ Canontra.Harness.Guard: [sgrAllowPaths] :: SnapGuardReport -> ![Text]
+ Canontra.Harness.Guard: [sgrAllowedSkipped] :: SnapGuardReport -> ![FilePath]
+ Canontra.Harness.Guard: [sgrElapsedMs] :: SnapGuardReport -> !Double
+ Canontra.Harness.Guard: [sgrForbiddenTiers] :: SnapGuardReport -> ![Text]
+ Canontra.Harness.Guard: [sgrPassed] :: SnapGuardReport -> !Bool
+ Canontra.Harness.Guard: [sgrSchemaVersion] :: SnapGuardReport -> !Text
+ Canontra.Harness.Guard: [sgrStability] :: SnapGuardReport -> !Text
+ Canontra.Harness.Guard: [sgrViolations] :: SnapGuardReport -> ![GuardViolation]
+ Canontra.Harness.Guard: data GuardTier
+ Canontra.Harness.Guard: data GuardViolation
+ Canontra.Harness.Guard: data SnapGuardReport
+ Canontra.Harness.Guard: formatSnapGuard :: SnapGuardReport -> Text
+ Canontra.Harness.Guard: formatSnapGuardJson :: SnapGuardReport -> ByteString
+ Canontra.Harness.Guard: guardTierName :: GuardTier -> Text
+ Canontra.Harness.Guard: instance Control.DeepSeq.NFData Canontra.Harness.Guard.GuardTier
+ Canontra.Harness.Guard: instance Control.DeepSeq.NFData Canontra.Harness.Guard.GuardViolation
+ Canontra.Harness.Guard: instance Control.DeepSeq.NFData Canontra.Harness.Guard.SnapGuardReport
+ Canontra.Harness.Guard: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Harness.Guard.GuardTier
+ Canontra.Harness.Guard: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Harness.Guard.GuardViolation
+ Canontra.Harness.Guard: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Harness.Guard.SnapGuardReport
+ Canontra.Harness.Guard: instance GHC.Classes.Eq Canontra.Harness.Guard.GuardTier
+ Canontra.Harness.Guard: instance GHC.Classes.Eq Canontra.Harness.Guard.GuardViolation
+ Canontra.Harness.Guard: instance GHC.Classes.Eq Canontra.Harness.Guard.SnapGuardReport
+ Canontra.Harness.Guard: instance GHC.Classes.Ord Canontra.Harness.Guard.GuardTier
+ Canontra.Harness.Guard: instance GHC.Generics.Generic Canontra.Harness.Guard.GuardTier
+ Canontra.Harness.Guard: instance GHC.Generics.Generic Canontra.Harness.Guard.GuardViolation
+ Canontra.Harness.Guard: instance GHC.Generics.Generic Canontra.Harness.Guard.SnapGuardReport
+ Canontra.Harness.Guard: instance GHC.Show.Show Canontra.Harness.Guard.GuardTier
+ Canontra.Harness.Guard: instance GHC.Show.Show Canontra.Harness.Guard.GuardViolation
+ Canontra.Harness.Guard: instance GHC.Show.Show Canontra.Harness.Guard.SnapGuardReport
+ Canontra.Harness.Guard: matchesGlob :: Text -> Text -> Bool
+ Canontra.Harness.Guard: parseGuardTiers :: Text -> Either String [GuardTier]
+ Canontra.Harness.Guard: snapGuard :: FilePath -> Text -> [GuardTier] -> [Text] -> IO (Either String SnapGuardReport)
+ Canontra.Harness.Store: LedgerEntry :: !Text -> !Maybe Text -> !Text -> !Maybe Text -> !Maybe Text -> !SnapClassification -> !Text -> !Int -> !Int -> !Double -> LedgerEntry
+ Canontra.Harness.Store: SnapContractChange :: SnapClassification
+ Canontra.Harness.Store: SnapFileDelta :: !FilePath -> !Text -> !Text -> ![Text] -> ![Text] -> SnapFileDelta
+ Canontra.Harness.Store: SnapFileRecord :: !FilePath -> !Text -> !Integer -> !FingerprintBundle -> SnapFileRecord
+ Canontra.Harness.Store: SnapInternalLogic :: SnapClassification
+ Canontra.Harness.Store: SnapManifest :: !Text -> !Text -> !Text -> !Maybe Text -> !Text -> !Maybe Text -> !Maybe Text -> !SnapClassification -> !Text -> !Maybe Text -> !Maybe Text -> !Map FilePath SnapFileRecord -> ![SnapFileDelta] -> ![Text] -> !Double -> SnapManifest
+ Canontra.Harness.Store: SnapNoChange :: SnapClassification
+ Canontra.Harness.Store: SnapSemanticNoop :: SnapClassification
+ Canontra.Harness.Store: [leAgent] :: LedgerEntry -> !Maybe Text
+ Canontra.Harness.Store: [leChangedCount] :: LedgerEntry -> !Int
+ Canontra.Harness.Store: [leClassification] :: LedgerEntry -> !SnapClassification
+ Canontra.Harness.Store: [leElapsedMs] :: LedgerEntry -> !Double
+ Canontra.Harness.Store: [leFileCount] :: LedgerEntry -> !Int
+ Canontra.Harness.Store: [leLabel] :: LedgerEntry -> !Maybe Text
+ Canontra.Harness.Store: [leParentId] :: LedgerEntry -> !Maybe Text
+ Canontra.Harness.Store: [leRepoFR] :: LedgerEntry -> !Text
+ Canontra.Harness.Store: [leSnapId] :: LedgerEntry -> !Text
+ Canontra.Harness.Store: [leTimestamp] :: LedgerEntry -> !Text
+ Canontra.Harness.Store: [sfdInvariantTiers] :: SnapFileDelta -> ![Text]
+ Canontra.Harness.Store: [sfdMutatedTiers] :: SnapFileDelta -> ![Text]
+ Canontra.Harness.Store: [sfdPath] :: SnapFileDelta -> !FilePath
+ Canontra.Harness.Store: [sfdSeverity] :: SnapFileDelta -> !Text
+ Canontra.Harness.Store: [sfdStatus] :: SnapFileDelta -> !Text
+ Canontra.Harness.Store: [sfrBundle] :: SnapFileRecord -> !FingerprintBundle
+ Canontra.Harness.Store: [sfrF0] :: SnapFileRecord -> !Text
+ Canontra.Harness.Store: [sfrPath] :: SnapFileRecord -> !FilePath
+ Canontra.Harness.Store: [sfrSize] :: SnapFileRecord -> !Integer
+ Canontra.Harness.Store: [smAgent] :: SnapManifest -> !Maybe Text
+ Canontra.Harness.Store: [smChangedFiles] :: SnapManifest -> ![SnapFileDelta]
+ Canontra.Harness.Store: [smClassification] :: SnapManifest -> !SnapClassification
+ Canontra.Harness.Store: [smElapsedMs] :: SnapManifest -> !Double
+ Canontra.Harness.Store: [smFiles] :: SnapManifest -> !Map FilePath SnapFileRecord
+ Canontra.Harness.Store: [smLabel] :: SnapManifest -> !Maybe Text
+ Canontra.Harness.Store: [smParentId] :: SnapManifest -> !Maybe Text
+ Canontra.Harness.Store: [smRecommendedTests] :: SnapManifest -> ![Text]
+ Canontra.Harness.Store: [smRepoFR] :: SnapManifest -> !Text
+ Canontra.Harness.Store: [smRepoFWCG] :: SnapManifest -> !Maybe Text
+ Canontra.Harness.Store: [smRepoFWDF] :: SnapManifest -> !Maybe Text
+ Canontra.Harness.Store: [smSchemaVersion] :: SnapManifest -> !Text
+ Canontra.Harness.Store: [smSnapId] :: SnapManifest -> !Text
+ Canontra.Harness.Store: [smStability] :: SnapManifest -> !Text
+ Canontra.Harness.Store: [smTimestamp] :: SnapManifest -> !Text
+ Canontra.Harness.Store: appendLedgerEntry :: FilePath -> LedgerEntry -> IO ()
+ Canontra.Harness.Store: canontraStateDir :: FilePath -> FilePath
+ Canontra.Harness.Store: classificationText :: SnapClassification -> Text
+ Canontra.Harness.Store: data LedgerEntry
+ Canontra.Harness.Store: data SnapClassification
+ Canontra.Harness.Store: data SnapFileDelta
+ Canontra.Harness.Store: data SnapFileRecord
+ Canontra.Harness.Store: data SnapManifest
+ Canontra.Harness.Store: ensureSnapStore :: FilePath -> IO ()
+ Canontra.Harness.Store: getCurrentPidString :: IO String
+ Canontra.Harness.Store: headFilePath :: FilePath -> FilePath
+ Canontra.Harness.Store: instance Control.DeepSeq.NFData Canontra.Harness.Store.LedgerEntry
+ Canontra.Harness.Store: instance Control.DeepSeq.NFData Canontra.Harness.Store.SnapClassification
+ Canontra.Harness.Store: instance Control.DeepSeq.NFData Canontra.Harness.Store.SnapFileDelta
+ Canontra.Harness.Store: instance Control.DeepSeq.NFData Canontra.Harness.Store.SnapFileRecord
+ Canontra.Harness.Store: instance Control.DeepSeq.NFData Canontra.Harness.Store.SnapManifest
+ Canontra.Harness.Store: instance Data.Aeson.Types.FromJSON.FromJSON Canontra.Harness.Store.LedgerEntry
+ Canontra.Harness.Store: instance Data.Aeson.Types.FromJSON.FromJSON Canontra.Harness.Store.SnapClassification
+ Canontra.Harness.Store: instance Data.Aeson.Types.FromJSON.FromJSON Canontra.Harness.Store.SnapFileDelta
+ Canontra.Harness.Store: instance Data.Aeson.Types.FromJSON.FromJSON Canontra.Harness.Store.SnapFileRecord
+ Canontra.Harness.Store: instance Data.Aeson.Types.FromJSON.FromJSON Canontra.Harness.Store.SnapManifest
+ Canontra.Harness.Store: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Harness.Store.LedgerEntry
+ Canontra.Harness.Store: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Harness.Store.SnapClassification
+ Canontra.Harness.Store: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Harness.Store.SnapFileDelta
+ Canontra.Harness.Store: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Harness.Store.SnapFileRecord
+ Canontra.Harness.Store: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Harness.Store.SnapManifest
+ Canontra.Harness.Store: instance GHC.Classes.Eq Canontra.Harness.Store.LedgerEntry
+ Canontra.Harness.Store: instance GHC.Classes.Eq Canontra.Harness.Store.SnapClassification
+ Canontra.Harness.Store: instance GHC.Classes.Eq Canontra.Harness.Store.SnapFileDelta
+ Canontra.Harness.Store: instance GHC.Classes.Eq Canontra.Harness.Store.SnapFileRecord
+ Canontra.Harness.Store: instance GHC.Classes.Eq Canontra.Harness.Store.SnapManifest
+ Canontra.Harness.Store: instance GHC.Classes.Ord Canontra.Harness.Store.SnapClassification
+ Canontra.Harness.Store: instance GHC.Classes.Ord Canontra.Harness.Store.SnapFileDelta
+ Canontra.Harness.Store: instance GHC.Generics.Generic Canontra.Harness.Store.LedgerEntry
+ Canontra.Harness.Store: instance GHC.Generics.Generic Canontra.Harness.Store.SnapClassification
+ Canontra.Harness.Store: instance GHC.Generics.Generic Canontra.Harness.Store.SnapFileDelta
+ Canontra.Harness.Store: instance GHC.Generics.Generic Canontra.Harness.Store.SnapFileRecord
+ Canontra.Harness.Store: instance GHC.Generics.Generic Canontra.Harness.Store.SnapManifest
+ Canontra.Harness.Store: instance GHC.Show.Show Canontra.Harness.Store.LedgerEntry
+ Canontra.Harness.Store: instance GHC.Show.Show Canontra.Harness.Store.SnapClassification
+ Canontra.Harness.Store: instance GHC.Show.Show Canontra.Harness.Store.SnapFileDelta
+ Canontra.Harness.Store: instance GHC.Show.Show Canontra.Harness.Store.SnapFileRecord
+ Canontra.Harness.Store: instance GHC.Show.Show Canontra.Harness.Store.SnapManifest
+ Canontra.Harness.Store: isSafeRelativeFilePath :: FilePath -> Bool
+ Canontra.Harness.Store: isSafeSnapId :: Text -> Bool
+ Canontra.Harness.Store: isValidSha256Hex :: Text -> Bool
+ Canontra.Harness.Store: ledgerFilePath :: FilePath -> FilePath
+ Canontra.Harness.Store: listAllManifestIds :: FilePath -> IO [Text]
+ Canontra.Harness.Store: manifestFilePath :: FilePath -> Text -> FilePath
+ Canontra.Harness.Store: manifestsDir :: FilePath -> FilePath
+ Canontra.Harness.Store: objectBlobPath :: FilePath -> Text -> Maybe FilePath
+ Canontra.Harness.Store: objectsDir :: FilePath -> FilePath
+ Canontra.Harness.Store: parseClassificationText :: Text -> Maybe SnapClassification
+ Canontra.Harness.Store: readHeadSnapId :: FilePath -> IO (Maybe Text)
+ Canontra.Harness.Store: readLedgerEntries :: FilePath -> IO [LedgerEntry]
+ Canontra.Harness.Store: readSnapManifest :: FilePath -> Text -> IO (Either String SnapManifest)
+ Canontra.Harness.Store: readSnapManifestDirect :: FilePath -> Text -> IO (Either String SnapManifest)
+ Canontra.Harness.Store: readVerifiedBlob :: FilePath -> Text -> IO (Either String ByteString)
+ Canontra.Harness.Store: removeManifestFile :: FilePath -> Text -> IO ()
+ Canontra.Harness.Store: resolveSnapId :: FilePath -> Text -> IO (Either String Text)
+ Canontra.Harness.Store: snapsRootDir :: FilePath -> FilePath
+ Canontra.Harness.Store: storeBlobIfAbsent :: FilePath -> Text -> ByteString -> IO Bool
+ Canontra.Harness.Store: writeHeadSnapId :: FilePath -> Text -> IO ()
+ Canontra.Harness.Store: writeSnapManifest :: FilePath -> SnapManifest -> IO ()
+ Canontra.Harness.SubVersion: SnapDiffReport :: !Text -> !Text -> !Text -> !Text -> !SnapClassification -> !Bool -> ![SnapFileDelta] -> ![SnapFileDelta] -> ![SnapFileDelta] -> ![SnapSymbolChange] -> ![Text] -> !Double -> SnapDiffReport
+ Canontra.Harness.SubVersion: SnapGCReport :: !Text -> !Text -> !Int -> !Int -> !Int -> !Int -> !Integer -> SnapGCReport
+ Canontra.Harness.SubVersion: SnapRewindReport :: !Text -> !Text -> !Text -> !Bool -> ![FilePath] -> ![FilePath] -> !Int -> !Double -> SnapRewindReport
+ Canontra.Harness.SubVersion: SnapSymbolChange :: !FilePath -> !Text -> !Text -> !Text -> SnapSymbolChange
+ Canontra.Harness.SubVersion: [gcrLiveBlobs] :: SnapGCReport -> !Int
+ Canontra.Harness.SubVersion: [gcrPrunedSnaps] :: SnapGCReport -> !Int
+ Canontra.Harness.SubVersion: [gcrReclaimedBytes] :: SnapGCReport -> !Integer
+ Canontra.Harness.SubVersion: [gcrRemovedBlobs] :: SnapGCReport -> !Int
+ Canontra.Harness.SubVersion: [gcrRetainedSnaps] :: SnapGCReport -> !Int
+ Canontra.Harness.SubVersion: [gcrSchemaVersion] :: SnapGCReport -> !Text
+ Canontra.Harness.SubVersion: [gcrStability] :: SnapGCReport -> !Text
+ Canontra.Harness.SubVersion: [sdrClassification] :: SnapDiffReport -> !SnapClassification
+ Canontra.Harness.SubVersion: [sdrCompact] :: SnapDiffReport -> !Bool
+ Canontra.Harness.SubVersion: [sdrElapsedMs] :: SnapDiffReport -> !Double
+ Canontra.Harness.SubVersion: [sdrFromSnap] :: SnapDiffReport -> !Text
+ Canontra.Harness.SubVersion: [sdrLevel1Trivia] :: SnapDiffReport -> ![SnapFileDelta]
+ Canontra.Harness.SubVersion: [sdrLevel2Logic] :: SnapDiffReport -> ![SnapFileDelta]
+ Canontra.Harness.SubVersion: [sdrLevel3Contract] :: SnapDiffReport -> ![SnapFileDelta]
+ Canontra.Harness.SubVersion: [sdrRecommendedTests] :: SnapDiffReport -> ![Text]
+ Canontra.Harness.SubVersion: [sdrSchemaVersion] :: SnapDiffReport -> !Text
+ Canontra.Harness.SubVersion: [sdrStability] :: SnapDiffReport -> !Text
+ Canontra.Harness.SubVersion: [sdrSymbolChanges] :: SnapDiffReport -> ![SnapSymbolChange]
+ Canontra.Harness.SubVersion: [sdrToSnap] :: SnapDiffReport -> !Text
+ Canontra.Harness.SubVersion: [srrDryRun] :: SnapRewindReport -> !Bool
+ Canontra.Harness.SubVersion: [srrElapsedMs] :: SnapRewindReport -> !Double
+ Canontra.Harness.SubVersion: [srrRemovedFiles] :: SnapRewindReport -> ![FilePath]
+ Canontra.Harness.SubVersion: [srrRestoredFiles] :: SnapRewindReport -> ![FilePath]
+ Canontra.Harness.SubVersion: [srrSchemaVersion] :: SnapRewindReport -> !Text
+ Canontra.Harness.SubVersion: [srrStability] :: SnapRewindReport -> !Text
+ Canontra.Harness.SubVersion: [srrTargetSnapId] :: SnapRewindReport -> !Text
+ Canontra.Harness.SubVersion: [srrUnchangedSkip] :: SnapRewindReport -> !Int
+ Canontra.Harness.SubVersion: [sscAction] :: SnapSymbolChange -> !Text
+ Canontra.Harness.SubVersion: [sscDetail] :: SnapSymbolChange -> !Text
+ Canontra.Harness.SubVersion: [sscFile] :: SnapSymbolChange -> !FilePath
+ Canontra.Harness.SubVersion: [sscSymbol] :: SnapSymbolChange -> !Text
+ Canontra.Harness.SubVersion: allTierNames :: [Text]
+ Canontra.Harness.SubVersion: classifySnapDeltas :: [SnapFileDelta] -> SnapClassification
+ Canontra.Harness.SubVersion: computeFileDeltas :: Map FilePath SnapFileRecord -> Map FilePath SnapFileRecord -> [SnapFileDelta]
+ Canontra.Harness.SubVersion: data SnapDiffReport
+ Canontra.Harness.SubVersion: data SnapGCReport
+ Canontra.Harness.SubVersion: data SnapRewindReport
+ Canontra.Harness.SubVersion: data SnapSymbolChange
+ Canontra.Harness.SubVersion: diffFileBundles :: FingerprintBundle -> FingerprintBundle -> ([Text], [Text], Text)
+ Canontra.Harness.SubVersion: formatSnapDiff :: Bool -> SnapDiffReport -> Text
+ Canontra.Harness.SubVersion: formatSnapDiffJson :: Bool -> SnapDiffReport -> ByteString
+ Canontra.Harness.SubVersion: formatSnapGC :: SnapGCReport -> Text
+ Canontra.Harness.SubVersion: formatSnapGCJson :: SnapGCReport -> ByteString
+ Canontra.Harness.SubVersion: formatSnapLog :: Maybe Text -> [LedgerEntry] -> Text
+ Canontra.Harness.SubVersion: formatSnapLogJson :: Maybe Text -> [LedgerEntry] -> ByteString
+ Canontra.Harness.SubVersion: formatSnapManifest :: Bool -> SnapManifest -> Text
+ Canontra.Harness.SubVersion: formatSnapManifestJson :: SnapManifest -> ByteString
+ Canontra.Harness.SubVersion: formatSnapRewind :: SnapRewindReport -> Text
+ Canontra.Harness.SubVersion: formatSnapRewindJson :: SnapRewindReport -> ByteString
+ Canontra.Harness.SubVersion: instance Control.DeepSeq.NFData Canontra.Harness.SubVersion.SnapDiffReport
+ Canontra.Harness.SubVersion: instance Control.DeepSeq.NFData Canontra.Harness.SubVersion.SnapGCReport
+ Canontra.Harness.SubVersion: instance Control.DeepSeq.NFData Canontra.Harness.SubVersion.SnapRewindReport
+ Canontra.Harness.SubVersion: instance Control.DeepSeq.NFData Canontra.Harness.SubVersion.SnapSymbolChange
+ Canontra.Harness.SubVersion: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Harness.SubVersion.SnapDiffReport
+ Canontra.Harness.SubVersion: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Harness.SubVersion.SnapGCReport
+ Canontra.Harness.SubVersion: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Harness.SubVersion.SnapRewindReport
+ Canontra.Harness.SubVersion: instance Data.Aeson.Types.ToJSON.ToJSON Canontra.Harness.SubVersion.SnapSymbolChange
+ Canontra.Harness.SubVersion: instance GHC.Classes.Eq Canontra.Harness.SubVersion.SnapDiffReport
+ Canontra.Harness.SubVersion: instance GHC.Classes.Eq Canontra.Harness.SubVersion.SnapGCReport
+ Canontra.Harness.SubVersion: instance GHC.Classes.Eq Canontra.Harness.SubVersion.SnapRewindReport
+ Canontra.Harness.SubVersion: instance GHC.Classes.Eq Canontra.Harness.SubVersion.SnapSymbolChange
+ Canontra.Harness.SubVersion: instance GHC.Classes.Ord Canontra.Harness.SubVersion.SnapSymbolChange
+ Canontra.Harness.SubVersion: instance GHC.Generics.Generic Canontra.Harness.SubVersion.SnapDiffReport
+ Canontra.Harness.SubVersion: instance GHC.Generics.Generic Canontra.Harness.SubVersion.SnapGCReport
+ Canontra.Harness.SubVersion: instance GHC.Generics.Generic Canontra.Harness.SubVersion.SnapRewindReport
+ Canontra.Harness.SubVersion: instance GHC.Generics.Generic Canontra.Harness.SubVersion.SnapSymbolChange
+ Canontra.Harness.SubVersion: instance GHC.Show.Show Canontra.Harness.SubVersion.SnapDiffReport
+ Canontra.Harness.SubVersion: instance GHC.Show.Show Canontra.Harness.SubVersion.SnapGCReport
+ Canontra.Harness.SubVersion: instance GHC.Show.Show Canontra.Harness.SubVersion.SnapRewindReport
+ Canontra.Harness.SubVersion: instance GHC.Show.Show Canontra.Harness.SubVersion.SnapSymbolChange
+ Canontra.Harness.SubVersion: recommendTestsForDeltas :: FilePath -> [FilePath] -> [SnapFileDelta] -> IO [Text]
+ Canontra.Harness.SubVersion: scanWorkspaceRecords :: FilePath -> IO (Either String (RepositoryManifest, Map FilePath SnapFileRecord))
+ Canontra.Harness.SubVersion: snapDiff :: FilePath -> Text -> Text -> Bool -> IO (Either String SnapDiffReport)
+ Canontra.Harness.SubVersion: snapGC :: FilePath -> Int -> IO (Either String SnapGCReport)
+ Canontra.Harness.SubVersion: snapInit :: FilePath -> IO (Either String SnapManifest)
+ Canontra.Harness.SubVersion: snapLog :: FilePath -> Int -> IO (Either String (Maybe Text, [LedgerEntry]))
+ Canontra.Harness.SubVersion: snapMark :: FilePath -> Maybe Text -> Maybe Text -> Bool -> IO (Either String (SnapManifest, Bool))
+ Canontra.Harness.SubVersion: snapRewind :: FilePath -> Text -> [FilePath] -> Bool -> IO (Either String SnapRewindReport)
+ Canontra.Harness.SubVersion: toRunnableTestCommand :: FilePath -> Text
+ Canontra.Normalize.Algebraic: containsFloatOperand :: Expr -> Bool
+ Canontra.Normalize.Algebraic: isNonTrappingPureExpr :: Expr -> Bool
+ Canontra.Normalize.Alpha: [aeBindingDepths] :: AlphaEnv -> !Map Text Int
+ Canontra.Normalize.Alpha: [aeLanguage] :: AlphaEnv -> !Text
+ Canontra.Normalize.Alpha: canonicalizeAlphaModuleForLang :: Text -> Module -> Module
+ Canontra.Normalize.Alpha: canonicalizeFunctionLocalsForLang :: Text -> Set Text -> Function -> Function
+ Canontra.Normalize.Alpha: emptyAlphaEnvForLang :: Text -> Set Text -> AlphaEnv
+ Canontra.Normalize.Normalize: CanonicalProgram :: Program -> CanonicalProgram
+ Canontra.Normalize.Normalize: [unCanonicalProgram] :: CanonicalProgram -> Program
+ Canontra.Normalize.Normalize: instance Control.DeepSeq.NFData Canontra.Normalize.Normalize.CanonicalProgram
+ Canontra.Normalize.Normalize: instance GHC.Classes.Eq Canontra.Normalize.Normalize.CanonicalProgram
+ Canontra.Normalize.Normalize: instance GHC.Show.Show Canontra.Normalize.Normalize.CanonicalProgram
+ Canontra.Normalize.Normalize: newtype CanonicalProgram
+ Canontra.Normalize.Normalize: toCanonicalProgram :: Program -> CanonicalProgram
+ Canontra.Normalize.Rules: snapSchemaVersion :: Text
+ Canontra.Normalize.Rules: snapStability :: Text
+ Canontra.Parser.FastPython: advanceColumnW8 :: Int -> Word8 -> Int
+ Canontra.Parser.FastPython: tokenizeFastPythonBS :: ByteString -> Either (Int, Int, String) [LocatedToken]
+ Canontra.Parser.Go: parseGoByteString :: FilePath -> ByteString -> Either ParseError Program
+ Canontra.Parser.JS: parseJSByteString :: FilePath -> ByteString -> Either ParseError Program
+ Canontra.Parser.JS: tokenizeJSByteString :: ByteString -> [JSToken]
+ Canontra.Parser.Polyglot: parsePolyglotByteString :: FilePath -> ByteString -> Either ParseError Program
+ Canontra.Parser.Polyglot: parsePolyglotByteStringWithLang :: LanguageTag -> FilePath -> ByteString -> Either ParseError Program
+ Canontra.Parser.Python: LocatedToken :: PyToken -> Int -> Int -> LocatedToken
+ Canontra.Parser.Python: TokBytes :: Text -> PyToken
+ Canontra.Parser.Python: TokDedent :: PyToken
+ Canontra.Parser.Python: TokEOF :: PyToken
+ Canontra.Parser.Python: TokFStr :: [FStringPart] -> PyToken
+ Canontra.Parser.Python: TokFloat :: Double -> PyToken
+ Canontra.Parser.Python: TokIdent :: Text -> PyToken
+ Canontra.Parser.Python: TokIndent :: PyToken
+ Canontra.Parser.Python: TokKw :: Text -> PyToken
+ Canontra.Parser.Python: TokNewline :: PyToken
+ Canontra.Parser.Python: TokNum :: Integer -> PyToken
+ Canontra.Parser.Python: TokStr :: Text -> PyToken
+ Canontra.Parser.Python: TokSymbol :: Text -> PyToken
+ Canontra.Parser.Python: [ltCol] :: LocatedToken -> Int
+ Canontra.Parser.Python: [ltLine] :: LocatedToken -> Int
+ Canontra.Parser.Python: [ltToken] :: LocatedToken -> PyToken
+ Canontra.Parser.Python: data LocatedToken
+ Canontra.Parser.Python: data PyToken
+ Canontra.Parser.Python: parsePythonTokens :: FilePath -> [LocatedToken] -> Either ParseError Program
+ Canontra.Parser.Rust: parseRustByteString :: FilePath -> ByteString -> Either ParseError Program
+ Canontra.Repository.Parallel: instance GHC.Show.Show (Canontra.Repository.Parallel.DequeState a)
- Canontra.Normalize.Alpha: AlphaEnv :: !Int -> !Int -> !Map Text Text -> !Set Text -> !Map Int Int -> AlphaEnv
+ Canontra.Normalize.Alpha: AlphaEnv :: !Int -> !Int -> !Map Text Text -> !Map Text Int -> !Set Text -> !Map Int Int -> !Text -> AlphaEnv
- Canontra.Repository.Parallel: ChaseLevDeque :: !Int -> !IORef (DequeState a) -> ChaseLevDeque a
+ Canontra.Repository.Parallel: ChaseLevDeque :: !Int -> !MVar (DequeState a) -> ChaseLevDeque a
- Canontra.Repository.Parallel: DequeState :: !Int -> !Int -> !Vector (Maybe a) -> DequeState a
+ Canontra.Repository.Parallel: DequeState :: !Int -> !Int -> !IOVector (Maybe a) -> DequeState a
- Canontra.Repository.Parallel: [cldState] :: ChaseLevDeque a -> !IORef (DequeState a)
+ Canontra.Repository.Parallel: [cldState] :: ChaseLevDeque a -> !MVar (DequeState a)
- Canontra.Repository.Parallel: [dsBuffer] :: DequeState a -> !Vector (Maybe a)
+ Canontra.Repository.Parallel: [dsBuffer] :: DequeState a -> !IOVector (Maybe a)
Files
- BENCHMARKS.md +125/−117
- CHANGELOG.md +36/−0
- CONTRIBUTING.md +11/−6
- HARNESS.md +184/−0
- README.md +45/−4
- REAL_WORLD_BENCHMARKS.md +10/−4
- SECURITY.md +16/−6
- bench/Bench.hs +204/−155
- benchmarkReport.md +120/−176
- canontra.cabal +13/−5
- src/Canontra/Analysis/BatchImpact.hs +6/−7
- src/Canontra/Analysis/CFG.hs +137/−48
- src/Canontra/Analysis/CFGCanonical.hs +203/−5
- src/Canontra/Analysis/DFG.hs +225/−72
- src/Canontra/Analysis/Impact.hs +19/−6
- src/Canontra/Analysis/TypeContract.hs +164/−29
- src/Canontra/Analysis/WholeRepoGraph.hs +403/−224
- src/Canontra/CLI/Cache.hs +88/−28
- src/Canontra/CLI/Commands.hs +194/−10
- src/Canontra/CLI/Completions.hs +34/−1
- src/Canontra/Cache/Inode.hs +4/−4
- src/Canontra/Cache/MerkleCache.hs +5/−0
- src/Canontra/Cache/PagedCache.hs +2/−1
- src/Canontra/Cache/SlabV7.hs +927/−0
- src/Canontra/Canonical/FastScan.hs +7/−1
- src/Canontra/Canonical/FusedStream.hs +27/−11
- src/Canontra/Export/Graph.hs +10/−2
- src/Canontra/Fingerprint/Bundle.hs +48/−32
- src/Canontra/Fingerprint/CallGraph.hs +8/−4
- src/Canontra/Fingerprint/ControlFlow.hs +8/−4
- src/Canontra/Fingerprint/DataFlow.hs +8/−4
- src/Canontra/Fingerprint/Structural.hs +7/−1
- src/Canontra/Fingerprint/TypeContract.hs +9/−0
- src/Canontra/Harness/Guard.hs +259/−0
- src/Canontra/Harness/Store.hs +537/−0
- src/Canontra/Harness/SubVersion.hs +982/−0
- src/Canontra/Normalize/Algebraic.hs +193/−84
- src/Canontra/Normalize/Alpha.hs +147/−59
- src/Canontra/Normalize/Normalize.hs +157/−114
- src/Canontra/Normalize/Rules.hs +15/−4
- src/Canontra/Parser/FastPython.hs +530/−8
- src/Canontra/Parser/Go.hs +200/−66
- src/Canontra/Parser/JS.hs +351/−128
- src/Canontra/Parser/Polyglot.hs +26/−6
- src/Canontra/Parser/Python.hs +25/−12
- src/Canontra/Parser/Rust.hs +270/−119
- src/Canontra/Repository/Parallel.hs +104/−87
- src/Canontra/Repository/Repository.hs +85/−59
- technicalSpecs.md +31/−37
- test/Canontra/MetamorphicSpec.hs +3/−3
BENCHMARKS.md view
@@ -1,117 +1,125 @@-# Canontra Performance Benchmarks - -Empirical Evaluation, Latency Measurements, and Algorithmic Complexity -**Version**: `v0.3.0.0` (Release `v0.3.0`) Deep Algebraic Equivalence & CSR-Native CIA 2.0 -**Test Environment**: x86_64, Windows 11 Enterprise (Build 26100), GHC 9.6.6 with `-O2` optimizations -**Repository**: <https://github.com/symtrace/canontra> - -## 1. Overview and Benchmarking Methodology - -This document details empirical benchmark results for Canontra v0.3.0 across synthetic micro-modules, real-world source files, polyglot frontends, unboxed Compressed Sparse Row (CSR) graphs, `CNTR\x06` memory-mapped slab caches, bound $\alpha$-renaming canonicalization, algebraic commutativity normalizers, and repository-scale Merkle DAG trees. - -All benchmarks were measured using wall-clock and cycle-accurate tracking via `tasty-bench` under GHC 9.6.6 with optimization level `-O2`. Benchmarks isolate each stage of the compilation pipeline: -* **Stage 1**: Hardware-accelerated 256-bit SIMD FastScan (`Canontra.Canonical.SIMDScan`) processing 32 bytes/cycle with 4 parallel 64-bit SWAR vector lanes for non-ASCII detection and CRLF newline conversion. -* **Stage 2**: Direct-to-IR polyglot parsing into Flat Linear Arenas (`LinearAST`) with zero intermediate CST allocation. -* **Stage 3**: Scope-aware bound lexical $\alpha$-canonicalization (`Canontra.Normalize.Alpha`), mapping internal local variables, loop iterators, comprehension binders, lambda parameters, and exception bindings to de Bruijn indices (`@v<depth>.<ordinal>`). -* **Stage 4**: Purity-guarded commutative and associative algebraic normalization (`Canontra.Normalize.Algebraic`) for `+`, `*`, `&`, `|`, `^`, `==`, `!=`, and relational dual inversion (`>` $\to$ `<`, `>=` $\to$ `<=`). -* **Stage 5**: CFG dominator-tree and Reverse Post-Order (RPO) canonicalization (`Canontra.Analysis.CFGCanonical`), lifting early returns and inverting negative condition branches. -* **Stage 6**: Structural type contract ($F_T$) extraction (`Canontra.Analysis.TypeContract`) with recursive Union/Intersection ANF flattening and positional generic parameter de Bruijn normalization (`[T, U]` $\to$ `[α0, α1]`). -* **Stage 7**: Unboxed Compressed Sparse Row (CSR) graph compilation (`Canontra.Analysis.CSRGraph`), eliminating heap pointer chasing with linear Tarjan SCC condensation, $O(\log(\text{deg}(u)))$ binary-search edge queries, and multi-file PR batch change impact analysis (`Canontra.Analysis.BatchImpact`). -* **Stage 8**: Canonical binary serialization and multi-tier cryptographic hashing ($F_0$ through $F_4$). -* **Stage 9**: `CNTR\x06` Zero-Copy Memory-Mapped Slab Cache (`Canontra.Cache.SlabV6`) with 64-byte CPU cacheline-aligned records and 256-way L1 Radix Jump Table. - -## 2. Pipeline Stage Latency across File Scales (RQ1) - -Measurements across five file scale tiers: -* **Micro**: ~25 Lines of Code (2 functions) -* **Small**: ~85 Lines of Code (10 functions) -* **Medium**: ~405 Lines of Code (50 functions) -* **Large**: ~1,605 Lines of Code (200 functions) -* **Monolithic (XL)**: ~4,005 Lines of Code (500 functions) - -### Latency by Pipeline Stage - -| Pipeline Stage | Micro (~25 LOC) | Small (~85 LOC) | Medium (~405 LOC) | Large (~1,605 LOC) | XL (~4,005 LOC) | Complexity | -| :--- | :---: | :---: | :---: | :---: | :---: | :--- | -| **1. 256-Bit SIMD Scan** | 7.8 μs | 23.4 μs | 92.1 μs | 175 μs | 268 μs | $O(N)$ 32 bytes/cycle | -| **2. Direct-to-IR AST Parsing** | 397 μs | 1.43 ms | 22.1 ms | 65.2 ms | 214 ms | $O(N)$ token stream | -| **3. AST Normalization & Serialization** | 150 μs | 1.06 ms | 5.18 ms | 39.5 ms | 74.6 ms | $O(N)$ AST nodes | -| **4. Scope Analysis** | 12.1 ns | 18.4 ns | 31.2 ns | 39.5 ns | 47.3 ns | $O(V)$ scope tree | -| **5. Call Graph Extraction** | 32.1 μs | 85.4 μs | 310 μs | 620 μs | 928 μs | $O(V + E)$ calls | -| **6. CFG Extraction & RPO** | 22.4 ns | 41.2 ns | 64.5 ns | 81.3 ns | 92.4 ns | $O(B + E)$ blocks | -| **7. DFG Def-Use Chains** | 28.5 ns | 49.1 ns | 78.4 ns | 99.2 ns | 121 ns | $O(D + U)$ SSA vars | -| **8. Multi-Tier Hashing (F0-F4)** | 8.2 μs | 22.4 μs | 75.1 μs | 285 μs | 775 μs | $O(B)$ linear stream | -| **Total End-to-End Pipeline** | **325 μs** | **1.59 ms** | **12.7 ms** | **41.8 ms** | **141 ms** | $O(N)$ linear | - -## 3. Polyglot Ingestion Throughput (RQ2) - -Single-module ingestion and complete 9-tier fingerprint bundle generation across supported programming languages (~100 LOC per file): - -| Language | Standard / Conformance | Pipeline Latency | Throughput | AST Memory Model | Intermediate Allocations | -| :--- | :--- | :---: | :---: | :--- | :--- | -| **Python** | 3.8-3.12 (PEP 701, PEP 695, PEP 572) | 1.51 ms | ~108,000 LOC/s | Direct-to-IR Flat Arena | Zero intermediate CST | -| **TypeScript / JS** | ES2024 / TS 5.2 (Resource Management) | 644 ns | ~253,000 LOC/s | Direct-to-IR Flat Arena | Zero intermediate CST | -| **Go** | Go 1.18-1.21+ (Generics, Tilde Sets) | 611 ns | ~312,000 LOC/s | Direct-to-IR Flat Arena | Zero intermediate CST | -| **Rust** | Rust 2021 (GATs, Raw Identifiers) | 602 ns | ~285,000 LOC/s | Direct-to-IR Flat Arena | Zero intermediate CST | - -## 4. Local Build Cache Performance (`CNTR\x06` Slab Cache, RQ14) - -Canontra v0.3.0 leverages the `CNTR\x06` zero-copy memory-mapped cache layout (`.canontra/cache.bin`), persisting 64-byte cacheline-aligned records with 4KB isolated CRC32-protected page blocks: - -* **Cache Hit Lookup (`lookupSlabBinaryBS`)**: **1.66 μs** (in-memory ByteString slice) / **< 500 ns** (virtual memory-mapped pointer fast-path). -* **Whole-Cache Scan & Verification (1,000 Files)**: **1.71 ms** (decode) / **17.2 ms** (full re-encoding of 1,000 bundles). -* **Binary CSR Graph Serialization (`encodeCSRGraph`)**: **46.5 μs** for 500 edges. -* **Binary CSR Graph Deserialization (`decodeCSRGraph`)**: **42.1 ns** via direct pointer casts into unboxed vectors. -* **Isolated 4KB Page Bit-Rot Recovery**: **28 μs** recovery time, salvaging healthy pages when a single 4KB block suffers corruption. - -## 5. Unboxed CSR Graph Engine Benchmarks (RQ13) - -Evaluated across 100-node to 1,000-node dependency and call networks using `Canontra.Analysis.CSRGraph`: - -| Operation | Micro-Benchmark Latency | Complexity | Algorithmic Guarantee | -| :--- | :---: | :---: | :--- | -| **`csrHasEdge` Binary Search (Hit)** | **24.4 ns** | $O(\log(\text{deg}(u)))$ | Binary search over sorted row slice | -| **`forwardReachabilityCone`** | **3.36 μs** | $O(V + E)$ | Forward reachability mask over unboxed array | -| **`tarjanSCC` Cycle Collapse** | **25.0 μs** | $O(V + E)$ | Linear unboxed DFS with single stack frame | -| **`transposeCSR` Matrix Inversion** | **61.8 μs** | $O(V + E)$ | In-memory unboxed row-pointer edge reversal | -| **`condenseSCC` Canonical DAG** | **42.3 μs** | $O(V + E)$ | Acyclic condensation DAG synthesis | -| **`buildCSRGraph` (100 nodes, 500 edges)** | **156 μs** | $O(E \log E)$ | Radix bucket sort with deduplication | -| **`buildCSRCallGraph` (10 modules)** | **13.2 ms** | $O(V + E)$ | Intra-module & inter-module call graph compilation | -| **`buildCSRDataFlow` (10 modules)** | **13.2 ms** | $O(V + E)$ | Whole-repo SSA def-use chain construction | - -## 6. Bound Lexical $\alpha$-Canonicalization & CFG RPO Benchmarks (RQ16) - -Canontra v0.3.0 implements scope-aware bound lexical index rewriting (`@v<depth>.<ordinal>`) and basic-block Reverse Post-Order (RPO) sorting: - -| Operation | Scale | Latency | Invariance Guarantee | -| :--- | :--- | :---: | :--- | -| **`canonicalizeAlphaProgram`** | Medium (~405 LOC) | **87.2 ns** | $F_1, F_{DF}, F_4$ 100% bit-identical under local renames | -| **`canonicalizeAlphaProgram`** | XL (~4,005 LOC) | **93.1 ns** | $F_1, F_{DF}, F_4$ 100% bit-identical under local renames | -| **`canonicalizeCFGRPO`** | XL (~4,005 LOC) | **125.9 ns** | $F_{CF}$ 100% invariant under block ID & branch permutations | - -## 7. Algebraic Normalization & CSR Batch CIA 2.0 (RQ17) - -Purity-guarded commutative and associative algebraic expression rewriting and joint PR batch reachability cone slicing over unboxed CSR matrices: - -| Operation | Scale | Latency | Notes | -| :--- | :--- | :---: | :--- | -| **`normalizeAlgebraicProgram`** | Medium (~405 LOC) | **71.9 ns** | Operands sorted by canonical hash (`+`, `*`, `==`, `!=`) | -| **`normalizeAlgebraicProgram`** | XL (~4,005 LOC) | **81.2 ns** | Sub-100 ns full AST algebraic traversal | -| **`computeBatchImpactSliceCSR`** | PR Batch Changeset | **187.7 μs** | Joint reachability cone across changed PR files | -| **`computeImpactSliceCSR`** | 10 Modules (Full Repo) | **408.9 μs** | Exact test runner command synthesis (`pytest`, `jest`, `go test`) | - -## 8. Multi-Core Work-Stealing Parallelism (RQ15) - -* **Chase-Lev Deque Push/Pop/Steal**: **210 μs** for 100-item atomic batch operations. -* **Work-Stealing Parallel Processing (1,000 Tasks)**: **11.9 ms** across multi-core capabilities. -* **Localized Edge Splicing (`spliceCSREdges`)**: **77.1 μs** for dynamic incremental CSR graph mutation without global re-indexing. -* **Incremental Whole-Repo Graph Update (`incrementalUpdateWholeRepoGraphs`)**: **29.1 ms** for 10 modules when a single file is edited. - -## 9. Comparative Summary vs. Alternative Approaches - -* **Raw SHA-256 Hashing**: Extremely fast (~1.5 μs) but **semantically blind**. A single comment, variable rename, or formatting edit busts remote caches and triggers full CI builds. -* **GitHub CodeQL**: Deep semantic analysis, but database compilation requires **18s to 1,043s** per repository (e.g., 17.4 minutes for `prometheus`). -* **Canontra v0.3.0**: Delivers 9-tier mathematical identity, $\alpha$-invariance, algebraic equivalence, CFG dominator canonicalization, and CSR batch impact analysis in **sub-second to low-second cold latencies**, with **sub-microsecond warm cache hits**. - -For complete real-world measurements across 15 production open-source repositories, see [benchmarkReport.md](benchmarkReport.md). - +# Canontra Performance Benchmarks++Empirical Evaluation, Latency Measurements, and Algorithmic Complexity +**Version**: `v0.4.0.0` (Release `v0.4.0`) Ultra-Low-Latency Pipeline, Accuracy Hardening & `canontra snap` +**Test Environment**: x86_64, Windows 11 (NTFS), GHC 9.6.6 with `-O2` optimizations +**Repository**: <https://github.com/symtrace/canontra> +**Raw CSV Dataset**: [researchBenchmarks/v0.4.0_microbench_results.csv](researchBenchmarks/v0.4.0_microbench_results.csv)++## 1. Overview and Benchmarking Methodology++This document details empirical microbenchmark results for Canontra `v0.4.0` across synthetic modules (`Micro` ~25 LOC to `XL` ~4,005 LOC), polyglot frontends, ByteString/SIMD scanners, unboxed Compressed Sparse Row (CSR) graphs, `CNTR\x06` / `CNTR\x07` incremental binary slab caches, bound $\alpha$-renaming canonicalization, algebraic equivalence normalizers, repository-scale Merkle DAG trees, and `canontra snap` AI harness kernels.++All 159 microbenchmarks (`RQ1`–`RQ19`) were measured using `tasty-bench` (`--timeout 2`) under GHC 9.6.6 with `-O2` optimization. Unlike earlier releases where certain lazy AST structures could stop at WHNF, `v0.4.0` enforces strict full-spine `NFData` (`nf`) evaluation across every benchmark.++Pipeline stages isolated in `bench/Bench.hs`:++* **Stage 1**: 256-bit SIMD/SWAR FastScan (`Canontra.Canonical.SIMDScan`, `Canontra.Canonical.FastScan`) scanning UTF-8 and CRLF line endings.+* **Stage 2**: ByteString/SIMD Direct-to-IR parsing into Flat Linear Arenas (`Canontra.IR.Arena`, `Canontra.Parser.FastPython`, `Python`, `JS`, `Go`, `Rust`).+* **Stage 3**: Scope-aware language-specific bound $\alpha$-canonicalization (`Canontra.Normalize.Alpha`) and purity/IEEE-754 guarded algebraic normal form (`Canontra.Normalize.Algebraic`).+* **Stage 4**: CFG dominator-tree (`computeDominators`) and Reverse Post-Order (`canonicalizeCFGRPO`) canonicalization (`Canontra.Analysis.CFGCanonical`).+* **Stage 5**: ABI-precise structural type contracts (`Canontra.Analysis.TypeContract`) and single-pass `CanonicalProgram` fusion (`Canontra.Normalize.Normalize`).+* **Stage 6**: Unboxed CSR graphs (`Canontra.Analysis.CSRGraph`), per-file `FileGraphSummary` synthesis (`Canontra.Analysis.WholeRepoGraph`), and `CNTR\x07` (`Canontra.Cache.SlabV7`) persistence.+* **Stage 7**: Stateless AI harness delta computation and guard kernels (`Canontra.Harness.SubVersion`, `Canontra.Harness.Guard`).++## 2. Pipeline Stage Latency across File Scales (RQ1)++Measurements across five Python scale tiers:++* **Micro**: ~25 LOC (2 functions)+* **Small**: ~85 LOC (10 functions)+* **Medium**: ~405 LOC (50 functions)+* **Large**: ~1,605 LOC (200 functions)+* **Monolithic (XL)**: ~4,005 LOC (500 functions)++| Pipeline Stage | Micro (~25 LOC) | Small (~85 LOC) | Medium (~405 LOC) | Large (~1,605 LOC) | XL (~4,005 LOC) | Complexity |+| :--- | :---: | :---: | :---: | :---: | :---: | :--- |+| **AST Parsing (`parsePythonSource`)** | 274.7 us | 1.33 ms | 7.52 ms | 55.47 ms | 148.44 ms | $O(N)$ token stream |+| **AST Norm & Serialize** | 80.9 us | 378.4 us | 1.98 ms | 14.65 ms | 28.13 ms | $O(N)$ AST nodes |+| **Scope Analysis (XL)** | — | — | — | — | 11.04 ms | $O(V)$ scope tree |+| **Call Graph Extraction (XL)** | — | — | — | — | 891.1 us | $O(V + E)$ calls |+| **Control-Flow Graph (XL)** | — | — | — | — | 2.81 ms | $O(B + E)$ blocks |+| **Data-Flow Graph (XL)** | — | — | — | — | 25.39 ms | $O(D + U)$ SSA vars |+| **F0 Raw Bytes Hash (XL)** | — | — | — | — | 689.7 us | $O(N)$ SHA-256 |+| **F4 Composite Hash** | — | — | — | — | 119.0 us | $O(1)$ 7-tier fold |+| **Full 8-Tier Pipeline (`computeBundle`)** | **2.17 ms** | **3.96 ms** | **23.83 ms** | **110.94 ms** | **226.56 ms** | $O(N)$ linear |++## 3. Polyglot Ingestion & ByteString/SIMD Parsers (RQ2 & RQ7)++### Complete End-to-End Pipeline (`computeBundle`, ~100 LOC per file)++| Language | Standard / Conformance | Latency (Mean) | `2*Stdev` | AST Memory Model |+| :--- | :--- | :---: | :---: | :--- |+| **Python** | 3.8–3.12 (PEP 701, PEP 695, PEP 572) | 3.86 ms | ± 2.42 ms | Direct-to-IR + Normalized Arena |+| **TypeScript / JS** | ES2024 / TS 5.2 (`using`, JSX, regex lookahead) | 1.76 ms | ± 772.1 us | Direct-to-IR |+| **Go** | Go 1.18–1.21+ (Generics, Tilde Sets, Receivers) | 1.83 ms | ± 881.3 us | Direct-to-IR |+| **Rust** | Rust 2021 (GATs, Raw Identifiers, Macros) | 1.40 ms | ± 986.6 us | Direct-to-IR |++### ByteString-Native & SIMD Parser Kernels (~85 LOC `Small` Tier)++| Parser Kernel | Mean Latency | `2*Stdev` | Notes |+| :--- | :---: | :---: | :--- |+| **`parseGoByteString` (`Go BS`)** | 95.4 us | ± 61.7 us | ByteString UTF-8 parser (`Go Parser Small`: `88.5 us`) |+| **`parseJSByteString` (`JS/TS BS`)** | 137.3 us | ± 21.0 us | ByteString UTF-8 lexer (`TS Parser Small`: `126.6 us`) |+| **`parseRustByteString` (`Rust Small BS`)** | 132.8 us | ± 130.1 us | ByteString UTF-8 lexer (`Rust Small`: `99.2 us`) |+| **`parseFastPythonByteString` (`FastPython BS`)** | 463.9 us | ± 438.7 us | Hybrid indent-stack SWAR parser (`Python Parser Small`: `1.68 ms`) |+| **`parsePolyglotByteString` (Py / TS)** | 628.7 us / 152.6 us | ± 875.4 / ± 89.2 us | Unified polyglot dispatch |++## 4. Local Slab Cache (`CNTR\x07` & `CNTR\x06`) Benchmarks (RQ14 & RQ18)++Canontra `v0.4.0` introduces `CNTR\x07` (`Canontra.Cache.SlabV7`), storing full 9-tier bundles and compact binary `FileGraphSummary` records in 4KB CRC-32C protected slab pages:++### RQ18: `v0.4.0` `CNTR\x07` SlabV7 & Summary Graph Synthesis (10 Modules)++| Operation | Mean Latency | `2*Stdev` | Benefit vs Full Cold Re-Parse |+| :--- | :---: | :---: | :--- |+| **`encodeSlabV7Binary` (10 modules)** | 671.4 us | ± 902.7 us | Encodes bundles + `FileGraphSummary` |+| **`decodeSlabV7Binary` (10 modules)** | 216.7 us | ± 205.7 us | Restores full cache + graph summaries |+| **`lookupSlabV7BinaryBS` (Warm Hit)** | **6.0 us** | ± 3.4 us | Direct ByteString Radix lookup |+| **`buildWholeRepoCallGraphFromSummaries` (10 mods)** | **112.9 us** | ± 34.6 us | **87.3× faster** than full-AST `buildCSRCallGraph` (`9.86 ms`) |+| **`buildWholeRepoDataFlowFromSummaries` (10 mods)** | **65.6 us** | ± 20.7 us | **180.2× faster** than full-AST `buildCSRDataFlow` (`11.82 ms`) |++### RQ14: `CNTR\x06` Slab & CSR Binary Reference Kernels (1,000 Files / 500 Edges)++* **`encodeSlabV6Binary` (1,000 files)**: `16.60 ms`+* **`decodeSlabV6Binary` (1,000 files)**: `4.39 ms`+* **`lookupSlabBinaryBS` (Zero-Copy Warm Hit)**: `2.0 us`+* **`encodeCSRGraph` / `decodeCSRGraph`**: `25.0 us` / `232 ps`++## 5. Unboxed CSR Graph Engine & Chase-Lev Parallelism (RQ13 & RQ15)++| Operation | Mean Latency | `2*Stdev` | Algorithmic Complexity |+| :--- | :---: | :---: | :--- |+| **`csrHasEdge` Binary Search (Hit)** | **21.0 ns** | ± 3.4 ns | $O(\log(\text{deg}(u)))$ |+| **`forwardReachabilityCone` (100 nodes)** | 4.2 us | ± 1.5 us | $O(V + E)$ |+| **`tarjanSCC` Cycle Collapse** | 27.1 us | ± 27.4 us | $O(V + E)$ |+| **`transposeCSR` Matrix Inversion** | 50.7 us | ± 71.8 us | $O(V + E)$ |+| **`condenseSCC` Canonical DAG** | 57.2 us | ± 44.6 us | $O(V + E)$ |+| **`buildCSRGraph` (100 nodes, 500 edges)** | 108.3 us | ± 116.3 us | $O(E \log E)$ |+| **`Chase-Lev Deque` Push/Pop/Steal** | 13.5 us | ± 6.0 us | Lock-free `MV.IOVector` circular buffer |+| **`parProcessWorkStealing` (1,000 tasks)** | 1.14 ms | ± 386.1 us | Work-stealing multi-core scheduler |+| **`spliceCSREdges` Localized Invalidation** | 55.7 us | ± 27.4 us | Localized CSR matrix delta |++## 6. Semantic Normalizers & Batch CIA 2.0 (RQ16 & RQ17, Strict `NFData`)++| Operation | Scale | Mean Latency | `2*Stdev` | Notes |+| :--- | :--- | :---: | :---: | :--- |+| **`canonicalizeAlphaProgram`** | Medium (~405 LOC) | 518.8 us | ± 356.8 us | Language-specific de Bruijn local renaming |+| **`canonicalizeAlphaProgram`** | XL (~4,005 LOC) | 11.33 ms | ± 2.65 ms | Full deep `NFData` spine evaluation |+| **`canonicalizeCFGRPO`** | XL (~4,005 LOC) | 20.02 ms | ± 23.18 ms | Dominator + RPO basic-block relabeling |+| **`normalizeAlgebraicProgram`** | Medium (~405 LOC) | 903.3 us | ± 1.10 ms | Pure commutative + IEEE-754 guarded AST rewrite |+| **`normalizeAlgebraicProgram`** | XL (~4,005 LOC) | 9.38 ms | ± 4.84 ms | Full deep `NFData` spine evaluation |+| **`computeBatchImpactSliceCSR`** | PR Batch Changeset | **164.8 us** | ± 130.1 us | Multi-source CSR reachability slice |+| **`computeImpactSliceCSR`** | 10 Modules | **241.1 us** | ± 82.9 us | Exact impacted test runner synthesis |++## 7. Stateless AI Harness Kernels (`canontra snap` - Alpha, RQ19)++| Harness Kernel | Mean Latency | `2*Stdev` | Role |+| :--- | :---: | :---: | :--- |+| **`diffFileBundles` (9-tier bundle comparison)** | **733.1 ns** | ± 588.4 ns | Computes mutated/invariant tiers & severity |+| **`computeFileDeltas` (1,000 files, 1 dirty)** | **1.73 ms** | ± 1.21 ms | Diffs two 1,000-file snapshot manifests |+| **`classifySnapDeltas` (dirty delta triage)** | **19.9 ns** | ± 3.4 ns | Classifies turn as `no_change`/`semantic_noop`/`internal_logic`/`contract_change` |+| **`parseGuardTiers` (`F2,F3,F_T`)** | **733.1 ns** | ± 241.8 ns | Parses `--forbid` policy flags |+| **`matchesGlob` (`**/*.py`)** | **5.9 us** | ± 7.9 us | Pure POSIX glob matching for `--allow-paths` |++For end-to-end multi-tool wall-clock comparisons across all 15 open-source repositories, see [benchmarkReport.md](benchmarkReport.md).
CHANGELOG.md view
@@ -6,6 +6,42 @@ and this project adheres to the [Haskell Package Versioning Policy (PVP)](https://pvp.haskell.org/) and [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.4.0.0] - 2026-12-01 + +### Ultra-Low Latency Pipeline, Hardened Accuracy & Stateless AI Harness (`canontra snap`, Alpha) + +The v0.4.0 release delivers end-to-end performance optimization (1.80×–12.43× cold and 3.38×–15.18× warm speedups across the 15-repo benchmark corpus), deepened multi-language semantic and type-contract accuracy, and an experimental stateless AI harness sub-versioning CLI (`canontra snap`, Alpha). + +#### Added + +- **Stateless AI Harness Semantic Sub-Versioning (`Canontra.Harness.*`, `canontra snap` — Alpha)**: + - **Alpha Feature** (`schema_version: "0.1-alpha"`, `stability: "alpha"`): zero-daemon, zero-IPC, zero-`.git`-mutation semantic checkpoints stored under `.canontra/snaps/` (`HEAD`, `ledger.jsonl`, `objects/`, `manifests/`). + - Subcommands: `canontra snap init|mark|diff|guard|rewind|log|gc`, with `--label`, `--agent`, `--skip-noop`, `--compact`, `--against`, `--forbid`, `--allow-paths`, `--file`, `--dry-run`, `--limit`, `--keep-last`, `--dir`, and `--json`. + - Auto-creates `.canontra/.gitignore` on `snap init`; enforces `isSafeSnapId`, `isSafeRelativeFilePath` + `canonicalizeSafePath`, and SHA-256 `readVerifiedBlob` preflight verification prior to any file mutation on `snap rewind`. + - 9-tier semantic triage classifying turns as `no_change`, `semantic_noop`, `internal_logic`, or `contract_change`, paired with CSR blast-radius test commands and tier policy gates (`canontra snap guard`). + - Documented in full in [HARNESS.md](HARNESS.md). + +- **CNTR\x07 Incremental Binary Slab Cache (`Canontra.Cache.SlabV7`)**: + - Extends 4KB CRC-32C protected slab pages with full 9-tier `FingerprintBundle` storage and compact per-file `FileGraphSummary` payloads for warm and single-file dirty whole-repository graph synthesis (`buildWholeRepoCallGraphFromSummaries`, `buildWholeRepoDataFlowFromSummaries`) without re-parsing untouched source files. + - Transparent read-upgrade compatibility for `CNTR\x06` and `CNTR\x05` caches (`readAnySlabCacheForV7`). + +#### Changed + +- **Single-Pass Pipeline Fusion & Algorithmic Speedups**: + - Added `CanonicalProgram` / `toCanonicalProgram` in `Canontra.Normalize.Normalize` and fused single-pass bundle hashing (`Canontra.Fingerprint.Bundle`), eliminating redundant multi-pass AST traversals and double parses in `computeManifest`. + - Replaced quadratic `Data.List.nub` hotspots in `WholeRepoGraph` and `TypeContract` with `Set`/`IntMap` structures, fixed lazy list concatenation in `DFG`, and upgraded `ChaseLevDeque` in `Canontra.Repository.Parallel` to mutable `MV.IOVector` circular buffers. + - Upgraded polyglot lexers/parsers (`Python`, `FastPython`, `JS`, `Go`, `Rust`, `Polyglot`, `FastScan`) toward ByteString/SIMD scanning, eliminating `T.snoc`/`T.head`/`T.tail` pathologies. + +- **Semantic & Type-Contract Accuracy Hardening**: + - **Structural Type Contracts ($F_T$)**: Fixed-width ABI scalar distinction, mutability qualifiers (`Mutability`), and ordered tuple contracts (`TypeTuple`). + - **Purity & IEEE-754 Guards (`Canontra.Normalize.Algebraic`)**: Added `containsFloatOperand` non-associativity guards for IEEE-754 floats and `isNonTrappingPureExpr` short-circuit/trapping guards. + - **Language-Specific $\alpha$-Scoping (`Canontra.Normalize.Alpha`)**: Hardened lexical scoping across Rust sequential `let` shadowing, Go `:=` short variable declarations, JavaScript `var` hoisting, and Python LEGB + walrus bindings (`canonicalizeAlphaModuleForLang`). + - **Lengauer-Tarjan Dominators & Whole-Repo Resolution**: Added `computeDominators` / `computeDominanceFrontiers` in `Canontra.Analysis.CFGCanonical`, improved Go directory package merging and TypeScript/JS barrel resolution in `WholeRepoGraph`, and updated repository Merkle root `F_R` to fold composite `F4`. + +- **Empirical Benchmarking & Documentation Sync**: + - Extended `bench/Bench.hs` with RQ18 (`SlabV7` + summary synthesis) and RQ19 (`canontra snap`), enforcing strict `NFData` (`nf`) across all 159 microbenchmarks. + - Replaced `Start-Process -Wait` with sub-millisecond `.NET ProcessStartInfo` timing in `researchBenchmarks/run_v0.4.0_benchmarks.ps1`; cold ingestion across all 15 repositories improved **4.07×** overall (`135.20 s` $\to$ `33.18 s`) and warm ingestion improved **9.07×** (`129.10 s` $\to$ `14.23 s`), up to **205.1× faster than CodeQL** (`ripgrep`) and **86.7× faster** on 994-file `prometheus`. + ## [0.3.0.0] - 2026-10-28 ### Deep Algebraic Equivalence, $\alpha$-Invariance & CSR-Native CIA 2.0 Milestone
CONTRIBUTING.md view
@@ -38,7 +38,7 @@ stack test --pedantic ``` -All 618+ automated tests should pass cleanly without any compiler warnings or test failures. +All 795 automated tests should pass cleanly without any compiler warnings or test failures. ## Core Architectural Constraints @@ -54,9 +54,12 @@ Ensure all binary serialization is strictly Big-Endian. Never rely on host CPU endianness or host filesystem path separators. Always normalize paths to forward slashes. 4. High-Performance Memory Hygiene: - Where possible, avoid allocating deeply nested pointer-heavy tree structures on the garbage-collected heap. Use Flat Linear Arenas and unboxed Vectors for AST representations, Unboxed Compressed Sparse Row (CSR) matrices for whole-repository graphs (`Canontra.Analysis.CSRGraph`), 64-byte aligned slab records for `CNTR\x06` caching, and SwissTables for symbol interning. + Where possible, avoid allocating deeply nested pointer-heavy tree structures on the garbage-collected heap. Use Flat Linear Arenas (`Canontra.IR.Arena`) and unboxed Vectors for AST representations, ByteString-native lexing (`flatparse` / `SIMDScan`), Unboxed Compressed Sparse Row (CSR) matrices for whole-repository graphs (`Canontra.Analysis.CSRGraph`), 4KB aligned `CNTR\x07` slab records (`Canontra.Cache.SlabV7`), mutable `MV.IOVector` Chase-Lev work-stealing buffers (`Canontra.Repository.Parallel`), and SwissTables for symbol interning. -5. Strict Compiler Flags: +5. Stateless AI Harness Hygiene (`Canontra.Harness.*` - Alpha): + All changes to `canontra snap` (`Store`, `SubVersion`, `Guard`) must preserve zero background daemons, zero IPC/network sockets, zero `.git` mutation, strict preflight SHA-256 verification and path containment prior to `snap rewind`, and auto-ignored `.canontra/` state. + +6. Strict Compiler Flags: The codebase compiles under `-Wall -Werror -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wpartial-fields -Wredundant-constraints`. Unused imports, missing export lists, or non-exhaustive pattern matches will fail the build. ## How to Add a New Transformation or Parser Feature @@ -73,7 +76,7 @@ Add both a soundness test (verifying that the transformation preserves F1, F2, F_T, and F4) and a sensitivity test (verifying that mutating the logic changes F1 and F4) in `test/Canontra/MetamorphicSpec.hs`. 4. Update Documentation: - Update `technicalSpecs.md` and `README.md` if your change introduces new flags or language features. + Update `README.md`, `HARNESS.md`, `CHANGELOG.md`, `SECURITY.md`, and `technicalSpecs.md` if your change introduces new flags, harness contracts, or language features. ## Submitting Pull Requests @@ -85,11 +88,14 @@ 2. Make your changes and commit with clear, descriptive commit messages: `git commit -m "Add TypeScript union type sorting in F_T type contract"` -3. Verify syntax and tests: +3. Verify syntax, linting, and tests: `stack test --pedantic` + `hlint --hint=.hlint.yaml src app bench test` `bash -n install.sh` `powershell -NoProfile -Command "Get-Command .\install.ps1 -Syntax"` + Every Pull Request automatically runs `.github/workflows/ci.yml` (strict `-Wall --pedantic` build & 795 tests), `.github/workflows/lint.yml` (`HLint` + `reviewdog` inline review, `shellcheck`, `actionlint`, `cabal check`), and `.github/workflows/security.yml` (zero-trust invariant gate, Gitleaks secret scan, OSV-Scanner dependency audit, and `zizmor` workflow audit). + 4. Push your branch to GitHub and open a Pull Request against `main`. 5. In your Pull Request description, explain what changed, why the change is necessary, and summarize the test results. @@ -97,4 +103,3 @@ ## Code of Conduct We are committed to providing a friendly, safe, and welcoming environment for everyone. Please be respectful, constructive, and collaborative in all discussions, issues, and pull requests. -
+ HARNESS.md view
@@ -0,0 +1,184 @@+# Canontra AI Harness Sub-Versioning (`canontra snap`)++> [!IMPORTANT]+> **Alpha Feature Notice (`schema_version: "0.1-alpha"`, `stability: "alpha"`)** +> `canontra snap` is an **experimental Alpha** subsystem introduced in Canontra `v0.4.0`. Command flags and JSON response fields (`0.1-alpha`) may evolve prior to `v1.0`. It is designed strictly as a **local, stateless CLI tool** for developer machines and local AI coding agent workspaces, never as a network service or background daemon.++## Overview++`canontra snap` gives AI coding agents, CLI wrappers, and automated refactoring loops sub-commit semantic checkpoints without touching `.git/index`, creating noisy WIP commits, or spawning background IPC daemons.++Each invocation runs synchronously as a short-lived CLI process, reads or updates local content-addressed state inside `.canontra/snaps/`, emits human-readable or `--json` output, and exits immediately with deterministic POSIX exit codes.++### Core Design Guarantees++* **Zero Background Daemons & Zero IPC**: Every `canontra snap` call starts, executes, and exits cleanly with no resident server, named pipe, or port binding.+* **Zero `.git` Mutation**: Never runs `git add`, `git commit`, `git stash`, or `git reset`. User git history and staging state remain completely untouched.+* **Auto-Excluded Storage**: `canontra snap init` automatically creates `.canontra/.gitignore` so local CAS blobs, manifests, and slab caches never appear as untracked git noise.+* **Air-Gapped & Pure Haskell**: Zero C-FFI bindings, zero network sockets, and zero telemetry.+* **9-Tier Semantic Triage**: Distinguishes formatting/comment churn (`semantic_noop`) from private implementation edits (`internal_logic`) and public signature/dependency/contract changes (`contract_change`).++## On-Disk Storage Layout++All harness state resides under `.canontra/snaps/` relative to the repository root (`--dir`):++```text+.canontra/+├── .gitignore # Auto-created ("*") to keep local state out of Git+├── cache.bin # Shared CNTR\x07 incremental slab + FileGraphSummary cache+└── snaps/+ ├── HEAD # Active snap_id (atomic swap on write)+ ├── ledger.jsonl # Append-only chronological turn metadata log+ ├── objects/+ │ └── <aa>/+ │ └── <sha256> # Deduplicated raw source blobs keyed by F0 SHA-256+ └── manifests/+ ├── snap_0.json # Immutable initial baseline snapshot+ └── snap_<ts>_<hash>.json+```++## Subcommand Reference++All subcommands accept `-d, --dir DIR` (repository root, defaults to `.`) and `--json` (machine-readable output), either before or after the subcommand name.++| Subcommand | Purpose | Key Options |+| :--- | :--- | :--- |+| `canontra snap init` | Create `.canontra/snaps/`, auto-create `.canontra/.gitignore`, and record baseline `snap_0` | `--dir DIR`, `--json` |+| `canontra snap mark` | Re-scan workspace via warm `CNTR\x07` cache, store new `F0` blobs, classify changes, advance `HEAD` | `-l/--label LABEL`, `-a/--agent AGENT`, `--skip-noop`, `--dir DIR`, `--json` |+| `canontra snap diff` | Compare `[FROM]` against `[TO]` (`HEAD` or `WORKTREE`) with symbol diffs and test slices | `[FROM]` (default `HEAD`), `[TO]` (default `WORKTREE`), `--compact`, `--dir DIR`, `--json` |+| `canontra snap guard` | Enforce semantic boundary policy against `--against` by forbidding specified tier mutations | `--against SNAP_ID`, `--forbid TIERS`, `--allow-paths GLOB` (repeatable), `--dir DIR`, `--json` |+| `canontra snap rewind` | Restore workspace (or specific files) to `SNAP_ID` after preflight path + SHA-256 verification | `SNAP_ID`, `-f/--file PATH` or `[FILES...]`, `--dry-run`, `--dir DIR`, `--json` |+| `canontra snap log` | Print reverse-chronological turn history from `ledger.jsonl` and current `HEAD` | `-n/--limit N` (default `20`), `--dir DIR`, `--json` |+| `canontra snap gc` | Prune older manifests (always preserving `snap_0` and `HEAD`) and sweep unreferenced CAS blobs | `--keep-last N` (default `50`), `--dir DIR`, `--json` |++### Semantic Classifications & Severity Levels++Every snapshot checkpoint and diff computes one of four turn-level classifications:++| Classification | Condition | Default File Severity Tiers Included |+| :--- | :--- | :--- |+| `no_change` | Identical `F0` source hashes across every tracked file | None |+| `semantic_noop` | `F0` changed, but `F1..F4` and `F_T` remained invariant (formatting, comments, docstrings, pure local $\alpha$-renaming) | `Level1_Trivia` |+| `internal_logic` | Body semantics (`F1`, `F_CG`, `F_CF`, `F_DF`, `F4`) changed without altering public APIs or dependencies | `Level2_Logic` |+| `contract_change` | Files added/deleted or public declarations (`F2`), dependencies (`F3`), or structural types (`F_T`) changed | `Level3_Contract` |++### Guard Tiers (`--forbid`)++Valid comma-separated tier tokens accepted by `canontra snap guard --forbid`:+`F0`, `F1`, `F2`, `F3`, `F_CG` (`FCG`), `F_CF` (`FCF`), `F_DF` (`FDF`), `F_T` (`FT`), `F4`.++### POSIX Exit Codes++* `0`: Success (or `snap guard` policy passed with zero violations).+* `1`: Policy violation detected by `snap guard`.+* `2`: Invalid CLI flags or missing required options.+* `4`: Unsafe snapshot ID (`..`, `/`, `\`), path-traversal violation, missing snapshot/blob, or SHA-256 verification failure.++## Agent Loop Workflow Example++A coding harness wrapping an LLM edit loop typically follows this sequence:++```bash+# 1. Establish baseline before an agent session begins (zero Git changes)+canontra snap init --json++# 2. Agent applies an edit, then checkpoints its turn+canontra snap mark --label "refactor-helper" --agent "coding-agent" --skip-noop --json++# 3. Verify no forbidden public contract tiers (F2, F3, F_T) broke during a refactor+canontra snap guard --against snap_0 --forbid F2,F3,F_T --allow-paths "tests/**" --json++# 4. If guard returns exit code 1 or tests fail, inspect compact diff or roll back safely+canontra snap diff snap_0 HEAD --compact --json+canontra snap rewind snap_0 --dry-run --json+canontra snap rewind snap_0 --json++# 5. Audit turn history or prune obsolete snapshots at session end+canontra snap log -n 10 --json+canontra snap gc --keep-last 10 --json+```++### Example JSON Payloads (`0.1-alpha`)++#### `canontra snap guard --against snap_0 --forbid F2,F3,F_T --json` (Exit Code `1`)++```json+{+ "against_snap_id": "snap_0",+ "allow_paths": [],+ "allowed_skipped": [],+ "elapsed_ms": 5.3398,+ "forbidden_tiers": ["F2", "F3", "F_T"],+ "passed": false,+ "schema_version": "0.1-alpha",+ "stability": "alpha",+ "violations": [+ {+ "mutated_tiers": ["F0", "F1", "F2", "F_CF", "F_DF", "F4"],+ "path": "app.py",+ "severity": "Level3_Contract",+ "status": "modified",+ "violated_tiers": ["F2"]+ }+ ]+}+```++#### `canontra snap diff snap_0 HEAD --compact --json`++```json+{+ "classification": "contract_change",+ "compact": true,+ "elapsed_ms": 11.4,+ "from_snap": "snap_0",+ "level1_trivia_count": 0,+ "level2_logic": [],+ "level3_contract": [+ {+ "invariant_tiers": ["F3", "F_CG", "F_T"],+ "mutated_tiers": ["F0", "F1", "F2", "F_CF", "F_DF", "F4"],+ "path": "app.py",+ "severity": "Level3_Contract",+ "status": "modified"+ }+ ],+ "recommended_tests": [],+ "schema_version": "0.1-alpha",+ "stability": "alpha",+ "symbol_changes": [+ {+ "action": "signature_modified",+ "detail": "Function signature altered",+ "file": "app.py",+ "symbol": "Function: compute"+ }+ ],+ "to_snap": "snap_20261130T181733297Z_3809be13"+}+```++## Performance Characteristics (Measured on `v0.4.0`)++Measured with `-O2` binaries on Windows 11 x86_64:++* **In-Memory Kernel Microbenchmarks (RQ19, `tasty-bench`)**:+ * `diffFileBundles` (single-file 9-tier comparison): **`733.1 ns`**+ * `computeFileDeltas` (1,000 tracked files, 1 dirty): **`1.73 ms`**+ * `classifySnapDeltas`: **`19.9 ns`**+ * `parseGuardTiers`: **`733.1 ns`**+ * `matchesGlob`: **`5.9 us`**+* **End-to-End Warm CLI `snap mark --skip-noop` Across 15 Real Repositories** (includes process startup + full directory walk + `CNTR\x07` cache check + whole-repo graph/manifest check):+ * Small/Medium Python & JS repos (`chalk`, `requests`, `marshmallow`, `bottle`, `jinja`, `click`, `gin`, `flask`): **`143.61 ms` – `440.52 ms`**+ * Large Rust/Go monorepos (`ripgrep` `477.16 ms`, `deno_core` `1,352.99 ms`, 994-file / 408k-LOC `prometheus` `3,978.55 ms`, `hugo` `5,022.56 ms`).++## Security & Rollback Safety++Every `snap rewind` operation runs a two-phase preflight before modifying any workspace file:++1. **Snapshot ID & Path Containment**: `isSafeSnapId` rejects traversal tokens (`..`, `/`, `\`) with POSIX exit code `4`. Every restored or removed path is validated with both `isSafeRelativeFilePath` and `canonicalizeSafePath` against the repository root.+2. **Cryptographic CAS Integrity**: Every source blob required for rollback is read from `.canontra/snaps/objects/` and SHA-256 verified against the manifest's `f0` digest (`readVerifiedBlob`) **before** any file on disk is written or deleted.+3. **Untracked User File Preservation**: Full snapshot rewinds only delete files that were tracked in the current `HEAD` manifest and absent from the target snapshot, never deleting unrelated untracked user files.+4. **Atomic Writes**: File writes use temporary `.tmp.<pid>` staging files swapped atomically with exponential backoff retry (`atomicSwapWithRetry_`).++For full threat model and reporting instructions, see [SECURITY.md](SECURITY.md).
README.md view
@@ -2,12 +2,14 @@ Deterministic Polyglot Program Identity and Semantic Graph Engine -Version: v0.3.0.0 (Release v0.3.0) +Version: v0.4.0.0 (Release v0.4.0) Open-source research project by [Jash Thakkar](https://github.com/JashT14) & SymtraceLabs Repository: <https://github.com/symtrace/canontra> +Documentation: <https://canontra-docs.vercel.app/> + ## What is Canontra? Imagine you are working on a team project. You open a source code file, add an inline comment to explain a tricky line of code, adjust indentation, or swap the order of two independent helper functions. @@ -30,15 +32,35 @@ Canontra works across five major programming languages: Python, JavaScript, TypeScript, Go, and Rust. -## What's New in v0.3.0 +## What's New in v0.4.0 +The v0.4.0 release delivers ultra-low-latency warm scanning, deepened multi-language semantic accuracy, and a stateless semantic sub-versioning engine (`canontra snap`, Alpha) designed for AI coding harnesses: + +* **Stateless AI Harness Semantic Sub-Versioning (`canontra snap`, Alpha)**: Zero-daemon, zero-`.git`-mutation checkpoints stored under `.canontra/snaps/` with content-addressed SHA-256 `F0` blobs, strict path-containment and SHA-256 preflight rollback, 9-tier delta classification (`no_change`, `semantic_noop`, `internal_logic`, `contract_change`), and CI/harness policy gates (`canontra snap guard`): + + ```bash + canontra snap init --json + canontra snap mark --label "refactor-step" --agent "harness" --skip-noop --json + canontra snap diff snap_0 HEAD --compact --json + canontra snap guard --against snap_0 --forbid F2,F3,F_T --json + canontra snap rewind snap_0 --dry-run --json + canontra snap log -n 10 --json + canontra snap gc --keep-last 25 --json + ``` + + > **Alpha Status Note**: `canontra snap` (`schema_version: "0.1-alpha"`) is currently in **Alpha**. CLI options and JSON output fields are local-only and experimental while agent harness integrations mature. See [HARNESS.md](HARNESS.md) for the complete specification, security model, and examples. +* **Ultra-Low-Latency Pipeline & `CNTR\x07` Incremental Binary Slab (`Canontra.Cache.SlabV7`)**: Direct UTF-8 ByteString lexing without intermediate `String`/`Text` unpacking, single-pass IR/normalization fusion, and paged `CNTR\x07` caches protected by IEEE 802.3 CRC32 verification. +* **Hardened Multi-Language Type Contracts ($F_T$) & Graph Precision**: Fixed-width scalar ABI distinction, mutability qualifiers, tuple/array shape preservation, float/boolean normalization guards, Lengauer-Tarjan CFG dominator canonicalization, and cross-file Go package and TypeScript/JS barrel module resolution. + +<!-- ## What's New in v0.3.0 + The v0.3.0 release deepens Canontra's semantic invariance across local variable renaming, algebraic laws, control-flow branch inversions, generic type contracts, and multi-file PR impact slicing: * **Scope-Aware Bound Lexical $\alpha$-Canonicalization (`Canontra.Normalize.Alpha`)**: Renaming local variables, loop counters, comprehension variables, lambda arguments, or exception bindings produces **100% bit-identical** $F_1$, $F_{DF}$, and $F_4$ fingerprints while keeping public function names and parameter contracts strictly sensitive in $F_2$. * **Commutative & Associative Algebraic Normal Form (`Canontra.Normalize.Algebraic`)**: Pure commutative expressions (`a + b` vs `b + a`, `x * y` vs `y * x`, `a == b` vs `b == a`), relational duals (`b > a` vs `a < b`, `b >= a` vs `a <= b`), and unordered set/dict literals (`{1, 2, 3}` vs `{3, 1, 2}`) normalize to identical canonical forms without reordering impure function calls. * **CFG Dominator-Tree & Reverse Post-Order Canonicalization (`Canontra.Analysis.CFGCanonical`)**: Branch inversions (`if not cond: B else: A` vs `if cond: A else: B`), early-exit guard clauses, and unreachable statements after `return`/`raise` normalize to identical $F_{CF}$ and $F_1$ digests. * **Deepened Structural Type Contract ($F_T$) Lattice**: Nested union/intersection flattening (`(A | B) | C` == `C | (B | A)`), positional de Bruijn generic type parameter normalization (`interface Store<K, V>` == `interface Store<Key, Val>`), and structural record field sorting across Python, TypeScript, Go, and Rust. -* **CSR-Native Multi-File PR Batch Change Impact Analysis (`canontra impact --pr-base <ref>`)**: Computes joint backward reachability cones over unboxed CSR graphs in under 50 microseconds and emits ready-to-run test commands for `pytest`, `jest`, `go test`, and `cargo test`. +* **CSR-Native Multi-File PR Batch Change Impact Analysis (`canontra impact --pr-base <ref>`)**: Computes joint backward reachability cones over unboxed CSR graphs in under 50 microseconds and emits ready-to-run test commands for `pytest`, `jest`, `go test`, and `cargo test`. --> <!-- ## What's New in v0.2.0 @@ -313,7 +335,7 @@ ### 7. Manage the Local Build Cache (`canontra cache`) -Canontra includes an ultra-fast local binary cache (`.canontra/cache.bin`) that remembers file fingerprints in compact, cache-aligned records. It delivers sub-microsecond warm lookups (< 500 ns per file) and features isolated 4KB page CRC32 checksums for automatic self-healing against corrupted files: +Canontra includes a `CNTR\x07` incremental binary slab cache (`.canontra/cache.bin`) persisting file fingerprints and per-file `FileGraphSummary` metadata in 4KB CRC32-protected pages for fast warm lookups and incremental graph synthesis: View cache statistics and hit rates: @@ -350,10 +372,27 @@ canontra completions powershell >> $PROFILE ``` +### 9. Stateless AI Harness Sub-Versioning (`canontra snap` - Alpha) + +> **Alpha Notice**: `canontra snap` (`schema_version: "0.1-alpha"`, `stability: "alpha"`) is an experimental local sub-versioning engine for AI coding harnesses; see [HARNESS.md](HARNESS.md) for full details. + +Capture turn-by-turn semantic checkpoints under `.canontra/snaps/`, verify tier invariants with `snap guard`, inspect compact symbol deltas with `snap diff`, and safely rewind via preflight SHA-256 verification without creating Git WIP commits or background daemons: + +```bash +canontra snap init --json +canontra snap mark --label "step-1" --agent "harness" --skip-noop --json +canontra snap guard --against snap_0 --forbid F2,F3,F_T --json +canontra snap rewind snap_0 --dry-run --json +``` + ## Where is Canontra Used? Canontra is designed for modern development workflows and infrastructure: +### AI Coding Agent Harnesses (Alpha) + +AI coding tools and local refactoring harnesses use `canontra snap` to checkpoint workspace edits between turns, detect `semantic_noop` formatting churn, reject unintended public API mutations with `snap guard`, and execute preflight-verified rollbacks without touching `.git`. See [HARNESS.md](HARNESS.md). + ### Smart CI/CD Build Caches In continuous integration pipelines, running test suites and building packages takes substantial time and cloud compute budget. By replacing raw byte hashes with Canontra semantic fingerprints, CI pipelines can safely skip rebuilding and testing packages when developers only update documentation, comments, formatting, or internal variable names. @@ -374,7 +413,9 @@ Explore the rest of the documentation for full technical details: +* [Online Documentation](https://canontra-docs.vercel.app/): Official Canontra documentation website (quickstart, CLI reference, language conformance, guides, and benchmarks). * [CHANGELOG.md](CHANGELOG.md): Complete release history, version notes, and PVP conformance. +* [HARNESS.md](HARNESS.md): Alpha specification and usage guide for `canontra snap` stateless AI harness sub-versioning. * [benchmarkReport.md](benchmarkReport.md): Empirical benchmark report, multi-tool comparative evaluation, and whole-repository graph synthesis evaluation across 15 production repositories. * [BENCHMARKS.md](BENCHMARKS.md): Performance benchmarks, latency measurements, and throughput statistics across supported languages. * [REAL_WORLD_BENCHMARKS.md](REAL_WORLD_BENCHMARKS.md): Empirical reproduction runbook and evaluation methodology across real-world open-source repositories.
REAL_WORLD_BENCHMARKS.md view
@@ -1,6 +1,6 @@ # Canontra Real-World Benchmark Protocol and Execution Instructions -Version: v0.3.0.0 (Release v0.3.0) Deep Algebraic Equivalence & CSR-Native CIA 2.0 Architecture +Version: v0.4.0.0 (Release v0.4.0) Ultra-Low-Latency Engine & `canontra snap` Harness Author: Jash Thakkar & SymtraceLabs Engineering Team Status: Benchmark Execution Protocol @@ -120,17 +120,23 @@ ```bash # Build optimized production binary -stack build --copy-bins --local-bin-path ./dist-bin --ghc-options="-O2" +stack install --local-bin-path ./dist-bin --ghc-options="-O2" --pedantic -# Verify executable is functional and reports version 0.3.0 +# Verify executable is functional and reports version 0.4.0 ./dist-bin/canontra version ``` On Windows PowerShell: ```powershell -stack build --copy-bins --local-bin-path .\dist-bin --ghc-options="-O2" +stack install --local-bin-path .\dist-bin --ghc-options="-O2" --pedantic .\dist-bin\canontra.exe version +``` + +Or run the automated `v0.4.0` 15-repository runner (uses sub-millisecond `.NET ProcessStartInfo` timing and cleans `.canontra/` artifacts after each repo): + +```powershell +powershell -ExecutionPolicy Bypass -File researchBenchmarks\run_v0.4.0_benchmarks.ps1 ``` ### Step 2: Workspace Staging Preparation
SECURITY.md view
@@ -1,6 +1,6 @@ # Security Policy and Architecture -Version: v0.3.0.0 (Release v0.3.0)+Version: v0.4.0.0 (Release v0.4.0) Target: Canontra Production Release Organization: SymtraceLabs Security Team @@ -32,14 +32,14 @@ * Bounded Graph Traversal: Dominator tree computations and data-flow reachability passes enforce finite iteration bounds, guaranteeing termination on arbitrary control flow graphs. * Bounded CSR Batch Reachability: Multi-source reachability BFS queues allocate memory strictly bounded by the total number of repository symbols, preventing runaway allocations on cyclic or adversarial graph structures. -### 4. Memory Safety and Binary Slab Cache Security (CNTR v6)+### 4. Memory Safety and Binary Slab Cache Security (`CNTR\x07` / `SlabV7`) * Pure Haskell Runtime: Built on GHC 9.6.6 with pure functional semantics. The core library strictly avoids unmanaged pointer manipulation. * Flat Linear Arena & Unboxed CSR Protection: Unboxed vector representations prevent heap-allocated pointer corruption and enforce strict array boundary checking.-* 4KB Paged Radix Slab Cache Security (`CNTR\x06`):- * Every 4,096-byte slab page in `.canontra/cache.bin` is protected by an IEEE 802.3 CRC-32C checksum.- * Corrupted cache pages are discarded and recomputed in isolation (`salvageSlabCacheFile`) without crashing the engine.- * Cache writes are staged to a private temporary file and finalized using `atomicSwapWithRetry` with exponential backoff and jitter, preventing Windows Defender / SearchIndexer lock failures and torn writes during sudden termination.+* 4KB Paged Radix Slab Cache Security (`CNTR\x07`, `Canontra.Cache.SlabV7`):+ * Every 4,096-byte slab page in `.canontra/cache.bin` is protected by an IEEE 802.3 CRC-32C checksum alongside per-file `FileGraphSummary` metadata.+ * Corrupted cache pages are discarded and recomputed in isolation (`decodeSlabV7Resilient` / `readSlabV7FileResilient`) without crashing the engine.+ * Cache writes are staged to a private temporary file and finalized using `atomicSwapWithRetry` / `atomicSwapWithRetry_` with exponential backoff and jitter, preventing Windows Defender / SearchIndexer lock failures and torn writes during sudden termination. ### 5. Safe Git and CI Change Impact Analysis Integration @@ -49,6 +49,16 @@ * No Shell Execution: Arguments are passed directly to OS process spawning routines without invoking intermediate shells (`sh`, `bash`, `cmd.exe`, or `powershell.exe`), eliminating shell injection vectors. * Path Sanitization: All file paths reported by `git diff --name-only` are validated via `canonicalizeSafePath` before being processed by the CSR reachability engine. * Read-Only Access: Canontra only executes read-only inspection commands. It never modifies, commits, or alters repository git state.++### 6. AI Harness Sub-Versioning (`canontra snap` - Alpha) Security & Rollback Guarantees++The stateless `canontra snap` subsystem (`Canontra.Harness.Store`, `Canontra.Harness.SubVersion`, `Canontra.Harness.Guard`) adds content-addressed checkpoints under `.canontra/snaps/` with strict local confinement:++* Zero `.git` Mutation & Auto-Exclusion: `.canontra/snaps/` stores local CAS blobs (`objects/`), manifests (`manifests/`), `HEAD`, and `ledger.jsonl` without running `git` write commands or altering `.git/`. `ensureSnapStore` automatically writes `.canontra/.gitignore` so harness artifacts never leak into commits.+* Identifier & Path Containment Validation: `isSafeSnapId` rejects `..`, slashes, backslashes, leading dots, or malformed IDs (exiting with POSIX code `4`). `snapRewind` validates every path with both `isSafeRelativeFilePath` and `canonicalizeSafePath` against the workspace root (and existing parent directories) before touching disk.+* Preflight SHA-256 Blob Verification: Before `snap rewind` modifies or removes any workspace file, `preflightRewind` reads and SHA-256 verifies every target CAS object via `readVerifiedBlob`. Tampered or truncated objects abort cleanly with zero partial filesystem mutation.+* Atomic Swap & Untracked File Preservation: Restored files are staged in temporary `.tmp.<pid>` files and swapped atomically via `atomicSwapWithRetry_`. Unrelated untracked workspace files are never deleted on rollback (only tracked files added after the target snapshot relative to `HEAD`).+* Zero Daemons & Zero Telemetry: All harness operations run purely synchronously per CLI invocation with zero background processes, zero IPC sockets, and zero network egress. ## Reporting a Security Vulnerability
bench/Bench.hs view
@@ -3,18 +3,13 @@ {- | Module : Main-Description : Research benchmark suite measuring latency, polyglot throughput, Direct-to-IR parsers, SymbolTable interning, and Outline mode (v0.0.5-alpha).+Description : Empirical research benchmark suite for Canontra v0.4.0 (RQ1-RQ19). -This suite empirically evaluates canontra v0.0.5-alpha across 9 core Research Questions (RQs):-- RQ1: Execution Latency & Algorithmic Scalability across Pipeline Stages & Program Scales-- RQ2: Polyglot Ingestion & Pipeline Throughput (Python, TS/JS, Go, Rust)-- RQ3: Mutation Invariance Processing (Whitespace, Comments, Body Edits)-- RQ4: Multi-File Polyglot Repository Aggregation Scaling (FR Tier up to 1,000 files)-- RQ5: Comparative Baseline Overhead & Throughput Limits-- RQ6: High-Performance Optimizations (StreamingHash, CompactGraph, Fused Normalizer, MerkleCache)-- RQ7: v0.0.5-alpha FlatFusion Direct-to-IR Parser Throughput & Sub-ms Verification-- RQ8: SymbolTable Interning & Zero-Allocation Symbol Resolution-- RQ9: Selective Outline Mode Speedup for F2 (Declarations) & F3 (Dependencies)+This suite empirically evaluates canontra v0.4.0 across 19 Research Questions (RQs),+from Core Pipeline Stages, Polyglot ByteString/SIMD Parsers, SwissTable Interning,+Fused Streaming, Unboxed CSR Graphs, CNTR\x06 & CNTR\x07 Slab Caches, Bound+Alpha-Canonicalization & CFG RPO, Algebraic Equivalence, to Stateless AI Harness+Semantic Sub-Versioning (@canontra snap@). -} module Main (main) where @@ -23,6 +18,7 @@ import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Lazy as LBS import Data.List (foldl')+import qualified Data.Map.Strict as Map import qualified Data.Text as T import qualified Data.Text.Encoding as TE import GHC.IO.Encoding (setFileSystemEncoding, setForeignEncoding, setLocaleEncoding, utf8)@@ -53,13 +49,14 @@ import Canontra.IR.Arena (fusedHashLinearAST, programToLinearAST) import Canontra.Normalize.Fused (fusedNormalizeProgram) import Canontra.Normalize.Normalize (normalizeProgram)-import Canontra.Parser.FastPython (parseFastPythonByteString, parseFastPythonToArena)-import Canontra.Parser.Go (parseGoSource)+import Canontra.Parser.FastPython (parseFastPythonByteString, parseFastPythonSource, parseFastPythonToArena)+import Canontra.Parser.Go (parseGoByteString, parseGoSource) import Canontra.Parser.Ingest (ingestOutlineSource, ingestSource)-import Canontra.Parser.JS (parseJSSource)+import Canontra.Parser.JS (parseJSByteString, parseJSSource) import Canontra.Parser.Outline (computeF2Outline, computeF3Outline, parseOutlineGo, parseOutlineJS, parseOutlinePython, parseOutlineRust)+import Canontra.Parser.Polyglot (parsePolyglotByteString) import Canontra.Parser.Python (parsePythonSource)-import Canontra.Parser.Rust (parseRustSource)+import Canontra.Parser.Rust (parseRustByteString, parseRustSource) import Canontra.Parser.SwissTable (emptySwissTable, swissInternBS, swissLookupBS, swissResolveId) import Canontra.Parser.SymbolTable (SymbolId (..), emptySymbolTable, internManyBS, internSymbolBS, preloadPolyglotKeywords, resolveSymbolBS) import Canontra.Repository.MerkleDAG (buildMerkleDAG, diffMerkleDAG, merkleDAGRootHash)@@ -70,13 +67,27 @@ import Canontra.Analysis.TypeContract (extractTypeContracts) import Canontra.Normalize.Algebraic (normalizeAlgebraicProgram) import Canontra.Normalize.Alpha (canonicalizeAlphaProgram)-import Canontra.Analysis.WholeRepoGraph (buildCSRCallGraph, buildCSRDataFlow, buildWholeRepoCallGraph, buildWholeRepoDataFlow, incrementalUpdateWholeRepoGraphs, toCSRCallGraph)+import Canontra.Analysis.WholeRepoGraph+ ( buildCSRCallGraph+ , buildCSRDataFlow+ , buildWholeRepoCallGraph+ , buildWholeRepoCallGraphFromSummaries+ , buildWholeRepoDataFlow+ , buildWholeRepoDataFlowFromSummaries+ , extractFileGraphSummary+ , incrementalUpdateWholeRepoGraphs+ , toCSRCallGraph+ ) import Canontra.Cache.PagedCache (decodeBinaryCacheV5, encodeBinaryCacheV5, lookupBinaryCacheV5) import Canontra.Cache.SlabV6 (decodeCSRGraph, decodeSlabV6Binary, encodeCSRGraph, encodeSlabV6Binary, lookupSlabBinaryBS)+import Canontra.Cache.SlabV7 (SlabV7Entry (..), decodeSlabV7Binary, encodeSlabV7Binary, lookupSlabV7BinaryBS) import Canontra.Canonical.SIMDScan (fastCanonicalizeSIMD, isPureAsciiUnixSIMD, scanSourceSIMD) import Canontra.Fingerprint.TypeContract (computeFT) import Canontra.Fingerprint.WholeRepoCallGraph (computeFWCG) import Canontra.Fingerprint.WholeRepoDataFlow (computeFWDF)+import Canontra.Harness.Guard (matchesGlob, parseGuardTiers)+import Canontra.Harness.Store (SnapFileRecord (..))+import Canontra.Harness.SubVersion (classifySnapDeltas, computeFileDeltas, diffFileBundles) import Canontra.IR.Expression (Op (..)) import Canontra.Repository.Parallel (newChaseLevDeque, parMapChunks, parProcessWorkStealing, popBottom, pushBottom, stealBatchTop) import Canontra.Repository.Repository (computeRepositoryFingerprint)@@ -271,146 +282,170 @@ slabEntries1000 = [ (fePath e, FileMetadata (fePath e) 1024 1700000000, feFingerprints e) | e <- repo1000 ] slabV6Bin = encodeSlabV6Binary slabEntries1000 Nothing+ summaries10 = [extractFileGraphSummary p pr | (p, pr) <- modules10]+ slabV7Entries10 =+ [ SlabV7Entry (FileMetadata p 1024 1700000000) (feFingerprints (head repo10)) (Just s)+ | ((p, _), s) <- zip modules10 summaries10+ ]+ slabV7Bin10 = encodeSlabV7Binary slabV7Entries10 Nothing (wcg10Graph, _) = buildCSRCallGraph modules10 (wdf10Graph, _) = buildCSRDataFlow modules10 csrPair10 = toCSRCallGraph wcg10Graph csrEncodedBS = LBS.toStrict (BB.toLazyByteString (encodeCSRGraph csrGraph100)) + snapMap1000 = Map.fromList+ [ (fePath e, SnapFileRecord (fePath e) (unFingerprint (f0Source (feFingerprints e))) 1024 (feFingerprints e))+ | e <- repo1000+ ]+ snapMap1000Mod = Map.insert "src/module_500.py"+ (SnapFileRecord "src/module_500.py" "modified_f0" 1024 dummyBundleM)+ snapMap1000+ snapDirtyDeltas = computeFileDeltas snapMap1000 snapMap1000Mod+ defaultMain [ bgroup "RQ1: Pipeline Latency across Scales" [ bgroup "1. AST Parsing"- [ bench "Micro (~25 LOC)" $ whnf (parsePythonSource "micro.py") microSrc- , bench "Small (~85 LOC)" $ whnf (parsePythonSource "small.py") smallSrc- , bench "Medium (~405 LOC)" $ whnf (parsePythonSource "med.py") medSrc- , bench "Large (~1605 LOC)" $ whnf (parsePythonSource "large.py") largeSrc- , bench "XL (~4005 LOC)" $ whnf (parsePythonSource "xl.py") xlSrc+ [ bench "Micro (~25 LOC)" $ nf (parsePythonSource "micro.py") microSrc+ , bench "Small (~85 LOC)" $ nf (parsePythonSource "small.py") smallSrc+ , bench "Medium (~405 LOC)" $ nf (parsePythonSource "med.py") medSrc+ , bench "Large (~1605 LOC)" $ nf (parsePythonSource "large.py") largeSrc+ , bench "XL (~4005 LOC)" $ nf (parsePythonSource "xl.py") xlSrc ] , bgroup "2. AST Normalization & Serialization"- [ bench "Micro (~25 LOC)" $ whnf (canonicalizeProgram . normalizeProgram) microProg- , bench "Small (~85 LOC)" $ whnf (canonicalizeProgram . normalizeProgram) smallProg- , bench "Medium (~405 LOC)" $ whnf (canonicalizeProgram . normalizeProgram) medProg- , bench "Large (~1605 LOC)" $ whnf (canonicalizeProgram . normalizeProgram) largeProg- , bench "XL (~4005 LOC)" $ whnf (canonicalizeProgram . normalizeProgram) xlProg+ [ bench "Micro (~25 LOC)" $ nf (canonicalizeProgram . normalizeProgram) microProg+ , bench "Small (~85 LOC)" $ nf (canonicalizeProgram . normalizeProgram) smallProg+ , bench "Medium (~405 LOC)" $ nf (canonicalizeProgram . normalizeProgram) medProg+ , bench "Large (~1605 LOC)" $ nf (canonicalizeProgram . normalizeProgram) largeProg+ , bench "XL (~4005 LOC)" $ nf (canonicalizeProgram . normalizeProgram) xlProg ] , bgroup "3. Semantic Graph Analysis"- [ bench "Scope Analysis (XL)" $ whnf analyzeProgramScope xlProg- , bench "Call Graph Extraction (XL)" $ whnf buildCallGraph xlProg- , bench "Control-Flow Graph (CFG) (XL)"$ whnf buildCFGs xlProg- , bench "Data-Flow Graph (DFG) (XL)" $ whnf buildDFGs xlProg+ [ bench "Scope Analysis (XL)" $ nf analyzeProgramScope xlProg+ , bench "Call Graph Extraction (XL)" $ nf buildCallGraph xlProg+ , bench "Control-Flow Graph (CFG) (XL)"$ nf buildCFGs xlProg+ , bench "Data-Flow Graph (DFG) (XL)" $ nf buildDFGs xlProg ] , bgroup "4. Cryptographic Hashing"- [ bench "F0 Raw Bytes Hash (XL)" $ whnf computeF0 xlBytes- , bench "F1 Structural Hash (XL)" $ whnf computeF1 xlProg- , bench "F2 Declaration Hash (XL)" $ whnf computeF2 xlProg- , bench "F3 Dependency Hash (XL)" $ whnf computeF3 xlProg- , bench "F_CG Call Graph Hash (XL)" $ whnf computeFCG xlProg- , bench "F_CF Control-Flow Hash (XL)"$ whnf computeFCF xlProg- , bench "F_DF Data-Flow Hash (XL)" $ whnf computeFDF xlProg- , bench "F4 Composite Hash" $ whnf (\fp -> computeF4 fp fp fp fp fp fp fp) (Fingerprint "test")+ [ bench "F0 Raw Bytes Hash (XL)" $ nf computeF0 xlBytes+ , bench "F1 Structural Hash (XL)" $ nf computeF1 xlProg+ , bench "F2 Declaration Hash (XL)" $ nf computeF2 xlProg+ , bench "F3 Dependency Hash (XL)" $ nf computeF3 xlProg+ , bench "F_CG Call Graph Hash (XL)" $ nf computeFCG xlProg+ , bench "F_CF Control-Flow Hash (XL)"$ nf computeFCF xlProg+ , bench "F_DF Data-Flow Hash (XL)" $ nf computeFDF xlProg+ , bench "F4 Composite Hash" $ nf (\fp -> computeF4 fp fp fp fp fp fp fp) (Fingerprint "test") ] , bgroup "5. Full 8-Tier Pipeline"- [ bench "Micro (~25 LOC)" $ whnf (\s -> computeBundle "micro.py" microBytes s) microSrc- , bench "Small (~85 LOC)" $ whnf (\s -> computeBundle "small.py" smallBytes s) smallSrc- , bench "Medium (~405 LOC)" $ whnf (\s -> computeBundle "med.py" medBytes s) medSrc- , bench "Large (~1605 LOC)" $ whnf (\s -> computeBundle "large.py" largeBytes s) largeSrc- , bench "XL (~4005 LOC)" $ whnf (\s -> computeBundle "xl.py" xlBytes s) xlSrc+ [ bench "Micro (~25 LOC)" $ nf (\s -> computeBundle "micro.py" microBytes s) microSrc+ , bench "Small (~85 LOC)" $ nf (\s -> computeBundle "small.py" smallBytes s) smallSrc+ , bench "Medium (~405 LOC)" $ nf (\s -> computeBundle "med.py" medBytes s) medSrc+ , bench "Large (~1605 LOC)" $ nf (\s -> computeBundle "large.py" largeBytes s) largeSrc+ , bench "XL (~4005 LOC)" $ nf (\s -> computeBundle "xl.py" xlBytes s) xlSrc ] ] , bgroup "RQ2: Polyglot Ingestion Pipelines"- [ bench "Python Pipeline (~100 LOC)" $ whnf (\s -> computeBundle "sample.py" smallBytes s) smallSrc- , bench "TypeScript Pipeline (~100 LOC)" $ whnf (\s -> computeBundle "sample.ts" tsSmallBytes s) tsSmall- , bench "Go Pipeline (~100 LOC)" $ whnf (\s -> computeBundle "sample.go" goSmallBytes s) goSmall- , bench "Rust Pipeline (~100 LOC)" $ whnf (\s -> computeBundle "sample.rs" rsSmallBytes s) rsSmall+ [ bench "Python Pipeline (~100 LOC)" $ nf (\s -> computeBundle "sample.py" smallBytes s) smallSrc+ , bench "TypeScript Pipeline (~100 LOC)" $ nf (\s -> computeBundle "sample.ts" tsSmallBytes s) tsSmall+ , bench "Go Pipeline (~100 LOC)" $ nf (\s -> computeBundle "sample.go" goSmallBytes s) goSmall+ , bench "Rust Pipeline (~100 LOC)" $ nf (\s -> computeBundle "sample.rs" rsSmallBytes s) rsSmall ] , bgroup "RQ3: Mutation Invariance Processing"- [ bench "Base Code Evaluation" $ whnf (computeBundleFromSource "base.py") baseCode- , bench "M1: Whitespace Jitter" $ whnf (computeBundleFromSource "m1.py") mutWhitespace- , bench "M2: Comment Churn" $ whnf (computeBundleFromSource "m2.py") mutComments- , bench "M3: Internal Body Edit" $ whnf (computeBundleFromSource "m3.py") mutBody+ [ bench "Base Code Evaluation" $ nf (computeBundleFromSource "base.py") baseCode+ , bench "M1: Whitespace Jitter" $ nf (computeBundleFromSource "m1.py") mutWhitespace+ , bench "M2: Comment Churn" $ nf (computeBundleFromSource "m2.py") mutComments+ , bench "M3: Internal Body Edit" $ nf (computeBundleFromSource "m3.py") mutBody ] , bgroup "RQ4: Repository Aggregation Scaling (FR)"- [ bench "10 Files" $ whnf computeRepositoryFingerprint repo10- , bench "50 Files" $ whnf computeRepositoryFingerprint repo50- , bench "200 Files" $ whnf computeRepositoryFingerprint repo200- , bench "500 Files" $ whnf computeRepositoryFingerprint repo500- , bench "1,000 Files" $ whnf computeRepositoryFingerprint repo1000+ [ bench "10 Files" $ nf computeRepositoryFingerprint repo10+ , bench "50 Files" $ nf computeRepositoryFingerprint repo50+ , bench "200 Files" $ nf computeRepositoryFingerprint repo200+ , bench "500 Files" $ nf computeRepositoryFingerprint repo500+ , bench "1,000 Files" $ nf computeRepositoryFingerprint repo1000 ] , bgroup "RQ5: Comparative Baseline Overhead"- [ bench "Raw SHA-256 Hashing (XL)" $ whnf computeF0 xlBytes- , bench "AST Parsing Only (XL)" $ whnf (parsePythonSource "xl.py") xlSrc- , bench "Canontra Full 8-Tier (XL)" $ whnf (\s -> computeBundle "xl.py" xlBytes s) xlSrc+ [ bench "Raw SHA-256 Hashing (XL)" $ nf computeF0 xlBytes+ , bench "AST Parsing Only (XL)" $ nf (parsePythonSource "xl.py") xlSrc+ , bench "Canontra Full 8-Tier (XL)" $ nf (\s -> computeBundle "xl.py" xlBytes s) xlSrc ] , bgroup "RQ6: High-Performance Optimizations (v0.0.4-alpha)"- [ bench "StreamingHash (XL Builder)" $ whnf hashBuilderDirect (BB.byteString xlBytes)- , bench "Standard hashBytes (XL)" $ whnf hashBytes xlBytes- , bench "Fused Normalization (XL)" $ whnf fusedNormalizeProgram xlProg- , bench "Standard Normalization (XL)" $ whnf normalizeProgram xlProg- , bench "CompactCFG Conversion (XL)" $ whnf (map fromControlFlowGraph . buildCFGs) xlProg- , bench "CompactDFG Conversion (XL)" $ whnf (map fromDataFlowGraph . buildDFGs) xlProg- , bench "MerkleCache Lookup (Hit)" $ whnf (lookupCache "src/module_1.py" sampleMeta) populatedCache- , bench "Zero-Copy Ingestion (XL)" $ whnf (\b -> ingestSource "xl.py" b xlSrc) xlBytes+ [ bench "StreamingHash (XL Builder)" $ nf hashBuilderDirect (BB.byteString xlBytes)+ , bench "Standard hashBytes (XL)" $ nf hashBytes xlBytes+ , bench "Fused Normalization (XL)" $ nf fusedNormalizeProgram xlProg+ , bench "Standard Normalization (XL)" $ nf normalizeProgram xlProg+ , bench "CompactCFG Conversion (XL)" $ nf (map fromControlFlowGraph . buildCFGs) xlProg+ , bench "CompactDFG Conversion (XL)" $ nf (map fromDataFlowGraph . buildDFGs) xlProg+ , bench "MerkleCache Lookup (Hit)" $ nf (lookupCache "src/module_1.py" sampleMeta) populatedCache+ , bench "Zero-Copy Ingestion (XL)" $ nf (\b -> ingestSource "xl.py" b xlSrc) xlBytes ] , bgroup "RQ7: v0.0.5-alpha FlatFusion Direct-to-IR Parser Throughput" [ bgroup "Python Parser"- [ bench "Small (~85 LOC)" $ whnf (parsePythonSource "small.py") smallSrc- , bench "Med (~405 LOC)" $ whnf (parsePythonSource "med.py") medSrc- , bench "Large (~1605 LOC)" $ whnf (parsePythonSource "large.py") largeSrc+ [ bench "Small (~85 LOC)" $ nf (parsePythonSource "small.py") smallSrc+ , bench "Med (~405 LOC)" $ nf (parsePythonSource "med.py") medSrc+ , bench "Large (~1605 LOC)" $ nf (parsePythonSource "large.py") largeSrc ] , bgroup "TypeScript Parser"- [ bench "Small (~85 LOC)" $ whnf (parseJSSource "small.ts") tsSmall- , bench "Med (~405 LOC)" $ whnf (parseJSSource "med.ts") tsMed- , bench "Large (~1605 LOC)" $ whnf (parseJSSource "large.ts") tsLarge+ [ bench "Small (~85 LOC)" $ nf (parseJSSource "small.ts") tsSmall+ , bench "Med (~405 LOC)" $ nf (parseJSSource "med.ts") tsMed+ , bench "Large (~1605 LOC)" $ nf (parseJSSource "large.ts") tsLarge ] , bgroup "Go Parser"- [ bench "Small (~85 LOC)" $ whnf (parseGoSource "small.go") goSmall- , bench "Med (~405 LOC)" $ whnf (parseGoSource "med.go") goMed- , bench "Large (~1605 LOC)" $ whnf (parseGoSource "large.go") goLarge+ [ bench "Small (~85 LOC)" $ nf (parseGoSource "small.go") goSmall+ , bench "Med (~405 LOC)" $ nf (parseGoSource "med.go") goMed+ , bench "Large (~1605 LOC)" $ nf (parseGoSource "large.go") goLarge ] , bgroup "Rust Parser"- [ bench "Small (~85 LOC)" $ whnf (parseRustSource "small.rs") rsSmall- , bench "Med (~405 LOC)" $ whnf (parseRustSource "med.rs") rsMed- , bench "Large (~1605 LOC)" $ whnf (parseRustSource "large.rs") rsLarge+ [ bench "Small (~85 LOC)" $ nf (parseRustSource "small.rs") rsSmall+ , bench "Small BS (~85 LOC)"$ nf (parseRustByteString "small.rs") rsSmallBytes+ , bench "Med (~405 LOC)" $ nf (parseRustSource "med.rs") rsMed+ , bench "Large (~1605 LOC)" $ nf (parseRustSource "large.rs") rsLarge ]+ , bgroup "ByteString SIMD Parsers (v0.4.0)"+ [ bench "FastPython BS (Small)" $ nf (parseFastPythonByteString "small.py") smallBytes+ , bench "FastPython Src (XL)" $ nf (parseFastPythonSource "xl.py") xlSrc+ , bench "JS/TS BS (Small)" $ nf (parseJSByteString "small.ts") tsSmallBytes+ , bench "Go BS (Small)" $ nf (parseGoByteString "small.go") goSmallBytes+ , bench "Polyglot BS (Py)" $ nf (parsePolyglotByteString "small.py") smallBytes+ , bench "Polyglot BS (TS)" $ nf (parsePolyglotByteString "small.ts") tsSmallBytes+ ] ] , bgroup "RQ8: SymbolTable Interning & Resolution"- [ bench "Batch Intern 1,000 Identifiers" $ whnf (internManyBS sampleIdentifiers) emptySymbolTable- , bench "Single Symbol Intern" $ whnf (internSymbolBS "identifier_example") benchSymTable- , bench "SymbolId Lookup (Hit)" $ whnf (`resolveSymbolBS` benchSymTable) (SymbolId 42)- , bench "Preloaded Polyglot Lookup" $ whnf (`resolveSymbolBS` preloadPolyglotKeywords) (SymbolId 5)+ [ bench "Batch Intern 1,000 Identifiers" $ nf (internManyBS sampleIdentifiers) emptySymbolTable+ , bench "Single Symbol Intern" $ nf (internSymbolBS "identifier_example") benchSymTable+ , bench "SymbolId Lookup (Hit)" $ nf (`resolveSymbolBS` benchSymTable) (SymbolId 42)+ , bench "Preloaded Polyglot Lookup" $ nf (`resolveSymbolBS` preloadPolyglotKeywords) (SymbolId 5) ] , bgroup "RQ9: Selective Outline Mode Speedup for F2 / F3" [ bgroup "Python Outline"- [ bench "Full AST Parse (Large)" $ whnf (parsePythonSource "large.py") largeSrc- , bench "Outline Parse (Large)" $ whnf (parseOutlinePython "large.py") largeSrc- , bench "F2 Full AST Compute" $ whnf computeF2 largeProg- , bench "F2 Outline Mode Compute" $ whnf (\s -> case parseOutlinePython "large.py" s of Right o -> computeF2Outline o; Left _ -> Fingerprint "") largeSrc- , bench "F3 Full AST Compute" $ whnf computeF3 largeProg- , bench "F3 Outline Mode Compute" $ whnf (\s -> case parseOutlinePython "large.py" s of Right o -> computeF3Outline o; Left _ -> Fingerprint "") largeSrc+ [ bench "Full AST Parse (Large)" $ nf (parsePythonSource "large.py") largeSrc+ , bench "Outline Parse (Large)" $ nf (parseOutlinePython "large.py") largeSrc+ , bench "F2 Full AST Compute" $ nf computeF2 largeProg+ , bench "F2 Outline Mode Compute" $ nf (\s -> case parseOutlinePython "large.py" s of Right o -> computeF2Outline o; Left _ -> Fingerprint "") largeSrc+ , bench "F3 Full AST Compute" $ nf computeF3 largeProg+ , bench "F3 Outline Mode Compute" $ nf (\s -> case parseOutlinePython "large.py" s of Right o -> computeF3Outline o; Left _ -> Fingerprint "") largeSrc ] , bgroup "Polyglot Outline Extraction"- [ bench "TS Outline (Large)" $ whnf (parseOutlineJS "large.ts") tsLarge- , bench "Go Outline (Large)" $ whnf (parseOutlineGo "large.go") goLarge- , bench "Rust Outline (Large)" $ whnf (parseOutlineRust "large.rs") rsLarge- , bench "IngestOutlineSource (Large)"$ whnf (\b -> ingestOutlineSource "large.py" b largeSrc) largeBytes+ [ bench "TS Outline (Large)" $ nf (parseOutlineJS "large.ts") tsLarge+ , bench "Go Outline (Large)" $ nf (parseOutlineGo "large.go") goLarge+ , bench "Rust Outline (Large)" $ nf (parseOutlineRust "large.rs") rsLarge+ , bench "IngestOutlineSource (Large)"$ nf (\b -> ingestOutlineSource "large.py" b largeSrc) largeBytes ] ] , bgroup "RQ10: v0.0.6-alpha Hardware-Speed Engines" [ bgroup "Engine 1: SWAR FastScan"- [ bench "SWAR scanAsciiAndLineEndings (XL)" $ whnf scanAsciiAndLineEndings xlBytes- , bench "SWAR fastCanonicalizeBS (XL)" $ whnf fastCanonicalizeBS xlBytes- , bench "Standard Unicode canonicalizeText (XL)" $ whnf canonicalizeText xlSrc+ [ bench "SWAR scanAsciiAndLineEndings (XL)" $ nf scanAsciiAndLineEndings xlBytes+ , bench "SWAR fastCanonicalizeBS (XL)" $ nf fastCanonicalizeBS xlBytes+ , bench "Standard Unicode canonicalizeText (XL)" $ nf canonicalizeText xlSrc ] , bgroup "Engine 2: Fused Direct-to-Hash Streaming"- [ bench "fusedHashProgram F1 Direct (XL)" $ whnf fusedHashProgram xlProg- , bench "Standard 3-Pass F1 Compute (XL)" $ whnf (hashBytes . canonicalizeProgram . normalizeProgram) xlProg- , bench "fusedHashDeclarations F2 Direct (XL)" $ whnf (fusedHashDeclarations . extractDeclarations) xlProg+ [ bench "fusedHashProgram F1 Direct (XL)" $ nf fusedHashProgram xlProg+ , bench "Standard 3-Pass F1 Compute (XL)" $ nf (hashBytes . canonicalizeProgram . normalizeProgram) xlProg+ , bench "fusedHashDeclarations F2 Direct (XL)" $ nf (fusedHashDeclarations . extractDeclarations) xlProg ] , bgroup "Engine 3: Compact Binary Merkle Cache Index (CNTR v2)"- [ bench "encodeBinaryCache (1,000 files)" $ whnf encodeBinaryCache largeCache- , bench "decodeBinaryCache (1,000 files)" $ whnf decodeBinaryCache largeCacheBin- , bench "lookupBinaryCache O(log N) Hit" $ whnf (lookupBinaryCache "src/module_500.py" (FileMetadata "src/module_500.py" 1024 1700000000)) largeCacheBin- , bench "Legacy JSON Aeson Decode (1,000 files)" $ whnf (Aeson.decodeStrict :: BS.ByteString -> Maybe MerkleCache) largeCacheJSON+ [ bench "encodeBinaryCache (1,000 files)" $ nf encodeBinaryCache largeCache+ , bench "decodeBinaryCache (1,000 files)" $ nf decodeBinaryCache largeCacheBin+ , bench "lookupBinaryCache O(log N) Hit" $ nf (lookupBinaryCache "src/module_500.py" (FileMetadata "src/module_500.py" 1024 1700000000)) largeCacheBin+ , bench "Legacy JSON Aeson Decode (1,000 files)" $ nf (Aeson.decodeStrict :: BS.ByteString -> Maybe MerkleCache) largeCacheJSON ] , bgroup "Engine 4: Dynamic Work-Stealing Parallel Scheduler" [ bench "parMapChunks 1,000 Tasks" $ nfIO (parMapChunks pure [1..1000 :: Int])@@ -418,83 +453,83 @@ ] , bgroup "RQ11: v0.0.7-alpha Ultra-Low Latency Architecture Engines" [ bgroup "Engine 1: Radix-Directed Binary Cache (CNTR v3)"- [ bench "lookupBinaryCache Radix Hit (1,000 files)" $ whnf (lookupBinaryCache "src/module_500.py" (FileMetadata "src/module_500.py" 1024 1700000000)) largeCacheBin- , bench "encodeBinaryCache with Radix Directory" $ whnf encodeBinaryCache largeCache- , bench "decodeBinaryCache v3 (1,000 files)" $ whnf decodeBinaryCache largeCacheBin+ [ bench "lookupBinaryCache Radix Hit (1,000 files)" $ nf (lookupBinaryCache "src/module_500.py" (FileMetadata "src/module_500.py" 1024 1700000000)) largeCacheBin+ , bench "encodeBinaryCache with Radix Directory" $ nf encodeBinaryCache largeCache+ , bench "decodeBinaryCache v3 (1,000 files)" $ nf decodeBinaryCache largeCacheBin ] , bgroup "Engine 2: Flat Linear Arena AST"- [ bench "programToLinearAST Linearization (XL)" $ whnf programToLinearAST xlProg- , bench "fusedHashLinearAST Direct Arena Hash (XL)" $ whnf fusedHashLinearAST xlArena+ [ bench "programToLinearAST Linearization (XL)" $ nf programToLinearAST xlProg+ , bench "fusedHashLinearAST Direct Arena Hash (XL)" $ nf fusedHashLinearAST xlArena ] , bgroup "Engine 3: SWAR Direct-to-IR FastPython Parser"- [ bench "parseFastPythonByteString Direct (XL)" $ whnf (parseFastPythonByteString "xl.py") xlBytes- , bench "parseFastPythonToArena Direct (XL)" $ whnf (parseFastPythonToArena "xl.py") xlSrc+ [ bench "parseFastPythonByteString Direct (XL)" $ nf (parseFastPythonByteString "xl.py") xlBytes+ , bench "parseFastPythonToArena Direct (XL)" $ nf (parseFastPythonToArena "xl.py") xlSrc ] , bgroup "Engine 4: Isomorphic Incremental Merkle DAG"- [ bench "buildMerkleDAG (1,000 files)" $ whnf buildMerkleDAG repoEntries1000- , bench "merkleDAGRootHash Root Evaluation" $ whnf merkleDAGRootHash dag1000- , bench "diffMerkleDAG (1 delta in 1,000 files)" $ whnf (diffMerkleDAG dag1000) dag1000Mod+ [ bench "buildMerkleDAG (1,000 files)" $ nf buildMerkleDAG repoEntries1000+ , bench "merkleDAGRootHash Root Evaluation" $ nf merkleDAGRootHash dag1000+ , bench "diffMerkleDAG (1 delta in 1,000 files)" $ nf (diffMerkleDAG dag1000) dag1000Mod ] , bgroup "Engine 5: SwissTable Open-Addressing Interning"- [ bench "swissInternBS 1,000 Symbols" $ whnf (\ids -> foldl' (\(_, tbl) bs -> swissInternBS tbl bs) (SymbolId 0, emptySwissTable 1024) ids) sampleIdentifiers- , bench "swissLookupBS Hit" $ whnf (swissLookupBS benchSwissTable) "identifier_500"- , bench "swissResolveId Inverse Lookup" $ whnf (swissResolveId benchSwissTable) (SymbolId 500)+ [ bench "swissInternBS 1,000 Symbols" $ nf (\ids -> foldl' (\(_, tbl) bs -> swissInternBS tbl bs) (SymbolId 0, emptySwissTable 1024) ids) sampleIdentifiers+ , bench "swissLookupBS Hit" $ nf (swissLookupBS benchSwissTable) "identifier_500"+ , bench "swissResolveId Inverse Lookup" $ nf (swissResolveId benchSwissTable) (SymbolId 500) ] ] , bgroup "RQ12: v0.0.9-alpha Whole-Repo Intelligence & Verification" [ bgroup "Engine 1: Whole-Repo Call Graph (F_WCG)"- [ bench "buildWholeRepoCallGraph (10 modules)" $ whnf buildWholeRepoCallGraph modules10- , bench "computeFWCG (10 modules)" $ whnf computeFWCG modules10+ [ bench "buildWholeRepoCallGraph (10 modules)" $ nf buildWholeRepoCallGraph modules10+ , bench "computeFWCG (10 modules)" $ nf computeFWCG modules10 ] , bgroup "Engine 2: Whole-Repo Inter-Procedural Data-Flow (F_WDF)"- [ bench "buildWholeRepoDataFlow (10 modules)" $ whnf buildWholeRepoDataFlow modules10- , bench "computeFWDF (10 modules)" $ whnf computeFWDF modules10+ [ bench "buildWholeRepoDataFlow (10 modules)" $ nf buildWholeRepoDataFlow modules10+ , bench "computeFWDF (10 modules)" $ nf computeFWDF modules10 ] , bgroup "Engine 3: Semantic Change Impact Slicing (CIA)"- [ bench "classifySeverity (Interface Mutation)" $ whnf (classifySeverity (feFingerprints sampleBundle)) (feFingerprints (head repo1000))- , bench "computeImpactSlice (10 modules)" $ whnf (\b -> computeImpactSlice "src/module_1.py" (feFingerprints sampleBundle) b wcg10 (map fst modules10)) (feFingerprints (head repo1000))+ [ bench "classifySeverity (Interface Mutation)" $ nf (classifySeverity (feFingerprints sampleBundle)) (feFingerprints (head repo1000))+ , bench "computeImpactSlice (10 modules)" $ nf (\b -> computeImpactSlice "src/module_1.py" (feFingerprints sampleBundle) b wcg10 (map fst modules10)) (feFingerprints (head repo1000)) ] , bgroup "Engine 4: Structural Type Contract Invariance (F_T)"- [ bench "extractTypeContracts (XL)" $ whnf extractTypeContracts xlProg- , bench "computeFT (XL)" $ whnf computeFT xlProg+ [ bench "extractTypeContracts (XL)" $ nf extractTypeContracts xlProg+ , bench "computeFT (XL)" $ nf computeFT xlProg ] , bgroup "Engine 5: Memory-Mapped Paged Radix Cache (CNTR v5)"- [ bench "encodeBinaryCacheV5 (1,000 files)" $ whnf encodeBinaryCacheV5 largeCache- , bench "decodeBinaryCacheV5 (1,000 files)" $ whnf decodeBinaryCacheV5 largeCacheV5Bin- , bench "lookupBinaryCacheV5 Hit" $ whnf (lookupBinaryCacheV5 "src/module_500.py" (FileMetadata "src/module_500.py" 1024 1700000000)) largeCacheV5Bin+ [ bench "encodeBinaryCacheV5 (1,000 files)" $ nf encodeBinaryCacheV5 largeCache+ , bench "decodeBinaryCacheV5 (1,000 files)" $ nf decodeBinaryCacheV5 largeCacheV5Bin+ , bench "lookupBinaryCacheV5 Hit" $ nf (lookupBinaryCacheV5 "src/module_500.py" (FileMetadata "src/module_500.py" 1024 1700000000)) largeCacheV5Bin ] , bgroup "Engine 6: Metamorphic Mutation & Verification"- [ bench "verifyMetamorphicProgramTransform (XL)"$ whnf (`verifyMetamorphicProgramTransform` (ReformatWhitespaceTrivia 4)) xlProg- , bench "verifyProgramMutation (XL)" $ whnf (`verifyProgramMutation` (MutFlipArithmeticOp OpAdd OpSub)) xlProg- , bench "runMetamorphicSuite (Polyglot Corpus)" $ whnf runMetamorphicSuite polyglotFixtures+ [ bench "verifyMetamorphicProgramTransform (XL)"$ nf (`verifyMetamorphicProgramTransform` (ReformatWhitespaceTrivia 4)) xlProg+ , bench "verifyProgramMutation (XL)" $ nf (`verifyProgramMutation` (MutFlipArithmeticOp OpAdd OpSub)) xlProg+ , bench "runMetamorphicSuite (Polyglot Corpus)" $ nf runMetamorphicSuite polyglotFixtures ] ] , bgroup "RQ13: v0.2.0 Unboxed CSR Graph Engine" [ bgroup "Engine 1: CSR Construction & Query"- [ bench "buildCSRGraph (100 nodes, 500 edges)" $ whnf (buildCSRGraph 100) csrEdges500- , bench "csrHasEdge Binary Search (Hit)" $ whnf (\g -> csrHasEdge g 10 37) csrGraph100- , bench "transposeCSR Linear Transpose" $ whnf transposeCSR csrGraph100- , bench "tarjanSCC Cycle Detection" $ whnf tarjanSCC csrGraph100- , bench "condenseSCC Canonical DAG" $ whnf condenseSCC csrGraph100- , bench "forwardReachabilityCone (100 nodes)" $ whnf (\g -> forwardReachabilityCone g [10]) csrGraph100+ [ bench "buildCSRGraph (100 nodes, 500 edges)" $ nf (buildCSRGraph 100) csrEdges500+ , bench "csrHasEdge Binary Search (Hit)" $ nf (\g -> csrHasEdge g 10 37) csrGraph100+ , bench "transposeCSR Linear Transpose" $ nf transposeCSR csrGraph100+ , bench "tarjanSCC Cycle Detection" $ nf tarjanSCC csrGraph100+ , bench "condenseSCC Canonical DAG" $ nf condenseSCC csrGraph100+ , bench "forwardReachabilityCone (100 nodes)" $ nf (\g -> forwardReachabilityCone g [10]) csrGraph100 ] , bgroup "Engine 2: Whole-Repo CSR Synthesis"- [ bench "buildCSRCallGraph (10 modules)" $ whnf buildCSRCallGraph modules10- , bench "buildCSRDataFlow (10 modules)" $ whnf buildCSRDataFlow modules10+ [ bench "buildCSRCallGraph (10 modules)" $ nf buildCSRCallGraph modules10+ , bench "buildCSRDataFlow (10 modules)" $ nf buildCSRDataFlow modules10 ] ] , bgroup "RQ14: v0.2.0 CNTR\\x06 Zero-Copy Memory-Mapped Slab Cache"- [ bench "encodeSlabV6Binary (1,000 files)" $ whnf (`encodeSlabV6Binary` Nothing) slabEntries1000- , bench "decodeSlabV6Binary (1,000 files)" $ whnf decodeSlabV6Binary slabV6Bin- , bench "lookupSlabBinaryBS Zero-Copy Warm Hit" $ whnf (\bs -> lookupSlabBinaryBS "src/module_500.py" (FileMetadata "src/module_500.py" 1024 1700000000) bs) slabV6Bin- , bench "encodeCSRGraph Binary Serialization" $ whnf (LBS.toStrict . BB.toLazyByteString . encodeCSRGraph) csrGraph100- , bench "decodeCSRGraph Binary Deserialization" $ whnf decodeCSRGraph csrEncodedBS+ [ bench "encodeSlabV6Binary (1,000 files)" $ nf (`encodeSlabV6Binary` Nothing) slabEntries1000+ , bench "decodeSlabV6Binary (1,000 files)" $ nf decodeSlabV6Binary slabV6Bin+ , bench "lookupSlabBinaryBS Zero-Copy Warm Hit" $ nf (\bs -> lookupSlabBinaryBS "src/module_500.py" (FileMetadata "src/module_500.py" 1024 1700000000) bs) slabV6Bin+ , bench "encodeCSRGraph Binary Serialization" $ nf (LBS.toStrict . BB.toLazyByteString . encodeCSRGraph) csrGraph100+ , bench "decodeCSRGraph Binary Deserialization" $ nf decodeCSRGraph csrEncodedBS ] , bgroup "RQ15: v0.2.0 SIMD FastScan & Chase-Lev Work-Stealing" [ bgroup "Engine 1: 256-Bit Hardware SIMD Scan"- [ bench "scanSourceSIMD 256-Bit (XL)" $ whnf scanSourceSIMD xlBytes- , bench "isPureAsciiUnixSIMD FastPath (XL)" $ whnf isPureAsciiUnixSIMD xlBytes- , bench "fastCanonicalizeSIMD (XL)" $ whnf fastCanonicalizeSIMD xlBytes+ [ bench "scanSourceSIMD 256-Bit (XL)" $ nf scanSourceSIMD xlBytes+ , bench "isPureAsciiUnixSIMD FastPath (XL)" $ nf isPureAsciiUnixSIMD xlBytes+ , bench "fastCanonicalizeSIMD (XL)" $ nf fastCanonicalizeSIMD xlBytes ] , bgroup "Engine 2: Chase-Lev Lock-Free Work-Stealing" [ bench "Chase-Lev Deque Push/Pop/Steal" $ nfIO $ do@@ -506,20 +541,34 @@ , bench "parProcessWorkStealing (1,000 tasks)" $ nfIO $ parProcessWorkStealing (\x -> pure (x * (2 :: Int))) [1..1000 :: Int] ] , bgroup "Engine 3: Localized Incremental Graph Delta"- [ bench "spliceCSREdges Localized Invalidation" $ whnf (\g -> spliceCSREdges g [10] [(10, 20, 1)]) csrGraph100- , bench "incrementalUpdateWholeRepoGraphs (10 modules)" $ whnf (\mods -> incrementalUpdateWholeRepoGraphs wcg10Graph wdf10Graph mods ["src/module_1.py"]) modules10+ [ bench "spliceCSREdges Localized Invalidation" $ nf (\g -> spliceCSREdges g [10] [(10, 20, 1)]) csrGraph100+ , bench "incrementalUpdateWholeRepoGraphs (10 modules)" $ nf (\mods -> incrementalUpdateWholeRepoGraphs wcg10Graph wdf10Graph mods ["src/module_1.py"]) modules10 ] ] , bgroup "RQ16: v0.3.0 Bound Alpha-Canonicalization & CFG RPO"- [ bench "canonicalizeAlphaProgram (Medium)" $ whnf canonicalizeAlphaProgram medProg- , bench "canonicalizeAlphaProgram (XL)" $ whnf canonicalizeAlphaProgram xlProg- , bench "canonicalizeCFGRPO (XL)" $ whnf (map canonicalizeCFGRPO . buildCFGs) xlProg+ [ bench "canonicalizeAlphaProgram (Medium)" $ nf canonicalizeAlphaProgram medProg+ , bench "canonicalizeAlphaProgram (XL)" $ nf canonicalizeAlphaProgram xlProg+ , bench "canonicalizeCFGRPO (XL)" $ nf (map canonicalizeCFGRPO . buildCFGs) xlProg ] , bgroup "RQ17: v0.3.0 Algebraic Normalization & CSR Batch CIA 2.0"- [ bench "normalizeAlgebraicProgram (Medium)" $ whnf normalizeAlgebraicProgram medProg- , bench "normalizeAlgebraicProgram (XL)" $ whnf normalizeAlgebraicProgram xlProg- , bench "computeImpactSliceCSR (10 modules)" $ whnf (\b -> computeImpactSliceCSR "src/module_1.py" (feFingerprints sampleBundle) b csrPair10 (map fst modules10)) (feFingerprints (head repo1000))- , bench "computeBatchImpactSliceCSR (PR batch)" $ whnf (\b -> computeBatchImpactSliceCSR [("src/module_1.py", feFingerprints sampleBundle, b)] csrPair10 (map fst modules10)) (feFingerprints (head repo1000))+ [ bench "normalizeAlgebraicProgram (Medium)" $ nf normalizeAlgebraicProgram medProg+ , bench "normalizeAlgebraicProgram (XL)" $ nf normalizeAlgebraicProgram xlProg+ , bench "computeImpactSliceCSR (10 modules)" $ nf (\b -> computeImpactSliceCSR "src/module_1.py" (feFingerprints sampleBundle) b csrPair10 (map fst modules10)) (feFingerprints (head repo1000))+ , bench "computeBatchImpactSliceCSR (PR batch)" $ nf (\b -> computeBatchImpactSliceCSR [("src/module_1.py", feFingerprints sampleBundle, b)] csrPair10 (map fst modules10)) (feFingerprints (head repo1000))+ ]+ , bgroup "RQ18: v0.4.0 SlabV7 & Summary Synthesis"+ [ bench "encodeSlabV7Binary (10 modules)" $ nf (`encodeSlabV7Binary` Nothing) slabV7Entries10+ , bench "decodeSlabV7Binary (10 modules)" $ nf decodeSlabV7Binary slabV7Bin10+ , bench "lookupSlabV7BinaryBS (Warm Hit)" $ nf (lookupSlabV7BinaryBS "src/module_1.py" (FileMetadata "src/module_1.py" 1024 1700000000)) slabV7Bin10+ , bench "buildWholeRepoCallGraphFromSummaries (10 mods)" $ nf buildWholeRepoCallGraphFromSummaries summaries10+ , bench "buildWholeRepoDataFlowFromSummaries (10 mods)" $ nf buildWholeRepoDataFlowFromSummaries summaries10+ ]+ , bgroup "RQ19: v0.4.0 Stateless AI Harness Sub-Versioning (canontra snap)"+ [ bench "diffFileBundles (9-tier bundle comparison)" $ nf (diffFileBundles (feFingerprints sampleBundle)) dummyBundleM+ , bench "computeFileDeltas (1,000 files, 1 dirty)" $ nf (computeFileDeltas snapMap1000) snapMap1000Mod+ , bench "classifySnapDeltas (dirty delta triage)" $ nf classifySnapDeltas snapDirtyDeltas+ , bench "parseGuardTiers (F2,F3,F_T)" $ nf parseGuardTiers "F2,F3,F_T"+ , bench "matchesGlob (**/*.py)" $ nf (matchesGlob "**/*.py") "src/module_500.py" ] ] _ -> putStrLn "Error initializing benchmark source fixtures."
benchmarkReport.md view
@@ -1,176 +1,120 @@-# Canontra Empirical Benchmark Report & Scientific Evaluation (Version 3) - -**A Formal Investigation into Orthogonal Cryptographic Program Identity, Deep Algebraic Equivalence, Scope-Aware $\alpha$-Canonicalization, and CSR-Native Batch Change Impact Analysis** - -* **Report Version**: 3 -* **Lead Author / Principal Investigator**: Jash Thakkar & SymtraceLabs Research Team -* **Implementation**: Canontra v0.3.0.0 (Release v0.3.0) (`dist-bin/canontra.exe` compiled via GHC 9.6.6 with `-O2`) -* **Evaluation Date**: November 11, 2026 -* **Testbed Environment**: - * **Host Operating System**: Windows 11 Enterprise (Build 26100), NTFS filesystem - * **Processors / Capabilities**: Multi-core x86_64 hardware with Haskell GHC SMP work-stealing scheduler (`+RTS -N`) -* **Live Evaluated Toolchain (Installed Locally on Testbed)**: - * **Canontra**: v0.3.0.0 / v0.3.0 (`dist-bin/canontra.exe`) - * **GitHub CodeQL**: v2.27.0 CLI (`codeql.exe` with native extractors for Python, JavaScript/TypeScript, Rust, and Go) - * **Git**: v2.48.1 (`git hash-object` live per-file execution) - * **Turborepo**: v2.11.2 (`turbo` CLI) - * **Mozilla sccache**: v0.8.2 (`sccache.exe`) - * **Compilers**: Go 1.23.1, Rustc / Cargo 1.83+ -* **Corpus Scale**: 15 Real-World Open-Source Repositories, 3,258 Source Files, 1,044,717 Total Lines of Code (LOC) -* **Methodological Integrity**: **Zero Dogfooding**; **Zero Simulated Baseline Values**; every number in this report reflects true live process execution timings captured via high-resolution monotonic hardware timers. - -## 1. Executive Summary - -This report presents the empirical execution results for **Canontra v0.3.0.0 (v0.3.0): Deep Algebraic Equivalence, $\alpha$-Invariance & CSR-Native CIA 2.0 Milestone**. - -Canontra v0.3.0 expands semantic invariance across local variable naming, algebraic laws, control-flow topologies, and monorepo impact slicing: -1. **Scope-Aware Bound Lexical $\alpha$-Canonicalization (`Canontra.Normalize.Alpha`)**: Bound local variables, comprehension iterators, lambda binders, and exception variables normalize to deterministic de Bruijn indices (`@v<depth>.<ordinal>`), delivering **100% bit-identical** $F_1$, $F_{DF}$, and $F_4$ fingerprints while preserving public export sensitivity in $F_2$ and $F_T$. Evaluates in **$87.2\,\text{ns}$ - $93.1\,\text{ns}$** (RQ16). -2. **Commutative & Associative Algebraic Normal Form (`Canontra.Normalize.Algebraic`)**: Pure commutative operators (`+`, `*`, `&`, `|`, `^`, `==`, `!=`), relational duals (`b > a` $\to$ `a < b`), double negations (`not (not x)` $\to$ `x`), and set/dict literals normalize canonically. Evaluates in **$71.9\,\text{ns}$ - $81.2\,\text{ns}$** (RQ17). -3. **CFG Dominator-Tree & RPO Canonicalization (`Canontra.Analysis.CFGCanonical`)**: Branch inversions (`if (!c) B else A` $\to$ `if (c) A else B`), early-return guard lifting, and post-terminator dead code elimination normalize into canonical Reverse Post-Order (RPO) blocks in **$125.9\,\text{ns}$** (RQ16). -4. **Structural Type Contract ($F_T$) Lattice Deepening (`Canontra.Analysis.TypeContract`)**: Deep recursive Union/Intersection ANF flattening (`(A | B) | (C | A)` $\to$ `A | B | C`), structural record field sorting, and positional de Bruijn generic parameter normalization (`[T, U]` $\to$ `[α0, α1]`). -5. **CSR-Native Multi-File PR Batch Change Impact Analysis (`Canontra.Analysis.BatchImpact`)**: Slices joint caller cones over unboxed CSR call graphs in **$187.7\,\mu\text{s}$**, automatically triaging files into Level 1 (Trivia), Level 2 (Internal Logic), and Level 3 (Interface/Dependency), and synthesizing targeted test runner commands (`pytest`, `jest`, `go test`, `cargo test`). - -### Key Live Empirical Findings - -1. **Canontra Outperforms GitHub CodeQL by 2.6× to 92.1× Across All Languages**: - * On **Rust codebases** (`toml`, `ripgrep`), CodeQL database creation required **279.4s** and **249.4s**. Canontra completed cold indexing in **6.04s** (**46.2× faster**) and **4.04s** (**61.8× faster**). - * On **Go monolithic codebases** (`hugo`, `prometheus`), CodeQL database creation required **266.4s** and **1,043.2s** (~17.4 minutes). Canontra completed cold indexing in **31.25s** (**8.5× faster**) and **57.48s** (**18.1× faster**). - * On **Python and JavaScript repositories** (`bottle`, `requests`, `flask`, `marshmallow`, `chalk`, `click`, `jinja`, `express`), Canontra cold ingestion completed in **1.0s - 4.0s** (**6.4× to 21.6× faster than CodeQL**). -2. **Whole-Repository Graph Synthesis ($F_{WCG}$ & $F_{WDF}$)**: - * Computed via the unboxed CSR graph engine in linear time ($O(V + E)$). - * All 15 repository manifests emit concrete, collision-resistant 64-character SHA-256 digests for both call graphs and data-flow graphs with **zero null values**. -3. **Multi-File Batch Change Impact Analysis (CIA 2.0)**: - * Tested across all 15 codebases via `canontra impact`, computing reachability cones and generating runnable CI test execution strings in **1.0s to 32.2s** even for monolithic multi-hundred-thousand-LOC graphs. -4. **100% Ingestion and Verification Success Rate**: - * Across 15 production repositories and over 1,000,000 lines of code, Canontra incurred **zero panics, zero uncaught exceptions, and zero segmentation faults (exit code 0 across all cold, warm, and impact runs)**. - -## 2. Live Empirical Benchmark Dataset (15 Repositories) - -The table below presents the live measurements obtained by executing `researchBenchmarks/run_v0.3.0_benchmarks.ps1` on the local machine with Canontra v0.3.0 (`dist-bin/canontra.exe`). All latencies reflect wall-clock execution time in milliseconds and seconds measured with `System.Diagnostics.Stopwatch`. - -### Table 1: Canontra v0.3.0 Ingestion, Latency, and Graph Digests - -| Repository | Language | Total Files | Indexed Files | Total LOC | Cold Latency (ms) | Warm Latency (ms) | Speedup | Batch CIA (ms) | Throughput (LOC/s) | Repository Digest ($F_R$) | Whole-Repo Call Graph ($F_{WCG}$) | Whole-Repo Data Flow ($F_{WDF}$) | Exit | -| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :--- | :--- | :--- | :---: | -| **`bottle`** | Python | 30 | 16 | 7,759 | 1,030.13 ms | 1,022.29 ms | 1.01x | 1,018.42 ms | 7,532 | `d9d5f0a4d29ee1a5...` | `82e50951301442ed...` | `cbb258bf8a3cbdb1...` | 0 | -| **`toml`** | Rust | 166 | 166 | 44,360 | 6,043.64 ms | 5,041.02 ms | 1.20x | 3,040.85 ms | 7,340 | `83e82988975a8603...` | `dab9f05e19d22955...` | `10f14ec8fc9c2d99...` | 0 | -| **`requests`** | Python | 37 | 21 | 9,841 | 1,011.22 ms | 1,010.98 ms | 1.00x | 1,030.29 ms | 9,732 | `021edc63166980c2...` | `f87e69b26b22871e...` | `7a3f99351a2b36e7...` | 0 | -| **`flask`** | Python | 83 | 43 | 14,085 | 2,027.47 ms | 2,015.77 ms | 1.01x | 1,023.67 ms | 6,947 | `173a56a683e4def0...` | `69e9fed170f9be3b...` | `ea0930b55b7b42ee...` | 0 | -| **`marshmallow`**| Python | 38 | 17 | 12,734 | 1,011.87 ms | 1,029.08 ms | 0.98x | 1,015.49 ms | 12,585 | `2de9c340c1b7445d...` | `fc571f2cfde29e5d...` | `781892b2eb609196...` | 0 | -| **`chalk`** | JavaScript | 20 | 14 | 1,793 | 1,026.03 ms | 1,015.15 ms | 1.01x | 1,018.96 ms | 1,748 | `e5c21045aba8f627...` | `cd2aeacf9d0b0123...` | `7b599d6756e7a155...` | 0 | -| **`click`** | Python | 90 | 54 | 23,803 | 2,021.01 ms | 2,018.32 ms | 1.00x | 1,026.73 ms | 11,778 | `e99fc79f78c34726...` | `6523f4b5c26ed765...` | `665df9b138ec4dd5...` | 0 | -| **`gin`** | Go | 99 | 99 | 20,528 | 2,022.34 ms | 2,019.83 ms | 1.00x | 1,031.02 ms | 10,151 | `3d2dde3705f446a0...` | `2cd7ef354e69951c...` | `0e33037012cbca6b...` | 0 | -| **`jinja`** | Python | 60 | 25 | 18,825 | 1,012.95 ms | 1,014.92 ms | 1.00x | 1,019.03 ms | 18,584 | `e42d94052565adf7...` | `5db1aaea50f70fdc...` | `d544cbe367d050f8...` | 0 | -| **`ripgrep`** | Rust | 110 | 110 | 50,953 | 4,036.57 ms | 4,036.00 ms | 1.00x | 3,038.65 ms | 12,623 | `0b55f53d6fc0f441...` | `a9c2a086971c467f...` | `b7e3fce7a6910424...` | 0 | -| **`express`** | JavaScript | 141 | 141 | 17,552 | 4,048.29 ms | 2,028.79 ms | 2.00x | 1,024.37 ms | 4,336 | `62b6cbd1a191e140...` | `59ed1a022beeebd5...` | `3586e558224128dc...` | 0 | -| **`rich`** | Python | 213 | 142 | 45,787 | 16,129.89 ms| 16,133.07 ms| 1.00x | 11,081.50 ms| 2,839 | `b538c3d49fcf2aeb...` | `605c50f13677fc5f...` | `ff0f5187930879a5...` | 0 | -| **`hugo`** | Go | 936 | 937 | 202,834 | 31,254.55 ms| 28,188.98 ms| 1.11x | 14,102.29 ms| 6,490 | `05f53e27868ea3b7...` | `8ffc7964ec118b14...` | `946b6e3e5d4cbce6...` | 0 | -| **`deno_core`** | TS/Rust | 315 | 318 | 62,775 | 5,041.87 ms | 5,049.21 ms | 1.00x | 3,039.82 ms | 12,451 | `d4a60b6d7719e6a1...` | `e63a89fcaffdbd51...` | `5c0c30a14cf5bc8e...` | 0 | -| **`prometheus`** | Go | 844 | 994 | 369,444 | 57,483.26 ms| 57,478.64 ms| 1.00x | 32,258.46 ms| 6,427 | `6bbb1a9872070d3d...` | `b38eeec60454829a...` | `e118e953f378d294...` | 0 | - -*Data source: [`researchBenchmarks/v0.3.0_benchmark_summary.csv`](file:///d:/barista/canontra/researchBenchmarks/v0.3.0_benchmark_summary.csv).* - -## 3. Live Comparative Benchmark Evaluation across Tools - -The table below presents the comparative execution times across Canontra v0.3.0, Git raw hashing, Turborepo package hashing, Mozilla sccache compilation caching, and GitHub CodeQL static analysis database extraction. - -### Table 2: Comparative Tool Latency (Wall-Clock Seconds) - -| Repository | Language | Files | LOC | Canontra v0.3.0 (s) | Canontra Throughput (LOC/s) | Git Hashing (s) | Turborepo (s) | Sccache (s) | CodeQL CLI (s) | Speedup vs. CodeQL | -| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | -| **`bottle`** | Python | 30 | 7,759 | **1.030 s** | 7,532 | 1.456 s | 0.031 s | N/A | 18.052 s | **17.5x** | -| **`toml`** | Rust | 166 | 44,360 | **6.044 s** | 7,340 | 7.909 s | 0.177 s | 3.308 s | 279.388 s | **46.2x** | -| **`requests`** | Python | 37 | 9,841 | **1.011 s** | 9,732 | 2.514 s | 0.039 s | N/A | 18.054 s | **17.9x** | -| **`flask`** | Python | 83 | 14,085 | **2.027 s** | 6,947 | 4.212 s | 0.056 s | N/A | 19.060 s | **9.4x** | -| **`marshmallow`**| Python | 38 | 12,734 | **1.012 s** | 12,585 | 1.795 s | 0.051 s | N/A | 17.093 s | **16.9x** | -| **`chalk`** | JavaScript | 20 | 1,793 | **1.026 s** | 1,748 | 0.695 s | 0.140 s | N/A | 22.040 s | **21.5x** | -| **`click`** | Python | 90 | 23,803 | **2.021 s** | 11,778 | 4.074 s | 0.095 s | N/A | 19.057 s | **9.4x** | -| **`gin`** | Go | 99 | 20,528 | **2.022 s** | 10,151 | 4.525 s | 0.082 s | 2.626 s | 25.045 s | **12.4x** | -| **`jinja`** | Python | 60 | 18,825 | **1.013 s** | 18,584 | 2.699 s | 0.075 s | N/A | 19.059 s | **18.8x** | -| **`ripgrep`** | Rust | 110 | 50,953 | **4.037 s** | 12,623 | 4.931 s | 0.204 s | 3.493 s | 249.391 s | **61.8x** | -| **`express`** | JavaScript | 141 | 17,552 | **4.048 s** | 4,336 | 6.732 s | 1.365 s | N/A | 26.056 s | **6.4x** | -| **`rich`** | Python | 213 | 45,787 | **16.130 s** | 2,839 | 9.882 s | 0.183 s | N/A | 29.100 s | **1.8x** | -| **`hugo`** | Go | 936 | 202,834 | **31.255 s** | 6,490 | 42.110 s | 0.812 s | 9.262 s | 266.449 s | **8.5x** | -| **`deno_core`** | TS/Rust | 315 | 62,775 | **5.042 s** | 12,451 | 14.516 s | 1.151 s | 3.829 s | 27.050 s | **5.4x** | -| **`prometheus`** | Go | 844 | 369,444 | **57.483 s** | 6,427 | 47.279 s | 1.552 s | 14.640 s | 1,043.217 s | **18.1x** | - -*Data source: [`researchBenchmarks/v0.3.0_benchmark_comparative_summary.csv`](file:///d:/barista/canontra/researchBenchmarks/v0.3.0_benchmark_comparative_summary.csv).* - -## 4. Micro-Benchmark Evaluation (RQ16 & RQ17) - -Measured via `tasty-bench` under GHC 9.6.6 with `-O2`: - -### 4.1 Scope-Aware Bound Lexical $\alpha$-Canonicalization (RQ16) - -```text -RQ16: v0.3.0 Bound Alpha-Canonicalization & CFG RPO - canonicalizeAlphaProgram (Medium ~405 LOC): 87.2 ns ± 97 ns - canonicalizeAlphaProgram (XL ~4,005 LOC): 93.1 ns ± 110 ns - canonicalizeCFGRPO (XL ~4,005 LOC): 125.9 ns ± 37 ns -``` - -* **Mathematical Invariance**: 100% bit-identical $F_1$, $F_{DF}$, and $F_4$ fingerprints across local variable renamings. -* **Micro-Scale Performance**: Evaluates full lexical scope rewriting in under $100\,\text{ns}$ per module. - -### 4.2 Algebraic Normalization & CSR Batch CIA 2.0 (RQ17) - -```text -RQ17: v0.3.0 Algebraic Normalization & CSR Batch CIA 2.0 - normalizeAlgebraicProgram (Medium ~405 LOC): 71.9 ns ± 12 ns - normalizeAlgebraicProgram (XL ~4,005 LOC): 81.2 ns ± 37 ns - computeBatchImpactSliceCSR (PR batch): 187.7 μs ± 130 μs - computeImpactSliceCSR (10 modules): 408.9 μs ± 206 μs -``` - -* **Algebraic Soundness**: Pure commutative/associative operators (`+`, `*`, `&`, `|`, `^`, `==`, `!=`) flatten and sort canonically in under $85\,\text{ns}$. -* **PR Batch Impact Speed**: Joint reachability slicing over unboxed CSR call graphs completes in **$187.7\,\mu\text{s}$**, easily satisfying the sub-$50\,\mu\text{s}$ per-module latency gate. - -## 5. Metamorphic Mutation Testing Evaluation - -Canontra v0.3.0 was evaluated against 14 metamorphic mutations across the 15 repositories: - -| Trial | Repository | Language | Mutation Target | Mutation Type | Canontra $F_1$ | Canontra $F_2$ | Canontra $F_R$ | Canontra Verdict | Git Diverges? | Turborepo Diverges? | -| :---: | :--- | :--- | :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | -| 1 | `chalk` | JavaScript | `source/utilities.js` | Convert LF to CRLF line endings | Invariant | Invariant | Invariant | **INVARIANT** | YES (Diverges) | YES (Invalidates) | -| 2 | `bottle` | Python | `bottle.py` | Rename local variable `total` to `acc` | Invariant | Invariant | Invariant | **INVARIANT** | YES (Diverges) | YES (Invalidates) | -| 3 | `gin` | Go | `gin.go` | Swap commutative operands `a + b` $\to$ `b + a` | Invariant | Invariant | Invariant | **INVARIANT** | YES (Diverges) | YES (Invalidates) | -| 4 | `toml` | Rust | `src/lib.rs` | Invert branch `if (!c) B else A` $\to$ `if (c) A else B` | Invariant | Invariant | Invariant | **INVARIANT** | YES (Diverges) | YES (Invalidates) | -| 5 | `requests` | Python | `requests/api.py` | Reorder pure helper functions | Invariant | Invariant | Invariant | **INVARIANT** | YES (Diverges) | YES (Invalidates) | -| 6 | `express` | JavaScript | `lib/application.js` | Permute union type `(A \| B) \| C` $\to$ `C \| (B \| A)` | Invariant | Invariant | Invariant | **INVARIANT** | YES (Diverges) | YES (Invalidates) | -| 7 | `ripgrep` | Rust | `crates/core/main.rs` | Double negation `not (not x)` $\to$ `x` | Invariant | Invariant | Invariant | **INVARIANT** | YES (Diverges) | YES (Invalidates) | -| 8 | `flask` | Python | `src/flask/app.py` | Inject header license comments | Invariant | Invariant | Invariant | **INVARIANT** | YES (Diverges) | YES (Invalidates) | -| 9 | `hugo` | Go | `hugolib/site.go` | Add trailing spaces and blank lines | Invariant | Invariant | Invariant | **INVARIANT** | YES (Diverges) | YES (Invalidates) | -| 10 | `click` | Python | `src/click/core.py` | Semantic: mutate arithmetic `+` to `-` | **Diverged** | Invariant | **Diverged** | **DETECTED** | YES (Diverges) | YES (Invalidates) | -| 11 | `jinja` | Python | `src/jinja2/lexer.py` | Semantic: alter regex token pattern | **Diverged** | Invariant | **Diverged** | **DETECTED** | YES (Diverges) | YES (Invalidates) | -| 12 | `rich` | Python | `rich/console.py` | Semantic: alter default argument value | **Diverged** | **Diverged** | **Diverged** | **DETECTED** | YES (Diverges) | YES (Invalidates) | -| 13 | `deno_core` | Rust/TS | `core/runtime.rs` | Interface: add public export function | **Diverged** | **Diverged** | **Diverged** | **DETECTED** | YES (Diverges) | YES (Invalidates) | -| 14 | `prometheus` | Go | `model/labels.go` | Interface: modify public struct method sig | **Diverged** | **Diverged** | **Diverged** | **DETECTED** | YES (Diverges) | YES (Invalidates) | - -### Statistical Metrics -* **False-Discovery Rate (FDR)** for non-functional refactorings: **0.0%** (0 / 9 false invalidations in Canontra, compared to **100.0%** in Git and Turborepo). -* **True-Detection Rate (TDR)** for functional and interface mutations: **100.0%** (5 / 5 true positives detected across $F_1$, $F_2$, and $F_R$). - -## 6. Answers to Research Questions - -* **RQ1: Polyglot Ingestion Robustness**: Confirmed across 15 real-world repositories (3,258 files, >1,000,000 LOC) with 100% completion and zero crashes. -* **RQ2: Mathematical Determinism**: Confirmed ($\Delta F = 0$) across repeated cold and warm execution cycles. -* **RQ3: Micro-Architectural Throughput**: Confirmed sustained throughput up to 18,500 LOC/s on large codebases. -* **RQ4: Orthogonal Mutation Discrimination**: Confirmed $\text{FDR} = 0.0\%$ and $\text{TDR} = 100.0\%$. -* **RQ5: Industry Baseline Comparison**: Confirmed 5.4× to 61.8× faster than CodeQL CLI database extraction on non-trivial codebases. -* **RQ13: Unboxed CSR Graph Engine**: Confirmed logarithmic edge query ($24.4\,\text{ns}$) and linear SCC cycle condensation ($42.3\,\mu\text{s}$). -* **RQ14: `CNTR\x06` Memory-Mapped Slab Cache**: Confirmed sub-microsecond warm lookups ($< 500\,\text{ns}$) and binary CSR graph persistence. -* **RQ15: SIMD FastScan & Work-Stealing Parallelism**: Confirmed 256-bit SIMD classification ($268\,\mu\text{s}$) and Chase-Lev parallel processing ($11.9\,\text{ms}$). -* **RQ16: Bound $\alpha$-Canonicalization & CFG Dominators**: Confirmed sub-100 ns lexical $\alpha$-rewriting ($87.2\,\text{ns}$) and deterministic Reverse Post-Order basic block relabeling ($125.9\,\text{ns}$). -* **RQ17: Algebraic Equivalence & CSR Batch CIA 2.0**: Confirmed sub-100 ns algebraic expression sorting ($71.9\,\text{ns}$) and sub-200 microsecond joint PR batch impact slicing ($187.7\,\mu\text{s}$). - -## 7. Deliverables & Preserved Artifacts - -All experimental artifacts have been generated live and preserved in the repository: -1. **Definitive Report**: [`benchmarkReport.md`](file:///d:/barista/canontra/benchmarkReport.md) -2. **Performance Latency Documentation**: [`BENCHMARKS.md`](file:///d:/barista/canontra/BENCHMARKS.md) -3. **v0.3.0 Summary CSV**: [`researchBenchmarks/v0.3.0_benchmark_summary.csv`](file:///d:/barista/canontra/researchBenchmarks/v0.3.0_benchmark_summary.csv) -4. **v0.3.0 Comparative CSV**: [`researchBenchmarks/v0.3.0_benchmark_comparative_summary.csv`](file:///d:/barista/canontra/researchBenchmarks/v0.3.0_benchmark_comparative_summary.csv) -5. **v0.3.0 Microbenchmarks CSV**: [`scratch/v0.3.0_bench_results.csv`](file:///d:/barista/canontra/scratch/v0.3.0_bench_results.csv) -6. **Live Multi-Repository Benchmark Automation Runner**: [`researchBenchmarks/run_v0.3.0_benchmarks.ps1`](file:///d:/barista/canontra/researchBenchmarks/run_v0.3.0_benchmarks.ps1) -7. **Production Binary**: `dist-bin/canontra.exe` (v0.3.0) - +# Canontra Empirical Benchmark Report & Scientific Evaluation (Version 4)++**A Formal Investigation into Ultra-Low-Latency Semantic Hashing, ByteString/SIMD Parsing, `CNTR\x07` Incremental Graph Caching, Hardened Type Contracts, and Stateless AI Harness Sub-Versioning**++* **Report Version**: 4+* **Lead Author / Principal Investigator**: Jash Thakkar & SymtraceLabs Research Team+* **Implementation**: Canontra `v0.4.0.0` (Release `v0.4.0`, `dist-bin/canontra.exe` compiled via GHC 9.6.6 with `-O2`)+* **Evaluation Date**: December 1, 2026+* **Testbed Environment**:+ * **Host Operating System**: Windows 11 (NTFS filesystem)+ * **Processors / Capabilities**: Multi-core x86_64 hardware with Haskell GHC SMP work-stealing scheduler (`+RTS -N`)+* **Measurement Methodology Upgrade (`v0.4.0`)**:+ * `run_v0.4.0_benchmarks.ps1` replaces PowerShell `Start-Process -Wait` (which introduced a ~1,000 ms polling quantization floor in `v0.3.0`) with direct `.NET System.Diagnostics.Process` (`ProcessStartInfo` + async stream capture) timed via high-resolution `[System.Diagnostics.Stopwatch]`.+ * Microbenchmarks in `bench/Bench.hs` (`RQ1`–`RQ19`, 159 benchmarks) enforce strict full-spine `NFData` (`nf`) evaluation.+* **Live Evaluated Reference Baselines (`v0.3.0` Corpus)**:+ * **Canontra**: `v0.4.0.0` (`dist-bin/canontra.exe`) vs `v0.3.0.0` baselines+ * **GitHub CodeQL**: v2.27.0 CLI (`codeql.exe`)+ * **Git**: v2.48.1 (`git hash-object`), **Turborepo** v2.11.2, **Mozilla sccache** v0.8.2 (preserved from identical 15-repo corpus runs in [`researchBenchmarks/v0.3.0_benchmark_comparative_summary.csv`](file:///d:/barista/canontra/researchBenchmarks/v0.3.0_benchmark_comparative_summary.csv))+* **Corpus Scale**: 15 Real-World Open-Source Repositories, **3,182 source files** (`3,097` indexed), **1,026,521 lines of code (LOC)** (counted via `.NET [System.IO.File]::ReadAllLines().Length`)+* **Methodological Integrity**: Zero simulated baseline values; every Canontra `v0.4.0` latency, throughput, hash, and exit code reflects live `-O2` process execution captured cleanly with `.canontra/` reset before cold runs and deleted after evaluation.++## 1. Executive Summary++This report presents empirical measurements for **Canontra `v0.4.0.0` (Release `v0.4.0`)**, covering Phases 1–5 engineering upgrades across 15 production repositories and 159 `tasty-bench` microbenchmarks:++1. **Single-Pass Pipeline Fusion & $O(N^2)$ Removal**: Unified `CanonicalProgram` (`Canontra.Normalize.Normalize`), single-parse `computeManifest`, `Set`/`IntMap` deduplication in `WholeRepoGraph` and `TypeContract`, mutable `MV.IOVector` Chase-Lev deques (`1.14 ms` for 1,000 tasks in RQ15), and ByteString/SIMD lexers (`95.4 us` Go, `137.3 us` JS/TS, `463.9 us` FastPython BS).+2. **4.07× Cold & 9.07× Warm Total Corpus Speedup vs `v0.3.0`**: Across all 15 repositories (`1,026,521` LOC), aggregate cold ingestion dropped from **`135,201.09 ms`** (`135.20 s`) to **`33,181.10 ms`** (`33.18 s`), and aggregate warm ingestion dropped from **`129,102.05 ms`** (`129.10 s`) to **`14,228.02 ms`** (`14.23 s`). Peak cold throughput reached **`68,030 LOC/s`** (`jinja`), with **`59,328 LOC/s`** (`click`) and **`54,996 LOC/s`** (`marshmallow`).+3. **`CNTR\x07` Incremental Slab Cache (`Canontra.Cache.SlabV7`)**: Persists per-file `FileGraphSummary` binary payloads inside 4KB CRC-32C protected slab pages. Summary-backed graph synthesis (`RQ18`) runs in **`112.9 us`** (`F_WCG`) and **`65.6 us`** (`F_WDF`) on 10 modules (**87.3×** and **180.2×** faster than full-AST CSR rebuilding). End-to-end CLI warm caching accelerated `prometheus` (994 files, 408k LOC) by **15.18×** (`57,478.64 ms` $\to$ `3,786.11 ms`), `ripgrep` by **10.40×**, and `gin` by **8.28×**.+4. **9.7× to 205.1× Faster Cold Indexing than GitHub CodeQL**: On `ripgrep`, Canontra `v0.4.0` finished cold indexing in **`1.216 s`** vs CodeQL's **`249.391 s`** (**205.1× faster**); on 408k-LOC `prometheus`, Canontra finished cold in **`12.028 s`** (**86.7× faster**) and warm in **`3.786 s`** (**275.5× faster**) than CodeQL (`1,043.217 s`).+5. **Stateless AI Harness Sub-Versioning (`canontra snap` — Alpha, `0.1-alpha`)**: In-memory 1,000-file snapshot delta checks complete in **`1.73 ms`** (`RQ19`), single-bundle diffs in **`733.1 ns`**, and end-to-end warm CLI `snap mark --skip-noop` invocations complete in **`143.61 ms` – `571.66 ms`** on typical repos (and **`3,978.55 ms`** on 994-file `prometheus`).+6. **100% Execution Reliability**: Zero panics, zero uncaught exceptions, zero null graph digests, and **exit code 0 across all 15 cold, warm, CIA, and `snap` runs**.++## 2. Live Empirical Benchmark Dataset (15 Repositories)++Executed via [`researchBenchmarks/run_v0.4.0_benchmarks.ps1`](file:///d:/barista/canontra/researchBenchmarks/run_v0.4.0_benchmarks.ps1) against [`dist-bin/canontra.exe`](file:///d:/barista/canontra/dist-bin/canontra.exe) (`v0.4.0`).++### Table 1: Canontra `v0.4.0` Ingestion, Warm Cache, CIA 2.0 & `canontra snap` Latency++| Repository | Language | Source Files | Indexed | Total LOC | Cold Latency (`v0.4.0`) | Cold vs `v0.3.0` | Warm Latency (`v0.4.0`) | Warm vs `v0.3.0` | CIA 2.0 (ms) | `snap mark` Warm (ms) | Cold LOC/s | $F_R$ / $F_{WCG}$ / $F_{WDF}$ Prefixes | Exit |+| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :--- | :---: |+| **`bottle`** | Python | 30 | 16 | 9,228 | **339.50 ms** | 3.03× | **290.75 ms** | 3.52× | 462.49 | 325.56 | 27,181 | `066eea6c` / `d0a9f78b` / `3960c7c4` | 0 |+| **`toml`** | Rust | 166 | 166 | 49,698 | **2,291.04 ms** | 2.64× | **1,186.62 ms** | 4.25× | 2,375.24 | 1,288.91 | 21,692 | `f6319c62` / `5445b3e3` / `8dff8088` | 0 |+| **`requests`** | Python | 37 | 21 | 12,032 | **335.08 ms** | 3.02× | **276.05 ms** | 3.66× | 453.52 | 290.19 | 35,908 | `4f6ca7d7` / `f87e69b2` / `7a3f9935` | 0 |+| **`flask`** | Python | 83 | 43 | 18,345 | **607.21 ms** | 3.34× | **435.56 ms** | 4.63× | 761.26 | 440.52 | 30,212 | `91de3959` / `8ec8440f` / `9af98251` | 0 |+| **`marshmallow`** | Python | 38 | 17 | 15,704 | **285.55 ms** | 3.54× | **245.70 ms** | 4.19× | 508.29 | 301.55 | 54,996 | `d004bdec` / `fc571f2c` / `781892b2` | 0 |+| **`chalk`** | JavaScript | 20 | 14 | 2,215 | **135.64 ms** | 7.56× | **103.50 ms** | 9.81× | 287.29 | 143.61 | 16,330 | `34785a97` / `dd544702` / `96c58d9d` | 0 |+| **`click`** | Python | 90 | 54 | 29,121 | **490.85 ms** | 4.12× | **362.07 ms** | 5.57× | 765.02 | 408.79 | 59,328 | `ecccb6e8` / `0e4f5e07` / `5c53bbe9` | 0 |+| **`gin`** | Go | 99 | 99 | 24,226 | **763.45 ms** | 2.65× | **243.88 ms** | 8.28× | 943.15 | 356.78 | 31,732 | `35cbeb98` / `d5daf51d` / `61d355d7` | 0 |+| **`jinja`** | Python | 60 | 25 | 22,875 | **336.25 ms** | 3.01× | **300.64 ms** | 3.38× | 619.61 | 350.97 | **68,030** | `4a5080b6` / `5db1aaea` / `d544cbe3` | 0 |+| **`ripgrep`** | Rust | 110 | 110 | 56,386 | **1,216.22 ms** | 3.32× | **388.11 ms** | 10.40× | 1,632.35 | 477.16 | 46,362 | `4cf1916d` / `049b8842` / `33dc85a7` | 0 |+| **`express`** | JavaScript | 141 | 141 | 21,492 | **1,201.91 ms** | 3.37× | **520.51 ms** | 3.90× | 792.88 | 571.66 | 17,882 | `d15eb48a` / `22f20ad6` / `4c2972c3` | 0 |+| **`rich`** | Python | 213 | 142 | 51,866 | **1,297.27 ms** | **12.43×** | **1,301.98 ms*** | **12.39×** | 4,790.27 | 1,215.36 | 39,981 | `d09ca131` / `35186942` / `65e74c80` | 0 |+| **`hugo`** | Go | 936 | 937 | 235,224 | **9,054.14 ms** | 3.45× | **3,672.67 ms** | 7.68× | 9,106.94 | 5,022.56 | 25,980 | `57209ce8` / `c1b74b39` / `7be96a1f` | 0 |+| **`deno_core`** | TS/Rust | 315 | 318 | 69,692 | **2,799.02 ms** | 1.80× | **1,113.87 ms** | 4.53× | 3,144.59 | 1,352.99 | 24,899 | `bad5e9ce` / `ecc8b549` / `0298785d` | 0 |+| **`prometheus`** | Go | 844 | 994 | 408,417 | **12,027.97 ms** | 4.78× | **3,786.11 ms** | **15.18×** | 11,577.51 | 3,978.55 | 33,956 | `9571da7d` / `2c30a945` / `f00cbbf7` | 0 |+| **Total / Corpus** | **5 Langs** | **3,182** | **3,097** | **1,026,521** | **33,181.10 ms** | **4.07×** | **14,228.02 ms** | **9.07×** | — | — | — | 15 / 15 non-null digests | **0** |++*\*Note on `rich`: 142 of 213 files in `rich` parse and cache into `.canontra/cache.bin`; the remaining 71 test/fixture/doc files with parse warnings are re-checked during warm traversal, yielding `1,301.98 ms` warm vs `1,297.27 ms` cold (`12.39×` faster than `v0.3.0`'s `16,133.07 ms`).* +*Note on `v0.4.0` digests: $F_R$ now incorporates per-module composite $F_4$ digests, $F_{WCG}$ merges Go package directories and TS/JS barrel exports cleanly, and $F_T$ encodes exact ABI scalar widths and mutability, producing distinct `v0.4.0` cryptographic digests relative to `v0.3.0`.*++*Data source: [`researchBenchmarks/v0.4.0_benchmark_summary.csv`](file:///d:/barista/canontra/researchBenchmarks/v0.4.0_benchmark_summary.csv).*++## 3. Live Comparative Benchmark Evaluation across Tools++### Table 2: Comparative Cold Latency (Wall-Clock Seconds)++| Repository | Language | Files | LOC | Canontra `v0.4.0` (s) | Throughput (LOC/s) | Git Hashing (s) | Turborepo (s) | Sccache (s) | CodeQL CLI (s) | Speedup vs CodeQL |+| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |+| **`bottle`** | Python | 30 | 9,228 | **0.340 s** | 27,181 | 1.456 s | 0.031 s | N/A | 18.052 s | **53.1×** |+| **`toml`** | Rust | 166 | 49,698 | **2.291 s** | 21,692 | 7.909 s | 0.177 s | 3.308 s | 279.388 s | **122.0×** |+| **`requests`** | Python | 37 | 12,032 | **0.335 s** | 35,908 | 2.514 s | 0.039 s | N/A | 18.054 s | **53.9×** |+| **`flask`** | Python | 83 | 18,345 | **0.607 s** | 30,212 | 4.212 s | 0.056 s | N/A | 19.060 s | **31.4×** |+| **`marshmallow`** | Python | 38 | 15,704 | **0.286 s** | 54,996 | 1.795 s | 0.051 s | N/A | 17.093 s | **59.8×** |+| **`chalk`** | JavaScript | 20 | 2,215 | **0.136 s** | 16,330 | 0.695 s | 0.140 s | N/A | 22.040 s | **162.1×** |+| **`click`** | Python | 90 | 29,121 | **0.491 s** | 59,328 | 4.074 s | 0.095 s | N/A | 19.057 s | **38.8×** |+| **`gin`** | Go | 99 | 24,226 | **0.763 s** | 31,732 | 4.525 s | 0.082 s | 2.626 s | 25.045 s | **32.8×** |+| **`jinja`** | Python | 60 | 22,875 | **0.336 s** | **68,030** | 2.699 s | 0.075 s | N/A | 19.059 s | **56.7×** |+| **`ripgrep`** | Rust | 110 | 56,386 | **1.216 s** | 46,362 | 4.931 s | 0.204 s | 3.493 s | 249.391 s | **205.1×** |+| **`express`** | JavaScript | 141 | 21,492 | **1.202 s** | 17,882 | 6.732 s | 1.365 s | N/A | 26.056 s | **21.7×** |+| **`rich`** | Python | 213 | 51,866 | **1.297 s** | 39,981 | 9.882 s | 0.183 s | N/A | 29.100 s | **22.4×** |+| **`hugo`** | Go | 936 | 235,224 | **9.054 s** | 25,980 | 42.110 s | 0.812 s | 9.262 s | 266.449 s | **29.4×** |+| **`deno_core`** | TS/Rust | 315 | 69,692 | **2.799 s** | 24,899 | 14.516 s | 1.151 s | 3.829 s | 27.050 s | **9.7×** |+| **`prometheus`** | Go | 844 | 408,417 | **12.028 s** | 33,956 | 47.279 s | 1.552 s | 14.640 s | 1,043.217 s | **86.7×** |++*Data source: [`researchBenchmarks/v0.4.0_benchmark_comparative_summary.csv`](file:///d:/barista/canontra/researchBenchmarks/v0.4.0_benchmark_comparative_summary.csv).*++## 4. Key Micro-Benchmarks (`tasty-bench`, `v0.4.0` Strict `NFData`)++Measured via `canontra-bench` under GHC 9.6.6 `-O2` (full 159-row dataset in [`researchBenchmarks/v0.4.0_microbench_results.csv`](file:///d:/barista/canontra/researchBenchmarks/v0.4.0_microbench_results.csv)):++```text+RQ18: v0.4.0 SlabV7 & Summary Synthesis (10 modules)+ encodeSlabV7Binary (10 modules): 671.4 us (± 902.7 us)+ decodeSlabV7Binary (10 modules): 216.7 us (± 205.7 us)+ lookupSlabV7BinaryBS (Warm Hit): 6.0 us (± 3.4 us)+ buildWholeRepoCallGraphFromSummaries (10 mods): 112.9 us (± 34.6 us)+ buildWholeRepoDataFlowFromSummaries (10 mods): 65.6 us (± 20.7 us)++RQ19: v0.4.0 Stateless AI Harness Sub-Versioning (canontra snap)+ diffFileBundles (9-tier bundle comparison): 733.1 ns (± 588.4 ns)+ computeFileDeltas (1,000 files, 1 dirty): 1.73 ms (± 1.21 ms)+ classifySnapDeltas (dirty delta triage): 19.9 ns (± 3.4 ns)+ parseGuardTiers (F2,F3,F_T): 733.1 ns (± 241.8 ns)+ matchesGlob (**/*.py): 5.9 us (± 7.9 us)+```++For RQ1–RQ17 tables and methodology, see [`BENCHMARKS.md`](file:///d:/barista/canontra/BENCHMARKS.md).++## 5. Preserved Artifacts & Verification Status++All experimental artifacts are generated from live runs and tracked in the repository:++1. **Definitive Report**: [`benchmarkReport.md`](file:///d:/barista/canontra/benchmarkReport.md)+2. **Microbenchmark Reference**: [`BENCHMARKS.md`](file:///d:/barista/canontra/BENCHMARKS.md)+3. **AI Harness Guide (Alpha)**: [`HARNESS.md`](file:///d:/barista/canontra/HARNESS.md)+4. **`v0.4.0` 15-Repo Summary CSV**: [`researchBenchmarks/v0.4.0_benchmark_summary.csv`](file:///d:/barista/canontra/researchBenchmarks/v0.4.0_benchmark_summary.csv)+5. **`v0.4.0` Comparative Summary CSV**: [`researchBenchmarks/v0.4.0_benchmark_comparative_summary.csv`](file:///d:/barista/canontra/researchBenchmarks/v0.4.0_benchmark_comparative_summary.csv)+6. **`v0.4.0` `tasty-bench` CSV (159 rows)**: [`researchBenchmarks/v0.4.0_microbench_results.csv`](file:///d:/barista/canontra/researchBenchmarks/v0.4.0_microbench_results.csv)+7. **Live Multi-Repository Benchmark Runner**: [`researchBenchmarks/run_v0.4.0_benchmarks.ps1`](file:///d:/barista/canontra/researchBenchmarks/run_v0.4.0_benchmarks.ps1)+8. **Production Binary**: `dist-bin/canontra.exe` (`canontra version 0.4.0`)
canontra.cabal view
@@ -1,15 +1,17 @@ cabal-version: 3.0 name: canontra-version: 0.3.0.0+version: 0.4.0.0 synopsis: Deterministic polyglot program identity & semantic graph engine description: @canontra@ is a deterministic polyglot program identity and semantic graph engine written in pure Haskell. It computes multi-tier cryptographic fingerprints and semantic graphs (AST, Call Graph, CFG, DFG, and Merkle DAGs) across Python,- JavaScript, TypeScript, Go, and Rust. Featuring scope-aware bound lexical alpha-normalization,- commutative and associative algebraic equivalence, CFG dominator-tree canonicalization,- deepened structural type contracts, and CSR-native multi-file PR batch change impact analysis,- Canontra eliminates cache busts caused by formatting, comments, and non-semantic code refactorings.+ JavaScript, TypeScript, Go, and Rust. Featuring CNTR\x07 incremental slab caching,+ ByteString/SIMD polyglot lexers, scope-aware bound lexical alpha-normalization,+ commutative and associative algebraic equivalence, Lengauer-Tarjan CFG dominator+ canonicalization, ABI-precise structural type contracts (F_T), CSR-native multi-file+ change impact analysis, and stateless AI harness semantic sub-versioning (@canontra snap@),+ Canontra eliminates cache busts caused by formatting, comments, and non-semantic edits. category: Development, Static Analysis, Code Quality author: Jash Thakkar maintainer: Jash Thakkar@@ -23,6 +25,7 @@ README.md CHANGELOG.md CONTRIBUTING.md+ HARNESS.md technicalSpecs.md BENCHMARKS.md SECURITY.md@@ -109,6 +112,7 @@ Canontra.Cache.MerkleCache Canontra.Cache.PagedCache Canontra.Cache.SlabV6+ Canontra.Cache.SlabV7 Canontra.Fingerprint.Source Canontra.Fingerprint.Structural Canontra.Fingerprint.Declaration@@ -130,6 +134,9 @@ Canontra.Verification.Metamorphic Canontra.Comparison.Compare Canontra.Comparison.Diff+ Canontra.Harness.Store+ Canontra.Harness.SubVersion+ Canontra.Harness.Guard Canontra.Security.Path Canontra.Export.SARIF Canontra.Export.Graph@@ -232,6 +239,7 @@ base, canontra, bytestring,+ containers, text, vector, deepseq,
src/Canontra/Analysis/BatchImpact.hs view
@@ -27,7 +27,6 @@ import Control.DeepSeq (NFData) import Data.Aeson (FromJSON, ToJSON, encode) import qualified Data.ByteString.Lazy as BL-import Data.List (nub, sort) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T@@ -131,8 +130,8 @@ else reachabilityConeNodes (backwardReachabilityCone csr seedIndices) transitiveCallers =- sort $- nub+ Set.toAscList $+ Set.fromList [ callerPath | idx <- coneIndices , Just sym <- [lookupNode idx]@@ -140,10 +139,10 @@ , Set.notMember callerPath level3Set ] - activeSourceFiles = sort (nub (level2 ++ level3 ++ transitiveCallers))+ activeSourceFiles = Set.toAscList (Set.fromList (level2 ++ level3 ++ transitiveCallers)) directModifiedTests = filter isRepoTestFile (level2 ++ level3) matchedTests = findMatchingTests activeSourceFiles normRepoFiles- impactedTests = sort (nub (directModifiedTests ++ matchedTests))+ impactedTests = Set.toAscList (Set.fromList (directModifiedTests ++ matchedTests)) allRepoTests = filter isRepoTestFile normRepoFiles totalTests =@@ -181,8 +180,8 @@ "pytest " <> T.unwords (map T.pack impactedTests) | any (== ".go") exts -> let pkgDirs =- sort $- nub+ Set.toAscList $+ Set.fromList [ let d = normalizeImpactPath (takeDirectory tf) in if d == "." || null d then "./..."
src/Canontra/Analysis/CFG.hs view
@@ -21,6 +21,7 @@ import Control.DeepSeq (NFData) import Data.Aeson (FromJSON, ToJSON) import Data.List (sortBy)+import Data.Maybe (fromMaybe) import Data.Ord (comparing) import Data.Text (Text) import qualified Data.Text as T@@ -104,31 +105,66 @@ -- | Build a ControlFlowGraph for a sequence of statements with entry block 0. buildFunctionCFG :: Text -> [Stmt] -> ControlFlowGraph buildFunctionCFG fnName stmts =- let (blocks, edges, _) = partitionBlocks 0 stmts 1+ let (blocks, edges, _) = partitionBlocksWithDefers [] 0 stmts 1 sortedBlocks = sortBy (comparing bbId) blocks sortedEdges = sortBy (comparing (\e -> (edgeFrom e, edgeTo e, edgeCondition e))) edges in ControlFlowGraph fnName 0 sortedBlocks sortedEdges -partitionBlocks :: BlockId -> [Stmt] -> BlockId -> ([BasicBlock], [CFGEdge], BlockId)-partitionBlocks curId [] nextId =- ([BasicBlock curId [] TermExit], [], nextId)+partitionBlocksWithDefers :: [Expr] -> BlockId -> [Stmt] -> BlockId -> ([BasicBlock], [CFGEdge], BlockId)+partitionBlocksWithDefers defers curId [] nextId+ | null defers = ([BasicBlock curId [] TermExit], [], nextId)+ | otherwise =+ let deferBlockId = nextId+ curBlock = BasicBlock curId [] (TermJump deferBlockId)+ deferBlock = BasicBlock deferBlockId [StmtExpr d | d <- defers] TermExit+ edges =+ [ CFGEdge curId deferBlockId CondUnconditional+ , CFGEdge curId deferBlockId (CondException "defer")+ ]+ in ([curBlock, deferBlock], edges, deferBlockId + 1) -partitionBlocks curId (s:ss) nextId = case s of+partitionBlocksWithDefers defers curId (s:ss) nextId = case s of+ StmtDefer dExpr ->+ let nextDefers = dExpr : defers+ nextBlockId = nextId+ (nextBlocks, nextEdges, nextId1) = partitionBlocksWithDefers nextDefers nextBlockId ss (nextBlockId + 1)+ thisBlock = BasicBlock curId [StmtDefer dExpr] (TermJump nextBlockId)+ edges =+ [ CFGEdge curId nextBlockId CondUnconditional+ , CFGEdge curId nextBlockId (CondException "defer")+ ] ++ nextEdges+ in (thisBlock : nextBlocks, edges, nextId1)+ StmtReturn me ->- let block = BasicBlock curId [StmtReturn me] (TermReturn me)- in ([block], [], nextId)+ if null defers+ then ([BasicBlock curId [StmtReturn me] (TermReturn me)], [], nextId)+ else+ let deferBlockId = nextId+ curBlock = BasicBlock curId [StmtReturn me] (TermJump deferBlockId)+ deferBlock = BasicBlock deferBlockId [StmtExpr d | d <- defers] (TermReturn me)+ edges =+ [ CFGEdge curId deferBlockId CondUnconditional+ , CFGEdge curId deferBlockId (CondException "defer")+ ]+ in ([curBlock, deferBlock], edges, deferBlockId + 1) StmtRaise me _ ->- let block = BasicBlock curId [StmtRaise me Nothing] (TermRaise me)- in ([block], [], nextId)+ if null defers+ then ([BasicBlock curId [StmtRaise me Nothing] (TermRaise me)], [], nextId)+ else+ let deferBlockId = nextId+ curBlock = BasicBlock curId [StmtRaise me Nothing] (TermJump deferBlockId)+ deferBlock = BasicBlock deferBlockId [StmtExpr d | d <- defers] (TermRaise me)+ edges = [CFGEdge curId deferBlockId (CondException "defer")]+ in ([curBlock, deferBlock], edges, deferBlockId + 1) StmtIf cond thenStmts elseStmts -> let thenBlockId = nextId- (thenBlocks, thenEdges, nextId1) = partitionBlocks thenBlockId thenStmts (thenBlockId + 1)+ (thenBlocks, thenEdges, nextId1) = partitionBlocksWithDefers defers thenBlockId thenStmts (thenBlockId + 1) elseBlockId = nextId1- (elseBlocks, elseEdges, nextId2) = partitionBlocks elseBlockId elseStmts (elseBlockId + 1)+ (elseBlocks, elseEdges, nextId2) = partitionBlocksWithDefers defers elseBlockId elseStmts (elseBlockId + 1) joinBlockId = nextId2- (joinBlocks, joinEdges, nextId3) = partitionBlocks joinBlockId ss (joinBlockId + 1)+ (joinBlocks, joinEdges, nextId3) = partitionBlocksWithDefers defers joinBlockId ss (joinBlockId + 1) (condBlocks, condEdges, nextId4) = decomposeCondition curId cond thenBlockId elseBlockId nextId3 joinFromThen = [CFGEdge thenBlockId joinBlockId CondUnconditional | not (null ss)]@@ -140,9 +176,9 @@ StmtWhile cond bodyStmts elseStmts -> let bodyBlockId = nextId- (bodyBlocks, bodyEdges, nextId1) = partitionBlocks bodyBlockId bodyStmts (bodyBlockId + 1)+ (bodyBlocks, bodyEdges, nextId1) = partitionBlocksWithDefers defers bodyBlockId bodyStmts (bodyBlockId + 1) exitBlockId = nextId1- (exitBlocks, exitEdges, nextId2) = partitionBlocks exitBlockId (elseStmts ++ ss) (exitBlockId + 1)+ (exitBlocks, exitEdges, nextId2) = partitionBlocksWithDefers defers exitBlockId (elseStmts ++ ss) (exitBlockId + 1) (condBlocks, condEdges, nextId3) = decomposeCondition curId cond bodyBlockId exitBlockId nextId2 edges = condEdges ++ [CFGEdge bodyBlockId curId CondUnconditional] ++ bodyEdges ++ exitEdges@@ -151,9 +187,9 @@ StmtFor _ iter bodyStmts elseStmts -> let bodyBlockId = nextId- (bodyBlocks, bodyEdges, nextId1) = partitionBlocks bodyBlockId bodyStmts (bodyBlockId + 1)+ (bodyBlocks, bodyEdges, nextId1) = partitionBlocksWithDefers defers bodyBlockId bodyStmts (bodyBlockId + 1) exitBlockId = nextId1- (exitBlocks, exitEdges, nextId2) = partitionBlocks exitBlockId (elseStmts ++ ss) (exitBlockId + 1)+ (exitBlocks, exitEdges, nextId2) = partitionBlocksWithDefers defers exitBlockId (elseStmts ++ ss) (exitBlockId + 1) headerBlock = BasicBlock curId [] (TermBranch iter bodyBlockId exitBlockId) edges =@@ -166,7 +202,7 @@ StmtLoop bodyStmts -> let bodyBlockId = nextId- (bodyBlocks, bodyEdges, nextId1) = partitionBlocks bodyBlockId bodyStmts (bodyBlockId + 1)+ (bodyBlocks, bodyEdges, nextId1) = partitionBlocksWithDefers defers bodyBlockId bodyStmts (bodyBlockId + 1) headerBlock = BasicBlock curId [] (TermJump bodyBlockId) edges = [CFGEdge curId bodyBlockId CondUnconditional, CFGEdge bodyBlockId curId CondUnconditional] ++ bodyEdges in (headerBlock : bodyBlocks, edges, nextId1)@@ -174,7 +210,7 @@ StmtSwitch expr cases defaultStmts -> let (caseBlocks, caseEdges, caseTerms, nextId1) = foldl stepCase ([], [], [], nextId) cases exitBlockId = nextId1- (defBlocks, defEdges, nextId2) = partitionBlocks exitBlockId (defaultStmts ++ ss) (exitBlockId + 1)+ (defBlocks, defEdges, nextId2) = partitionBlocksWithDefers defers exitBlockId (defaultStmts ++ ss) (exitBlockId + 1) headerBlock = BasicBlock curId [] (TermSwitch expr caseTerms (Just exitBlockId)) caseHeaderEdges = [CFGEdge curId bId (CondCase cExpr) | (cExpr, bId) <- caseTerms] defHeaderEdge = CFGEdge curId exitBlockId CondDefault@@ -184,13 +220,13 @@ where stepCase (bAcc, eAcc, tAcc, nId) (cExpr, cStmts) = let cBlockId = nId- (cBlocks, cEdges, nId1) = partitionBlocks cBlockId cStmts (cBlockId + 1)+ (cBlocks, cEdges, nId1) = partitionBlocksWithDefers defers cBlockId cStmts (cBlockId + 1) in (bAcc ++ cBlocks, eAcc ++ cEdges, tAcc ++ [(cExpr, cBlockId)], nId1) StmtMatch expr cases -> let (caseBlocks, caseEdges, caseTerms, nextId1) = foldl stepCase ([], [], [], nextId) cases exitBlockId = nextId1- (exitBlocks, exitEdges, nextId2) = partitionBlocks exitBlockId ss (exitBlockId + 1)+ (exitBlocks, exitEdges, nextId2) = partitionBlocksWithDefers defers exitBlockId ss (exitBlockId + 1) headerBlock = BasicBlock curId [] (TermSwitch expr caseTerms (Just exitBlockId)) caseHeaderEdges = [CFGEdge curId bId (CondCase cExpr) | (cExpr, bId) <- caseTerms] allBlocks = headerBlock : (caseBlocks ++ exitBlocks)@@ -199,19 +235,19 @@ where stepCase (bAcc, eAcc, tAcc, nId) mc = let cBlockId = nId- (cBlocks, cEdges, nId1) = partitionBlocks cBlockId (mcBody mc) (cBlockId + 1)+ (cBlocks, cEdges, nId1) = partitionBlocksWithDefers defers cBlockId (mcBody mc) (cBlockId + 1) in (bAcc ++ cBlocks, eAcc ++ cEdges, tAcc ++ [(mcPattern mc, cBlockId)], nId1) StmtTry tryBody handlers elseBody finallyBody -> let joinBlockId = nextId- (joinBlocks, joinEdges, nextId1) = partitionBlocks joinBlockId ss (joinBlockId + 1)+ (joinBlocks, joinEdges, nextId1) = partitionBlocksWithDefers defers joinBlockId ss (joinBlockId + 1) (hasFinally, finBlockId, finBlocks, finEdges, nextId2) = if null finallyBody then (False, joinBlockId, [], [], nextId1) else let fId = nextId1- (fBlocks, fEdges, n2) = partitionBlocks fId finallyBody (fId + 1)+ (fBlocks, fEdges, n2) = partitionBlocksWithDefers defers fId finallyBody (fId + 1) fJoinEdge = [CFGEdge fId joinBlockId CondUnconditional | not (null ss)] in (True, fId, fBlocks, fEdges ++ fJoinEdge, n2) @@ -222,7 +258,7 @@ then (afterTryTarget, [], [], nextId2) else let eId = nextId2- (eBlocks, eEdges, n3) = partitionBlocks eId elseBody (eId + 1)+ (eBlocks, eEdges, n3) = partitionBlocksWithDefers defers eId elseBody (eId + 1) eTargetEdge = [CFGEdge eId afterTryTarget CondUnconditional] in (eId, eBlocks, eEdges ++ eTargetEdge, n3) @@ -230,7 +266,7 @@ foldl (stepHandler afterTryTarget) ([], [], [], nextId3) handlers tryBlockId = nextId4- (tryBlocks, tryEdges, nextId5) = partitionBlocks tryBlockId tryBody (tryBlockId + 1)+ (tryBlocks, tryEdges, nextId5) = partitionBlocksWithDefers defers tryBlockId tryBody (tryBlockId + 1) entryBlock = BasicBlock curId [] (TermJump tryBlockId) entryEdge = CFGEdge curId tryBlockId CondUnconditional@@ -262,38 +298,61 @@ where stepHandler targetId (bAcc, eAcc, hAcc, nId) (mExcExpr, _, hStmts) = let hBlockId = nId- (hBlocks, hEdges, nId1) = partitionBlocks hBlockId hStmts (hBlockId + 1)+ (hBlocks, hEdges, nId1) = partitionBlocksWithDefers defers hBlockId hStmts (hBlockId + 1) hExitEdge = [CFGEdge hBlockId targetId CondUnconditional] in (bAcc ++ hBlocks, eAcc ++ hEdges ++ hExitEdge, hAcc ++ [(mExcExpr, hBlockId)], nId1) StmtWith items body ->- partitionDisposalBlock curId items body ss nextId False+ partitionDisposalBlock defers curId items body ss nextId False StmtAsyncWith items body ->- partitionDisposalBlock curId items body ss nextId True+ partitionDisposalBlock defers curId items body ss nextId True + _ | stmtHasTryOp s ->+ let tryExpr = fromMaybe (ExprTryOp (ExprId "?")) (findStmtTryOp s)+ okBlockId = nextId+ errBlockId = okBlockId + 1+ errBlock = BasicBlock errBlockId [StmtExpr d | d <- defers] (TermReturn Nothing)+ (okBlocks, okEdges, nextId1) = partitionBlocksWithDefers defers okBlockId ss (errBlockId + 1)+ curBlock = BasicBlock curId [s] (TermBranch tryExpr okBlockId errBlockId)+ tryEdges =+ [ CFGEdge curId okBlockId (CondTrue tryExpr)+ , CFGEdge curId errBlockId (CondException "?")+ ]+ in (curBlock : errBlock : okBlocks, tryEdges ++ okEdges, nextId1)+ _ -> -- Collect non-branching statements into current block let (linear, rest) = span isLinearStmt (s:ss) in case rest of [] ->- ([BasicBlock curId linear TermExit], [], nextId)+ if null defers+ then ([BasicBlock curId linear TermExit], [], nextId)+ else+ let deferBlockId = nextId+ thisBlock = BasicBlock curId linear (TermJump deferBlockId)+ deferBlock = BasicBlock deferBlockId [StmtExpr d | d <- defers] TermExit+ edges =+ [ CFGEdge curId deferBlockId CondUnconditional+ , CFGEdge curId deferBlockId (CondException "defer")+ ]+ in ([thisBlock, deferBlock], edges, deferBlockId + 1) (r:rs) -> let nextBlockId = nextId- (nextBlocks, nextEdges, nextId1) = partitionBlocks nextBlockId (r:rs) (nextBlockId + 1)+ (nextBlocks, nextEdges, nextId1) = partitionBlocksWithDefers defers nextBlockId (r:rs) (nextBlockId + 1) thisBlock = BasicBlock curId linear (TermJump nextBlockId) edge = CFGEdge curId nextBlockId CondUnconditional in (thisBlock : nextBlocks, edge : nextEdges, nextId1) -partitionDisposalBlock :: BlockId -> [(Expr, Maybe Expr)] -> [Stmt] -> [Stmt] -> BlockId -> Bool -> ([BasicBlock], [CFGEdge], BlockId)-partitionDisposalBlock curId items body ss nextId _isAsync =+partitionDisposalBlock :: [Expr] -> BlockId -> [(Expr, Maybe Expr)] -> [Stmt] -> [Stmt] -> BlockId -> Bool -> ([BasicBlock], [CFGEdge], BlockId)+partitionDisposalBlock defers curId items body ss nextId _isAsync = let resourceStmts = [StmtAssign (maybe [] pure mTarget) resExpr | (resExpr, mTarget) <- items] bodyBlockId = nextId- (bodyBlocks, bodyEdges, nextId1) = partitionBlocks bodyBlockId body (bodyBlockId + 1)+ (bodyBlocks, bodyEdges, nextId1) = partitionBlocksWithDefers defers bodyBlockId body (bodyBlockId + 1) cleanupBlockId = nextId1 joinBlockId = cleanupBlockId + 1 cleanupBlock = BasicBlock cleanupBlockId [] (TermJump joinBlockId)- (joinBlocks, joinEdges, nextId2) = partitionBlocks joinBlockId ss (joinBlockId + 1)+ (joinBlocks, joinEdges, nextId2) = partitionBlocksWithDefers defers joinBlockId ss (joinBlockId + 1) entryBlock = BasicBlock curId resourceStmts (TermJump bodyBlockId) entryEdge = CFGEdge curId bodyBlockId CondUnconditional@@ -330,21 +389,51 @@ formatExcExpr (Just (ExprAttr _ name)) = name formatExcExpr (Just _) = "*" +stmtHasTryOp :: Stmt -> Bool+stmtHasTryOp s = case findStmtTryOp s of+ Just _ -> True+ Nothing -> False++findStmtTryOp :: Stmt -> Maybe Expr+findStmtTryOp = \case+ StmtAssign _ e -> findExprTryOp e+ StmtAnnAssign _ _ mE -> mE >>= findExprTryOp+ StmtAugAssign _ _ e -> findExprTryOp e+ StmtExpr e -> findExprTryOp e+ StmtAssert e _ -> findExprTryOp e+ _ -> Nothing++findExprTryOp :: Expr -> Maybe Expr+findExprTryOp = \case+ ExprTryOp e -> Just (ExprTryOp e)+ ExprBinary _ a b -> case findExprTryOp a of Just r -> Just r; Nothing -> findExprTryOp b+ ExprUnary _ a -> findExprTryOp a+ ExprCall f args kw -> foldl pick (findExprTryOp f) (map findExprTryOp args ++ map (findExprTryOp . snd) kw)+ ExprAttr e _ -> findExprTryOp e+ ExprAwait e -> findExprTryOp e+ _ -> Nothing+ where+ pick (Just x) _ = Just x+ pick Nothing y = y+ isLinearStmt :: Stmt -> Bool-isLinearStmt = \case- StmtIf {} -> False- StmtWhile {} -> False- StmtFor {} -> False- StmtAsyncFor {} -> False- StmtLoop {} -> False- StmtReturn {} -> False- StmtRaise {} -> False- StmtMatch {} -> False- StmtSwitch {} -> False- StmtTry {} -> False- StmtWith {} -> False- StmtAsyncWith {} -> False- _ -> True+isLinearStmt s+ | stmtHasTryOp s = False+ | otherwise = case s of+ StmtIf {} -> False+ StmtWhile {} -> False+ StmtFor {} -> False+ StmtAsyncFor {} -> False+ StmtLoop {} -> False+ StmtDefer {} -> False+ StmtReturn {} -> False+ StmtRaise {} -> False+ StmtMatch {} -> False+ StmtSwitch {} -> False+ StmtTry {} -> False+ StmtWith {} -> False+ StmtAsyncWith {} -> False+ _ -> True formatCFG :: ControlFlowGraph -> Text formatCFG cfg =
src/Canontra/Analysis/CFGCanonical.hs view
@@ -18,6 +18,8 @@ -} module Canontra.Analysis.CFGCanonical ( canonicalizeCFGRPO+ , computeDominators+ , computeDominanceFrontiers , normalizeBranchConditions , pruneDeadBlocks , relabelRPO@@ -28,6 +30,9 @@ , terminatesUnconditionally ) where +import Control.Monad (forM_, when)+import Control.Monad.ST (ST, runST)+import qualified Data.IntMap.Strict as IM import Data.List (sortBy) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map@@ -35,6 +40,8 @@ import Data.Ord (comparing) import Data.Set (Set) import qualified Data.Set as Set+import qualified Data.Vector.Unboxed.Mutable as MVU+import Data.STRef (modifySTRef', newSTRef, readSTRef, writeSTRef) import Canontra.Analysis.CFG ( BasicBlock (..)@@ -223,14 +230,196 @@ _ -> Nothing -- ------------------------------------------------------------------------------ 2. CFG-Level Dominator / RPO & Branch Inversion Canonicalization+-- 2. Lengauer-Tarjan Dominator Tree & Dominance Frontiers -- --------------------------------------------------------------------------- +-- | Compute the immediate dominator map (@BlockId -> idom BlockId@) for all basic blocks+-- reachable from 'cfgEntry' using the Lengauer-Tarjan algorithm in near-linear time+-- via mutable unboxed ST arrays and link-eval path compression.+computeDominators :: ControlFlowGraph -> Map BlockId BlockId+computeDominators cfg = runST $ do+ let entryId = cfgEntry cfg+ blockIds = Set.toAscList $ Set.fromList $ entryId : map bbId (cfgBlocks cfg)+ numAll = length blockIds+ if numAll == 0+ then pure Map.empty+ else do+ let idToDense = IM.fromList (zip blockIds [0 .. numAll - 1])+ succDense = IM.fromListWith (++)+ [ (uD, [vD])+ | e <- cfgEdges cfg+ , Just uD <- [IM.lookup (edgeFrom e) idToDense]+ , Just vD <- [IM.lookup (edgeTo e) idToDense]+ ]+ entryD = IM.findWithDefault 0 entryId idToDense+ blockArr = IM.fromList (zip [0 .. numAll - 1] blockIds)++ -- Lengauer-Tarjan state arrays indexed by dense node id (0..numAll-1)+ dfnum <- MVU.replicate numAll (-1 :: Int)+ parent <- MVU.replicate numAll (-1 :: Int)+ semi <- MVU.replicate numAll (-1 :: Int)+ ancestor <- MVU.replicate numAll (-1 :: Int)+ best <- MVU.replicate numAll (-1 :: Int)+ idom <- MVU.replicate numAll (-1 :: Int)+ samedom <- MVU.replicate numAll (-1 :: Int)+ vertex <- MVU.replicate numAll (-1 :: Int)+ predsRef <- MVU.replicate numAll (0 :: Int)+ _ <- MVU.read predsRef 0+ bucketRef <- newSTRef (IM.empty :: IM.IntMap [Int])+ predsMapRef <- newSTRef (IM.empty :: IM.IntMap [Int])+ cntRef <- newSTRef (0 :: Int)++ let dfs p u = do+ d <- MVU.read dfnum u+ when (d == -1) $ do+ curN <- readSTRef cntRef+ writeSTRef cntRef (curN + 1)+ MVU.write dfnum u curN+ MVU.write vertex curN u+ MVU.write semi u u+ MVU.write best u u+ MVU.write parent u p+ forM_ (IM.findWithDefault [] u succDense) $ \v -> do+ modifySTRef' predsMapRef (IM.insertWith (++) v [u])+ dfs u v++ dfs (-1) entryD+ nReach <- readSTRef cntRef+ predsMap <- readSTRef predsMapRef++ let link anc v = MVU.write ancestor v anc++ compress v = do+ a <- MVU.read ancestor v+ when (a /= -1) $ do+ aa <- MVU.read ancestor a+ when (aa /= -1) $ do+ compress a+ bV <- MVU.read best v+ bA <- MVU.read best a+ sBV <- MVU.read semi bV+ sBA <- MVU.read semi bA+ dSBV <- MVU.read dfnum sBV+ dSBA <- MVU.read dfnum sBA+ when (dSBA < dSBV) $+ MVU.write best v bA+ aa' <- MVU.read ancestor a+ MVU.write ancestor v aa'++ eval v = do+ a <- MVU.read ancestor v+ if a == -1+ then pure v+ else do+ compress v+ MVU.read best v++ -- Process vertices in reverse DFS order (skip root dfnum == 0)+ forM_ [nReach - 1, nReach - 2 .. 1] $ \i -> do+ n <- MVU.read vertex i+ p <- MVU.read parent n+ let ps = IM.findWithDefault [] n predsMap+ sInit <- foldrM_LT+ (\v sCur -> do+ dV <- MVU.read dfnum v+ if dV == -1+ then pure sCur+ else do+ u' <- eval v+ sU' <- MVU.read semi u'+ dSU' <- MVU.read dfnum sU'+ dSCur <- MVU.read dfnum sCur+ pure (if dSU' < dSCur then sU' else sCur))+ p+ ps+ MVU.write semi n sInit+ modifySTRef' bucketRef (IM.insertWith (++) sInit [n])+ link p n+ bMap <- readSTRef bucketRef+ let pBucket = IM.findWithDefault [] p bMap+ modifySTRef' bucketRef (IM.delete p)+ forM_ pBucket $ \v -> do+ u <- eval v+ sU <- MVU.read semi u+ sV <- MVU.read semi v+ dSU <- MVU.read dfnum sU+ dSV <- MVU.read dfnum sV+ if dSU < dSV+ then MVU.write samedom v u+ else MVU.write idom v p++ -- Second pass: resolve deferred same-dominator nodes+ forM_ [1 .. nReach - 1] $ \i -> do+ n <- MVU.read vertex i+ sd <- MVU.read samedom n+ when (sd /= -1) $ do+ idomSD <- MVU.read idom sd+ MVU.write idom n idomSD++ -- Collect final Map BlockId BlockId+ let collect i acc+ | i >= nReach = pure acc+ | otherwise = do+ n <- MVU.read vertex i+ let origN = IM.findWithDefault entryId n blockArr+ if i == 0+ then collect (i + 1) (Map.insert origN origN acc)+ else do+ domD <- MVU.read idom n+ let origDom = if domD >= 0 then IM.findWithDefault entryId domD blockArr else entryId+ collect (i + 1) (Map.insert origN origDom acc)+ collect 0 Map.empty+ where+ foldrM_LT :: (Int -> Int -> ST s Int) -> Int -> [Int] -> ST s Int+ foldrM_LT _ acc [] = pure acc+ foldrM_LT f acc (x:xs) = do+ acc' <- foldrM_LT f acc xs+ f x acc'++-- | Compute the Dominance Frontier (@DF[b]@) for every reachable basic block using+-- the Cooper-Harvey-Kennedy iterative predecessor-walk algorithm.+computeDominanceFrontiers+ :: ControlFlowGraph+ -> Map BlockId BlockId+ -> Map BlockId (Set BlockId)+computeDominanceFrontiers cfg idomMap =+ let reachableSet = Map.keysSet idomMap+ predsMap =+ Map.fromListWith (++)+ [ (edgeTo e, [edgeFrom e])+ | e <- cfgEdges cfg+ , Set.member (edgeFrom e) reachableSet+ , Set.member (edgeTo e) reachableSet+ ]+ joinWalk acc b p+ | p == cfgEntry cfg && Map.lookup b idomMap == Just p = acc+ | otherwise =+ case Map.lookup b idomMap of+ Nothing -> acc+ Just idomB ->+ if p == idomB+ then acc+ else+ let acc' = Map.insertWith Set.union p (Set.singleton b) acc+ in case Map.lookup p idomMap of+ Just nextP | nextP /= p -> joinWalk acc' b nextP+ _ -> acc'+ stepBlock acc b =+ let ps = Map.findWithDefault [] b predsMap+ in if length ps >= 2+ then foldl (\m p -> joinWalk m b p) acc ps+ else acc+ in foldl stepBlock Map.empty (Set.toList reachableSet)++-- ---------------------------------------------------------------------------+-- 3. CFG-Level Dominator / RPO & Branch Inversion Canonicalization+-- ---------------------------------------------------------------------------+ -- | Canonicalize a 'ControlFlowGraph' by: -- 1. Normalizing inverted branch terminators and edge conditions -- 2. Pruning spurious post-terminator edges and unreachable basic blocks -- 3. Contracting trivial empty jump-only trampoline blocks--- 4. Relabeling all reachable basic blocks in deterministic Reverse Post-Order (RPO)+-- 4. Relabeling all reachable basic blocks in deterministic dominator-guided RPO (0 .. k-1) canonicalizeCFGRPO :: ControlFlowGraph -> ControlFlowGraph canonicalizeCFGRPO = relabelRPO@@ -365,14 +554,23 @@ ] in pruneDeadBlocks (cfg { cfgBlocks = blocks', cfgEdges = edges' }) --- | Relabel all basic blocks and edges in deterministic Reverse Post-Order (RPO)+-- | Relabel all basic blocks and edges in deterministic dominator-guided Reverse Post-Order (RPO) -- starting from 'cfgEntry' (assigned BlockId 0). relabelRPO :: ControlFlowGraph -> ControlFlowGraph relabelRPO cfg = let blockMap = Map.fromList [(bbId b, b) | b <- cfgBlocks cfg]- -- Order outgoing edges deterministically: CondTrue before CondFalse, then cases, then unconditional, then exceptions+ idomMap = computeDominators cfg+ domChildren =+ Map.fromListWith Set.union+ [ (p, Set.singleton b)+ | (b, p) <- Map.toList idomMap+ , b /= p+ ]+ -- Order outgoing edges deterministically: CondTrue before CondFalse, prioritizing dominator tree children outEdgesMap =- Map.map (sortBy (comparing edgeOrderKey)) $+ Map.mapWithKey (\u es ->+ let dKids = Map.findWithDefault Set.empty u domChildren+ in sortBy (comparing (\e -> (edgeOrderKey e, not (Set.member (edgeTo e) dKids)))) es) $ Map.fromListWith (++) [ (edgeFrom e, [e]) | e <- cfgEdges cfg
src/Canontra/Analysis/DFG.hs view
@@ -24,11 +24,15 @@ , updateStack , pushScope , popScope+ , mergeBranchDefs+ , mergeMultiBranchDefs+ , collectModifiedVars+ , computeLoopPhiVars ) where import Control.DeepSeq (NFData) import Data.Aeson (FromJSON, ToJSON)-import Data.List (sortBy)+import Data.List (foldl', sortBy) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Ord (comparing)@@ -43,6 +47,29 @@ import Canontra.IR.Program import Canontra.Normalize.Alpha (canonicalizeAlphaProgram) +-- | Difference list for O(1) append without quadratic list concatenation.+type DList a = [a] -> [a]++{-# INLINE dlEmpty #-}+dlEmpty :: DList a+dlEmpty = id++{-# INLINE dlSingleton #-}+dlSingleton :: a -> DList a+dlSingleton x = (x :)++{-# INLINE dlFromList #-}+dlFromList :: [a] -> DList a+dlFromList xs = (xs ++)++{-# INLINE dlAppend #-}+dlAppend :: DList a -> DList a -> DList a+dlAppend = (.)++{-# INLINE dlToList #-}+dlToList :: DList a -> [a]+dlToList dl = dl []+ type NodeId = Int data DefUseKind@@ -138,13 +165,14 @@ setupParams :: [Parameter] -> NodeId -> ([DFGNode], Map Text NodeId, NodeId) setupParams params startId =- foldl step ([], Map.empty, startId) (zip [0..] params)+ let (nodesDL, defs, nextId) = foldl' step (dlEmpty, Map.empty, startId) (zip [0..] params)+ in (dlToList nodesDL, defs, nextId) where step (nodes, defs, curId) (idx, p) = let pName = paramName p node = DFGNode curId (DefParam idx) (Just (ExprId pName)) newDefs = Map.insert pName curId defs- in (nodes ++ [node], newDefs, curId + 1)+ in (nodes `dlAppend` dlSingleton node, newDefs, curId + 1) processStmts :: Map Text NodeId -> [Stmt] -> NodeId -> ([DFGNode], [DFGEdge], NodeId) processStmts activeDefs stmts startId =@@ -153,36 +181,49 @@ processStmtsWithStack :: ScopeStack -> [Stmt] -> NodeId -> ([DFGNode], [DFGEdge], ScopeStack, NodeId) processStmtsWithStack initialStack stmts startId =- foldl step ([], [], initialStack, startId) stmts+ let (nodesDL, edgesDL, finalStack, nextId) = foldl' step (dlEmpty, dlEmpty, initialStack, startId) stmts+ in (dlToList nodesDL, dlToList edgesDL, finalStack, nextId) where+ mkDefNodes :: Maybe Expr -> NodeId -> [Text] -> ([DFGNode], NodeId)+ mkDefNodes mExpr initId vars =+ let (nsDL, endId) = foldl' (\(ns, cId) v ->+ (ns `dlAppend` dlSingleton (DFGNode cId (DefAssignment v) mExpr), cId + 1)) (dlEmpty, initId) vars+ in (dlToList nsDL, endId)+ step (nodesAcc, edgesAcc, curStack, curId) stmt = case stmt of StmtAssign targets val -> let (useNodes, useEdges, nextId1) = extractExprUsesStack curStack val curId assignedVars = concatMap extractTargetVars targets walrusVars = collectWalrusDefs val allDefs = assignedVars ++ walrusVars- (defNodes, nextId2) = foldl (\(ns, cId) v ->- (ns ++ [DFGNode cId (DefAssignment v) (Just val)], cId + 1)) ([], nextId1) allDefs+ (defNodes, nextId2) = mkDefNodes (Just val) nextId1 allDefs defEdges = [ DFGEdge (dfgNodeId srcNode) (dfgNodeId targetNode) v | (targetNode, v) <- zip defNodes allDefs , srcNode <- useNodes ]- newStack = foldl (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes allDefs)- in (nodesAcc ++ useNodes ++ defNodes, edgesAcc ++ useEdges ++ defEdges, newStack, nextId2)+ newStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes allDefs)+ in ( nodesAcc `dlAppend` dlFromList useNodes `dlAppend` dlFromList defNodes+ , edgesAcc `dlAppend` dlFromList useEdges `dlAppend` dlFromList defEdges+ , newStack+ , nextId2+ ) StmtAnnAssign target _ mVal -> let assignedVars = extractTargetVars target (useNodes, useEdges, nextId1) = maybe ([], [], curId) (\val -> extractExprUsesStack curStack val curId) mVal walrusVars = maybe [] collectWalrusDefs mVal allDefs = assignedVars ++ walrusVars- (defNodes, nextId2) = foldl (\(ns, cId) v ->- (ns ++ [DFGNode cId (DefAssignment v) mVal], cId + 1)) ([], nextId1) allDefs+ (defNodes, nextId2) = mkDefNodes mVal nextId1 allDefs defEdges = [ DFGEdge (dfgNodeId srcNode) (dfgNodeId targetNode) v | (targetNode, v) <- zip defNodes allDefs , srcNode <- useNodes ]- newStack = foldl (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes allDefs)- in (nodesAcc ++ useNodes ++ defNodes, edgesAcc ++ useEdges ++ defEdges, newStack, nextId2)+ newStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes allDefs)+ in ( nodesAcc `dlAppend` dlFromList useNodes `dlAppend` dlFromList defNodes+ , edgesAcc `dlAppend` dlFromList useEdges `dlAppend` dlFromList defEdges+ , newStack+ , nextId2+ ) StmtAugAssign target op val -> let combinedExpr = ExprBinary op target val@@ -190,73 +231,82 @@ assignedVars = extractTargetVars target walrusVars = collectWalrusDefs val allDefs = assignedVars ++ walrusVars- (defNodes, nextId2) = foldl (\(ns, cId) v ->- (ns ++ [DFGNode cId (DefAssignment v) (Just combinedExpr)], cId + 1)) ([], nextId1) allDefs+ (defNodes, nextId2) = mkDefNodes (Just combinedExpr) nextId1 allDefs defEdges = [ DFGEdge (dfgNodeId srcNode) (dfgNodeId targetNode) v | (targetNode, v) <- zip defNodes allDefs , srcNode <- useNodes ]- newStack = foldl (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes allDefs)- in (nodesAcc ++ useNodes ++ defNodes, edgesAcc ++ useEdges ++ defEdges, newStack, nextId2)+ newStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes allDefs)+ in ( nodesAcc `dlAppend` dlFromList useNodes `dlAppend` dlFromList defNodes+ , edgesAcc `dlAppend` dlFromList useEdges `dlAppend` dlFromList defEdges+ , newStack+ , nextId2+ ) StmtReturn mVal -> let (useNodes, useEdges, nextId1) = maybe ([], [], curId) (\val -> extractExprUsesStack curStack val curId) mVal- in (nodesAcc ++ useNodes, edgesAcc ++ useEdges, curStack, nextId1)+ in (nodesAcc `dlAppend` dlFromList useNodes, edgesAcc `dlAppend` dlFromList useEdges, curStack, nextId1) StmtIf cond thenB elseB -> let (cNodes, cEdges, nextId1) = extractExprUsesStack curStack cond curId walrusVars = collectWalrusDefs cond- (wNodes, nextId1_w) = foldl (\(ns, cId) v ->- (ns ++ [DFGNode cId (DefAssignment v) (Just cond)], cId + 1)) ([], nextId1) walrusVars- condStack = foldl (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip wNodes walrusVars)+ (wNodes, nextId1_w) = mkDefNodes (Just cond) nextId1 walrusVars+ condStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip wNodes walrusVars) (tNodes, tEdges, thenStack, nextId2) = processStmtsWithStack condStack thenB nextId1_w (eNodes, eEdges, elseStack, nextId3) = processStmtsWithStack condStack elseB nextId2 (phiNodes, phiEdges, mergedStack, nextId4) = mergeBranchDefs condStack thenStack elseStack nextId3- in ( nodesAcc ++ cNodes ++ wNodes ++ tNodes ++ eNodes ++ phiNodes- , edgesAcc ++ cEdges ++ tEdges ++ eEdges ++ phiEdges+ in ( nodesAcc `dlAppend` dlFromList cNodes `dlAppend` dlFromList wNodes `dlAppend` dlFromList tNodes `dlAppend` dlFromList eNodes `dlAppend` dlFromList phiNodes+ , edgesAcc `dlAppend` dlFromList cEdges `dlAppend` dlFromList tEdges `dlAppend` dlFromList eEdges `dlAppend` dlFromList phiEdges , mergedStack , nextId4 ) StmtWhile cond body elseB ->- let (cNodes, cEdges, nextId1) = extractExprUsesStack curStack cond curId+ let loopModVars = collectModifiedVars body+ (phiHeaders, headerStack, nextId1) = allocLoopHeaderPhis curStack loopModVars Set.empty curId+ (cNodes, cEdges, nextId2) = extractExprUsesStack headerStack cond nextId1 walrusVars = collectWalrusDefs cond- (wNodes, nextId1_w) = foldl (\(ns, cId) v ->- (ns ++ [DFGNode cId (DefAssignment v) (Just cond)], cId + 1)) ([], nextId1) walrusVars- condStack = foldl (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip wNodes walrusVars)- (bNodes, bEdges, bodyStack, nextId2) = processStmtsWithStack condStack body nextId1_w- (eNodes, eEdges, elseStack, nextId3) = processStmtsWithStack condStack elseB nextId2- (phiNodes, phiEdges, mergedStack, nextId4) = mergeBranchDefs condStack bodyStack elseStack nextId3- in ( nodesAcc ++ cNodes ++ wNodes ++ bNodes ++ eNodes ++ phiNodes- , edgesAcc ++ cEdges ++ bEdges ++ eEdges ++ phiEdges+ (wNodes, nextId2_w) = mkDefNodes (Just cond) nextId2 walrusVars+ condStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) headerStack (zip wNodes walrusVars)+ (bNodes, bEdges, bodyStack, nextId3) = processStmtsWithStack condStack body nextId2_w+ (finalPhiNodes, finalPhiEdges) = finalizeLoopHeaderPhis phiHeaders bodyStack+ (eNodes, eEdges, elseStack, nextId4) = processStmtsWithStack headerStack elseB nextId3+ (postPhiNodes, postPhiEdges, mergedStack, nextId5) =+ if null elseB+ then ([], [], headerStack, nextId4)+ else mergeBranchDefs headerStack headerStack elseStack nextId4+ in ( nodesAcc `dlAppend` dlFromList finalPhiNodes `dlAppend` dlFromList cNodes `dlAppend` dlFromList wNodes `dlAppend` dlFromList bNodes `dlAppend` dlFromList eNodes `dlAppend` dlFromList postPhiNodes+ , edgesAcc `dlAppend` dlFromList finalPhiEdges `dlAppend` dlFromList cEdges `dlAppend` dlFromList bEdges `dlAppend` dlFromList eEdges `dlAppend` dlFromList postPhiEdges , mergedStack- , nextId4+ , nextId5 ) StmtFor target iter body elseB ->- let (iNodes, iEdges, nextId1) = extractExprUsesStack curStack iter curId- vars = extractTargetVars target- (defNodes, nextId2) = foldl (\(ns, cId) v ->- (ns ++ [DFGNode cId (DefAssignment v) (Just iter)], cId + 1)) ([], nextId1) vars- targetStack = foldl (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes vars)- (bNodes, bEdges, bodyStack, nextId3) = processStmtsWithStack targetStack body nextId2- (eNodes, eEdges, elseStack, nextId4) = processStmtsWithStack targetStack elseB nextId3- (phiNodes, phiEdges, mergedStack, nextId5) = mergeBranchDefs targetStack bodyStack elseStack nextId4- in ( nodesAcc ++ iNodes ++ defNodes ++ bNodes ++ eNodes ++ phiNodes- , edgesAcc ++ iEdges ++ bEdges ++ eEdges ++ phiEdges- , mergedStack- , nextId5+ analyzeLoopFor target iter body elseB nodesAcc edgesAcc curStack curId++ StmtAsyncFor target iter body elseB ->+ analyzeLoopFor target iter body elseB nodesAcc edgesAcc curStack curId++ StmtLoop body ->+ let loopModVars = collectModifiedVars body+ (phiHeaders, headerStack, nextId1) = allocLoopHeaderPhis curStack loopModVars Set.empty curId+ (bNodes, bEdges, bodyStack, nextId2) = processStmtsWithStack headerStack body nextId1+ (finalPhiNodes, finalPhiEdges) = finalizeLoopHeaderPhis phiHeaders bodyStack+ in ( nodesAcc `dlAppend` dlFromList finalPhiNodes `dlAppend` dlFromList bNodes+ , edgesAcc `dlAppend` dlFromList finalPhiEdges `dlAppend` dlFromList bEdges+ , headerStack+ , nextId2 ) StmtTry tryB handlers elseB finB -> let (tNodes, tEdges, tryStack, nextId1) = processStmtsWithStack curStack tryB curId- (hNodes, hEdges, hStacks, nextId2) = foldl stepHandler ([], [], [], nextId1) handlers+ (hNodesDL, hEdgesDL, hStacksDL, nextId2) = foldl' stepHandler (dlEmpty, dlEmpty, dlEmpty, nextId1) handlers (eNodes, eEdges, elseStack, nextId3) = processStmtsWithStack tryStack elseB nextId2- branchStacks = (if null elseB then tryStack else elseStack) : hStacks+ branchStacks = (if null elseB then tryStack else elseStack) : dlToList hStacksDL (phiNodes, phiEdges, mergedStack, nextId4) = mergeMultiBranchDefs curStack branchStacks nextId3 (fNodes, fEdges, finStack, nextId5) = processStmtsWithStack mergedStack finB nextId4- in ( nodesAcc ++ tNodes ++ hNodes ++ eNodes ++ phiNodes ++ fNodes- , edgesAcc ++ tEdges ++ hEdges ++ eEdges ++ phiEdges ++ fEdges+ in ( nodesAcc `dlAppend` dlFromList tNodes `dlAppend` hNodesDL `dlAppend` dlFromList eNodes `dlAppend` dlFromList phiNodes `dlAppend` dlFromList fNodes+ , edgesAcc `dlAppend` dlFromList tEdges `dlAppend` hEdgesDL `dlAppend` dlFromList eEdges `dlAppend` dlFromList phiEdges `dlAppend` dlFromList fEdges , finStack , nextId5 )@@ -268,52 +318,75 @@ excNode = [DFGNode cId (DefAssignment name) Nothing | Just name <- [mExcName]] cId1 = if null excNode then cId else cId + 1 (hN, hE, hS, cId2) = processStmtsWithStack excStack hStmts cId1- in (nsAcc ++ excNode ++ hN, esAcc ++ hE, stAcc ++ [hS], cId2)+ in (nsAcc `dlAppend` dlFromList excNode `dlAppend` dlFromList hN, esAcc `dlAppend` dlFromList hE, stAcc `dlAppend` dlSingleton hS, cId2) StmtSwitch expr cases defaultStmts -> let (eNodes, eEdges, nextId1) = extractExprUsesStack curStack expr curId- (cNodes, cEdges, caseStacks, nextId2) = foldl stepCase ([], [], [], nextId1) cases+ (cNodesDL, cEdgesDL, caseStacksDL, nextId2) = foldl' stepCase (dlEmpty, dlEmpty, dlEmpty, nextId1) cases (defNodes, defEdges, defStack, nextId3) = processStmtsWithStack curStack defaultStmts nextId2- allBranchStacks = defStack : caseStacks+ allBranchStacks = defStack : dlToList caseStacksDL (phiNodes, phiEdges, mergedStack, nextId4) = mergeMultiBranchDefs curStack allBranchStacks nextId3- in ( nodesAcc ++ eNodes ++ cNodes ++ defNodes ++ phiNodes- , edgesAcc ++ eEdges ++ cEdges ++ defEdges ++ phiEdges+ in ( nodesAcc `dlAppend` dlFromList eNodes `dlAppend` cNodesDL `dlAppend` dlFromList defNodes `dlAppend` dlFromList phiNodes+ , edgesAcc `dlAppend` dlFromList eEdges `dlAppend` cEdgesDL `dlAppend` dlFromList defEdges `dlAppend` dlFromList phiEdges , mergedStack , nextId4 ) where stepCase (nsAcc, esAcc, stAcc, cId) (_, cStmts) = let (cN, cE, cS, nId) = processStmtsWithStack curStack cStmts cId- in (nsAcc ++ cN, esAcc ++ cE, stAcc ++ [cS], nId)+ in (nsAcc `dlAppend` dlFromList cN, esAcc `dlAppend` dlFromList cE, stAcc `dlAppend` dlSingleton cS, nId) StmtMatch expr cases -> let (eNodes, eEdges, nextId1) = extractExprUsesStack curStack expr curId- (cNodes, cEdges, caseStacks, nextId2) = foldl stepCase ([], [], [], nextId1) cases- (phiNodes, phiEdges, mergedStack, nextId3) = mergeMultiBranchDefs curStack caseStacks nextId2- in ( nodesAcc ++ eNodes ++ cNodes ++ phiNodes- , edgesAcc ++ eEdges ++ cEdges ++ phiEdges+ (cNodesDL, cEdgesDL, caseStacksDL, nextId2) = foldl' stepCase (dlEmpty, dlEmpty, dlEmpty, nextId1) cases+ (phiNodes, phiEdges, mergedStack, nextId3) = mergeMultiBranchDefs curStack (dlToList caseStacksDL) nextId2+ in ( nodesAcc `dlAppend` dlFromList eNodes `dlAppend` cNodesDL `dlAppend` dlFromList phiNodes+ , edgesAcc `dlAppend` dlFromList eEdges `dlAppend` cEdgesDL `dlAppend` dlFromList phiEdges , mergedStack , nextId3 ) where stepCase (nsAcc, esAcc, stAcc, cId) mc = let (cN, cE, cS, nId) = processStmtsWithStack curStack (mcBody mc) cId- in (nsAcc ++ cN, esAcc ++ cE, stAcc ++ [cS], nId)+ in (nsAcc `dlAppend` dlFromList cN, esAcc `dlAppend` dlFromList cE, stAcc `dlAppend` dlSingleton cS, nId) StmtExpr e -> let (useNodes, useEdges, nextId1) = extractExprUsesStack curStack e curId walrusVars = collectWalrusDefs e- (defNodes, nextId2) = foldl (\(ns, cId) v ->- (ns ++ [DFGNode cId (DefAssignment v) (Just e)], cId + 1)) ([], nextId1) walrusVars+ (defNodes, nextId2) = mkDefNodes (Just e) nextId1 walrusVars walrusEdges = [ DFGEdge (dfgNodeId srcNode) (dfgNodeId targetNode) v | (targetNode, v) <- zip defNodes walrusVars , srcNode <- useNodes ]- newStack = foldl (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes walrusVars)- in (nodesAcc ++ useNodes ++ defNodes, edgesAcc ++ useEdges ++ walrusEdges, newStack, nextId2)+ newStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) curStack (zip defNodes walrusVars)+ in ( nodesAcc `dlAppend` dlFromList useNodes `dlAppend` dlFromList defNodes+ , edgesAcc `dlAppend` dlFromList useEdges `dlAppend` dlFromList walrusEdges+ , newStack+ , nextId2+ ) _ -> (nodesAcc, edgesAcc, curStack, curId) + analyzeLoopFor target iter body elseB nodesAcc edgesAcc curStack curId =+ let (iNodes, iEdges, nextId1) = extractExprUsesStack curStack iter curId+ vars = extractTargetVars target+ loopModVars = collectModifiedVars body+ (phiHeaders, headerStack, nextId2) = allocLoopHeaderPhis curStack loopModVars (Set.fromList vars) nextId1+ (defNodes, nextId3) = mkDefNodes (Just iter) nextId2 vars+ targetStack = foldl' (\s (dNode, v) -> updateStack v (dfgNodeId dNode) s) headerStack (zip defNodes vars)+ (bNodes, bEdges, bodyStack, nextId4) = processStmtsWithStack targetStack body nextId3+ (finalPhiNodes, finalPhiEdges) = finalizeLoopHeaderPhis phiHeaders bodyStack+ (eNodes, eEdges, elseStack, nextId5) = processStmtsWithStack headerStack elseB nextId4+ (postPhiNodes, postPhiEdges, mergedStack, nextId6) =+ if null elseB+ then ([], [], targetStack, nextId5)+ else mergeBranchDefs targetStack targetStack elseStack nextId5+ in ( nodesAcc `dlAppend` dlFromList iNodes `dlAppend` dlFromList finalPhiNodes `dlAppend` dlFromList defNodes `dlAppend` dlFromList bNodes `dlAppend` dlFromList eNodes `dlAppend` dlFromList postPhiNodes+ , edgesAcc `dlAppend` dlFromList iEdges `dlAppend` dlFromList finalPhiEdges `dlAppend` dlFromList bEdges `dlAppend` dlFromList eEdges `dlAppend` dlFromList postPhiEdges+ , mergedStack+ , nextId6+ )+ extractTargetVars :: Expr -> [Text] extractTargetVars = \case ExprId v -> [v]@@ -331,11 +404,11 @@ mergeMultiBranchDefs inStack branchStacks startId = let allVars = Set.toList (Set.unions (map Map.keysSet branchTops)) diffVars = filter isDiff allVars- (phiNodes, phiEdges, newDefs, nextId) = foldl step ([], [], inTop, startId) diffVars+ (phiNodesDL, phiEdgesDL, newDefs, nextId) = foldl' step (dlEmpty, dlEmpty, inTop, startId) diffVars finalStack = case inStack of (_:rest) -> newDefs : rest [] -> [newDefs]- in (phiNodes, phiEdges, finalStack, nextId)+ in (dlToList phiNodesDL, dlToList phiEdgesDL, finalStack, nextId) where inTop = case inStack of (s:_) -> s; [] -> Map.empty branchTops = [case s of (t:_) -> t; [] -> Map.empty | s <- branchStacks]@@ -360,23 +433,103 @@ let phiNode = DFGNode cId (DefPhi incomingDefs) (Just (ExprId v)) phiEdges = [DFGEdge src cId v | src <- incomingDefs] newDefsAcc = Map.insert v cId defsAcc- in (nsAcc ++ [phiNode], esAcc ++ phiEdges, newDefsAcc, cId + 1)+ in (nsAcc `dlAppend` dlSingleton phiNode, esAcc `dlAppend` dlFromList phiEdges, newDefsAcc, cId + 1) +-- | Collect variables modified anywhere inside a statement list (dominance-frontier+-- iterated phi candidates for loop headers).+collectModifiedVars :: [Stmt] -> Set Text+collectModifiedVars = foldl' (\acc s -> Set.union acc (stmtDefs s)) Set.empty+ where+ stmtDefs = \case+ StmtAssign targets val ->+ Set.fromList (concatMap extractTargetVars targets ++ collectWalrusDefs val)+ StmtAnnAssign target _ mVal ->+ Set.fromList (extractTargetVars target ++ maybe [] collectWalrusDefs mVal)+ StmtAugAssign target _ val ->+ Set.fromList (extractTargetVars target ++ collectWalrusDefs val)+ StmtExpr e ->+ Set.fromList (collectWalrusDefs e)+ StmtIf c t e ->+ Set.unions [Set.fromList (collectWalrusDefs c), collectModifiedVars t, collectModifiedVars e]+ StmtWhile c b e ->+ Set.unions [Set.fromList (collectWalrusDefs c), collectModifiedVars b, collectModifiedVars e]+ StmtFor t _ b e ->+ Set.unions [Set.fromList (extractTargetVars t), collectModifiedVars b, collectModifiedVars e]+ StmtAsyncFor t _ b e ->+ Set.unions [Set.fromList (extractTargetVars t), collectModifiedVars b, collectModifiedVars e]+ StmtTry b hs e f ->+ Set.unions (collectModifiedVars b : collectModifiedVars e : collectModifiedVars f : [collectModifiedVars hb | (_, _, hb) <- hs])+ StmtWith items b ->+ Set.union (Set.fromList [v | (_, Just tgt) <- items, v <- extractTargetVars tgt]) (collectModifiedVars b)+ StmtAsyncWith items b ->+ Set.union (Set.fromList [v | (_, Just tgt) <- items, v <- extractTargetVars tgt]) (collectModifiedVars b)+ StmtSwitch _ cs d ->+ Set.union (foldMap (collectModifiedVars . snd) cs) (collectModifiedVars d)+ StmtMatch _ cs ->+ foldMap (collectModifiedVars . mcBody) cs+ StmtLoop b ->+ collectModifiedVars b+ _ -> Set.empty++-- | Compute the ordered list of loop-carried variables requiring SSA phi placement+-- at a loop header, given the pre-loop scope and loop body statements.+computeLoopPhiVars :: ScopeStack -> [Stmt] -> Set Text -> [(Text, NodeId)]+computeLoopPhiVars stack body excludeSet =+ let modVars = Set.difference (collectModifiedVars body) excludeSet+ in [ (v, preId)+ | v <- Set.toAscList modVars+ , Just preId <- [lookupStack v stack]+ ]++allocLoopHeaderPhis+ :: ScopeStack+ -> Set Text+ -> Set Text+ -> NodeId+ -> ([(Text, NodeId, NodeId)], ScopeStack, NodeId)+allocLoopHeaderPhis stack modVars excludeSet startId =+ let candidates = Set.toAscList (Set.difference modVars excludeSet)+ step (acc, sAcc, cId) v = case lookupStack v stack of+ Just preId ->+ ((v, preId, cId) : acc, updateStack v cId sAcc, cId + 1)+ Nothing ->+ (acc, sAcc, cId)+ (revHeaders, headerStack, nextId) = foldl' step ([], stack, startId) candidates+ in (reverse revHeaders, headerStack, nextId)++finalizeLoopHeaderPhis+ :: [(Text, NodeId, NodeId)]+ -> ScopeStack+ -> ([DFGNode], [DFGEdge])+finalizeLoopHeaderPhis headers bodyStack =+ let step (nsAcc, esAcc) (v, preId, phiId) =+ let mBodyId = lookupStack v bodyStack+ incoming = case mBodyId of+ Just bId | bId /= phiId -> [preId, bId]+ _ -> [preId]+ node = DFGNode phiId (DefPhi incoming) (Just (ExprId v))+ edges =+ DFGEdge preId phiId v+ : [DFGEdge bId phiId v | Just bId <- [mBodyId], bId /= phiId]+ in (nsAcc `dlAppend` dlSingleton node, esAcc `dlAppend` dlFromList edges)+ (nsDL, esDL) = foldl' step (dlEmpty, dlEmpty) headers+ in (dlToList nsDL, dlToList esDL)+ extractExprUses :: Map Text NodeId -> Expr -> NodeId -> ([DFGNode], [DFGEdge], NodeId) extractExprUses activeDefs expr startId = extractExprUsesStack [activeDefs] expr startId extractExprUsesStack :: ScopeStack -> Expr -> NodeId -> ([DFGNode], [DFGEdge], NodeId) extractExprUsesStack stack expr startId = let readVars = collectVarReads expr- (nodes, edges, nextId) = foldl step ([], [], startId) (Set.toList readVars)- in (nodes, edges, nextId)+ (nodesDL, edgesDL, nextId) = foldl' step (dlEmpty, dlEmpty, startId) (Set.toList readVars)+ in (dlToList nodesDL, dlToList edgesDL, nextId) where step (ns, es, curId) v = let useNode = DFGNode curId (UseRead v) (Just expr)- edge = case lookupStack v stack of- Just defNodeId -> [DFGEdge defNodeId curId v]- Nothing -> []- in (ns ++ [useNode], es ++ edge, curId + 1)+ edges' = case lookupStack v stack of+ Just defNodeId -> dlSingleton (DFGEdge defNodeId curId v)+ Nothing -> dlEmpty+ in (ns `dlAppend` dlSingleton useNode, es `dlAppend` edges', curId + 1) collectWalrusDefs :: Expr -> [Text] collectWalrusDefs = \case
src/Canontra/Analysis/Impact.hs view
@@ -31,7 +31,7 @@ import Control.DeepSeq (NFData) import Data.Aeson (FromJSON, ToJSON, encode) import qualified Data.ByteString.Lazy as BL-import Data.List (nub, sort)+import Data.List (sort) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T@@ -133,8 +133,8 @@ -- Extract direct external callers of target file via transposed CSR adjacency slice directCallers =- sort $- nub+ Set.toAscList $+ Set.fromList [ callerSym | idx <- targetNodeIndices , callerIdx <- VU.toList (csrNeighborIndices transCsr idx)@@ -158,14 +158,14 @@ SeverityInterface -> let reachableSymbols = traverseInvertedCallersCSR normTarget (csr, nodes)- affected = sort (nub (normTarget : map (normalizeImpactPath . symFilePath) reachableSymbols))+ affected = Set.toAscList (Set.fromList (normTarget : map (normalizeImpactPath . symFilePath) reachableSymbols)) tests = findMatchingTests affected allRepoFiles saved = computeSavedPct affected allRepoFiles in (affected, tests, saved) SeverityDependency -> let reachableSymbols = traverseInvertedCallersCSR normTarget (csr, nodes)- affected = sort (nub (normTarget : map (normalizeImpactPath . symFilePath) reachableSymbols))+ affected = Set.toAscList (Set.fromList (normTarget : map (normalizeImpactPath . symFilePath) reachableSymbols)) tests = findMatchingTests affected allRepoFiles saved = computeSavedPct affected allRepoFiles in (affected, tests, saved)@@ -207,13 +207,26 @@ ] -- | Discover test files associated with a set of modified source files.+-- Uses O(log |A|) exact and affix-stripped set lookups before falling back to+-- substring matching for irregular test names. findMatchingTests :: [FilePath] -> [FilePath] -> [FilePath] findMatchingTests affectedFiles allRepoFiles = let testFiles = filter isRepoTestFile allRepoFiles affectedBases = Set.fromList (map (T.toLower . T.pack . takeBaseName) affectedFiles)+ stripAffixes t =+ let s1 = maybe t id (T.stripPrefix "test_" t)+ s2 = maybe s1 id (T.stripPrefix "spec_" s1)+ s3 = maybe s2 id (T.stripSuffix "_test" s2)+ s4 = maybe s3 id (T.stripSuffix ".test" s3)+ s5 = maybe s4 id (T.stripSuffix "_spec" s4)+ s6 = maybe s5 id (T.stripSuffix ".spec" s5)+ in s6 matchesTest tf = let tBase = T.toLower (T.pack (takeBaseName tf))- in any (\b -> b `T.isInfixOf` tBase || tBase `T.isInfixOf` b) affectedBases+ tCore = stripAffixes tBase+ in Set.member tBase affectedBases+ || (not (T.null tCore) && Set.member tCore affectedBases)+ || any (\b -> b `T.isInfixOf` tBase || tBase `T.isInfixOf` b) affectedBases in sort (filter matchesTest testFiles) -- | Check whether a repository file path corresponds to a test or specification file.
src/Canontra/Analysis/TypeContract.hs view
@@ -18,7 +18,8 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Canontra.Analysis.TypeContract- ( StructuralType (..)+ ( Mutability (..)+ , StructuralType (..) , MethodContract (..) , InterfaceContract (..) , makeUnion@@ -32,15 +33,17 @@ , extractTypeContracts , areStructurallyEqual , isSubtypeOf+ , isStructuralSubtype ) where import Control.DeepSeq (NFData) import Data.Aeson (FromJSON, ToJSON) import Data.Char (isAlphaNum)-import Data.List (nub, partition, sort, sortBy)+import Data.List (partition, sortBy) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Ord (comparing)+import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import GHC.Generics (Generic)@@ -56,6 +59,13 @@ ) import Canontra.IR.Program (Module (..), Program (..)) +-- | Mutability qualifier for borrowed references and raw pointers.+data Mutability+ = Immut+ | Mut+ deriving stock (Eq, Ord, Show, Generic)+ deriving anyclass (ToJSON, FromJSON, NFData)+ -- | Language-independent canonical structural type representation. data StructuralType = TypePrimitive !Text@@ -67,6 +77,9 @@ | TypeOptional !StructuralType | TypeGeneric !Text ![StructuralType] | TypeRecVar !Int+ | TypeRef !Mutability !StructuralType+ | TypePtr !StructuralType+ | TypeTuple ![StructuralType] deriving stock (Eq, Ord, Show, Generic) deriving anyclass (ToJSON, FromJSON, NFData) @@ -75,7 +88,7 @@ makeUnion :: [StructuralType] -> StructuralType makeUnion types = let flattened = concatMap flattenU types- deduped = sort (nub flattened)+ deduped = Set.toAscList (Set.fromList flattened) in case deduped of [] -> TypePrimitive "never" [t] -> t@@ -89,7 +102,7 @@ makeIntersection :: [StructuralType] -> StructuralType makeIntersection types = let flattened = concatMap flattenI types- deduped = sort (nub flattened)+ deduped = Set.toAscList (Set.fromList flattened) in case deduped of [] -> TypePrimitive "any" [t] -> t@@ -101,7 +114,7 @@ -- | Smart constructor for structural Record types enforcing canonical field sorting. makeRecord :: [(Text, StructuralType)] -> StructuralType makeRecord fields =- TypeRecord (sortBy (comparing fst) (nub fields))+ TypeRecord (sortBy (comparing fst) (Set.toList (Set.fromList fields))) -- | Canonical method contract. data MethodContract = MethodContract@@ -120,7 +133,8 @@ } deriving stock (Eq, Ord, Show, Generic) deriving anyclass (ToJSON, FromJSON, NFData) --- | Normalize a raw type string into canonical 'StructuralType' across polyglot languages.+-- | Normalize a raw type string into canonical 'StructuralType' across polyglot languages,+-- preserving exact integer/unsigned/float bit-widths, pointer/reference mutability, and tuple order. parseTypeString :: Text -> StructuralType parseTypeString raw = let clean = stripOuterParens (T.strip (normalizeLifetimes raw))@@ -130,33 +144,34 @@ _ | T.null clean -> TypePrimitive "any" | length unionParts > 1 -> makeUnion (map parseTypeString unionParts)- | length interParts > 1 ->+ | not (T.isPrefixOf "&" clean) && length interParts > 1 -> makeIntersection (map parseTypeString interParts) | T.isPrefixOf "~" clean -> parseTypeString (T.drop 1 clean)+ | T.isPrefixOf "*mut " clean ->+ TypePtr (TypeRef Mut (parseTypeString (T.drop 5 clean)))+ | T.isPrefixOf "*const " clean ->+ TypePtr (parseTypeString (T.drop 7 clean)) | T.isPrefixOf "*" clean ->- parseTypeString (T.drop 1 clean)- | T.isPrefixOf "&mut " clean ->- parseTypeString (T.drop 5 clean)+ TypePtr (parseTypeString (T.drop 1 clean)) | T.isPrefixOf "&" clean ->- parseTypeString (T.drop 1 clean)+ let rest0 = T.strip (stripLeadingLifetime (T.drop 1 clean))+ in case T.stripPrefix "mut " rest0 of+ Just mutInner -> TypeRef Mut (parseTypeString mutInner)+ Nothing ->+ case T.stripPrefix "mut" rest0 of+ Just mutRest+ | Just (c, _) <- T.uncons mutRest+ , not (isAlphaNum c || c == '_') ->+ TypeRef Mut (parseTypeString mutRest)+ _ -> TypeRef Immut (parseTypeString rest0) | T.isPrefixOf "{" clean && T.isSuffixOf "}" clean -> parseRecordLiteral (T.drop 1 (T.dropEnd 1 clean))- | T.isPrefixOf "(" clean && T.isSuffixOf ")" clean && "," `T.isInfixOf` clean ->+ | T.isPrefixOf "(" clean && T.isSuffixOf ")" clean && length (splitTopLevel ',' (T.drop 1 (T.dropEnd 1 clean))) > 1 -> let inner = T.drop 1 (T.dropEnd 1 clean)- in makeUnion (map parseTypeString (splitTopLevel ',' inner))- | clean `elem` ["int", "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize", "int32", "int64", "uint", "uint32", "uint64", "number"] ->- TypePrimitive "number"- | clean `elem` ["float", "f32", "f64", "float32", "float64", "double"] ->- TypePrimitive "number"- | clean `elem` ["str", "string", "String", "Text"] ->- TypePrimitive "string"- | clean `elem` ["bool", "boolean", "Boolean"] ->- TypePrimitive "bool"- | clean `elem` ["void", "None", "()", "nil", "null", "undefined"] ->- TypePrimitive "void"- | clean `elem` ["any", "unknown", "interface{}", "Object", "object"] ->- TypePrimitive "any"+ in TypeTuple (map parseTypeString (splitTopLevel ',' inner))+ | Just prim <- normalizeScalarPrimitive clean ->+ TypePrimitive prim | clean `elem` ["bytes", "[]byte", "Uint8Array", "byte[]"] -> TypeArray (TypePrimitive "byte") | T.isSuffixOf "[]" clean ->@@ -175,7 +190,63 @@ normalizeGenericConstruct base (map parseTypeString args) | otherwise -> TypePrimitive (compactTypeSpacing clean)+ where+ stripLeadingLifetime txt =+ case T.uncons txt of+ Just ('\'', xs) -> T.dropWhile (\c -> isAlphaNum c || c == '_') xs+ _ -> txt +normalizeScalarPrimitive :: Text -> Maybe Text+normalizeScalarPrimitive = \case+ "i8" -> Just "i8"+ "int8" -> Just "i8"+ "i16" -> Just "i16"+ "int16" -> Just "i16"+ "i32" -> Just "i32"+ "int32" -> Just "i32"+ "i64" -> Just "i64"+ "int64" -> Just "i64"+ "i128" -> Just "i128"+ "isize" -> Just "isize"+ "u8" -> Just "u8"+ "uint8" -> Just "u8"+ "u16" -> Just "u16"+ "uint16" -> Just "u16"+ "u32" -> Just "u32"+ "uint32" -> Just "u32"+ "u64" -> Just "u64"+ "uint64" -> Just "u64"+ "u128" -> Just "u128"+ "usize" -> Just "usize"+ "uint" -> Just "uint"+ "int" -> Just "int"+ "number" -> Just "number"+ "f32" -> Just "f32"+ "float32" -> Just "f32"+ "f64" -> Just "f64"+ "float64" -> Just "f64"+ "float" -> Just "f64"+ "double" -> Just "f64"+ "str" -> Just "string"+ "string" -> Just "string"+ "String" -> Just "string"+ "Text" -> Just "string"+ "bool" -> Just "bool"+ "boolean" -> Just "bool"+ "Boolean" -> Just "bool"+ "void" -> Just "void"+ "None" -> Just "void"+ "()" -> Just "void"+ "nil" -> Just "void"+ "null" -> Just "void"+ "undefined" -> Just "void"+ "any" -> Just "any"+ "unknown" -> Just "any"+ "interface{}" -> Just "any"+ "Object" -> Just "any"+ "object" -> Just "any"+ _ -> Nothing+ -- | Strip redundant outer balanced parentheses wrapping an entire type expression, -- e.g. @"((string | number))"@ -> @"string | number"@, while preserving -- @" (A | B) | (C | D) "@ where the first '(' closes before the end.@@ -299,7 +370,7 @@ | (idx, (pName, _)) <- indexed ] constraintFields =- [ ("tparam_α" <> T.pack (show idx), substituteStructuralType substMap (parseTypeString c))+ [ ("tparam_α" <> T.pack (show idx), substituteStructuralType substMap (parseTypeParamConstraint c)) | (idx, (_, Just c)) <- indexed , let cleanC = T.strip c , not (T.null cleanC)@@ -307,6 +378,16 @@ ] in (substMap, constraintFields) +-- | Parse generic type parameter constraint bounds: in PEP 695 syntax (@[T: (int, float)]@),+-- a parenthesized comma list is an unordered union of constraint types rather than an ordered tuple.+parseTypeParamConstraint :: Text -> StructuralType+parseTypeParamConstraint raw =+ let clean = T.strip (normalizeLifetimes raw)+ in if T.isPrefixOf "(" clean && T.isSuffixOf ")" clean+ && length (splitTopLevel ',' (T.drop 1 (T.dropEnd 1 clean))) > 1+ then makeUnion (map parseTypeString (splitTopLevel ',' (T.drop 1 (T.dropEnd 1 clean))))+ else parseTypeString raw+ parseHeaderParams :: Text -> [(Text, Maybe Text)] parseHeaderParams header = let clean = T.strip header@@ -395,6 +476,12 @@ in TypeGeneric base' (map (substituteStructuralType substMap) args) TypeRecVar d -> TypeRecVar d+ TypeRef mut inner ->+ TypeRef mut (substituteStructuralType substMap inner)+ TypePtr inner ->+ TypePtr (substituteStructuralType substMap inner)+ TypeTuple elems ->+ TypeTuple (map (substituteStructuralType substMap) elems) applySubstToContract :: Map Text StructuralType -> [(Text, StructuralType)] -> InterfaceContract -> InterfaceContract applySubstToContract substMap extraFields contract@@ -563,9 +650,57 @@ areStructurallyEqual c1 c2 = icMethods c1 == icMethods c2 && icFields c1 == icFields c2 --- | Evaluate whether sub-contract satisfies super-contract (structural subtyping).+-- | Evaluate whether sub-contract satisfies super-contract (structural subtyping+-- with contravariant parameters, covariant return/field types, and mutability safety). isSubtypeOf :: InterfaceContract -> InterfaceContract -> Bool isSubtypeOf subContract superContract =- let hasAllMethods = all (`elem` icMethods subContract) (icMethods superContract)- hasAllFields = all (`elem` icFields subContract) (icFields superContract)+ let hasAllMethods = all (`satisfiesMethod` icMethods subContract) (icMethods superContract)+ hasAllFields = all (`satisfiesField` icFields subContract) (icFields superContract) in hasAllMethods && hasAllFields+ where+ satisfiesMethod reqSub candidates =+ any (\m -> isMethodSubtype m reqSub) candidates+ satisfiesField (reqName, reqTy) candidates =+ case lookup reqName candidates of+ Nothing -> False+ Just subTy -> isStructuralSubtype subTy reqTy++isMethodSubtype :: MethodContract -> MethodContract -> Bool+isMethodSubtype subM superM =+ mcName subM == mcName superM+ && mcIsAsync subM == mcIsAsync superM+ && length (mcParams subM) == length (mcParams superM)+ && and (zipWith isStructuralSubtype (mcParams superM) (mcParams subM))+ && isStructuralSubtype (mcReturn subM) (mcReturn superM)++-- | Variance-aware structural subtyping check @sub <: super@.+isStructuralSubtype :: StructuralType -> StructuralType -> Bool+isStructuralSubtype sub super+ | sub == super = True+ | super == TypePrimitive "any" = True+ | sub == TypePrimitive "never" = True+ | TypeUnion alts <- super =+ any (isStructuralSubtype sub) alts+ | TypeIntersection reqs <- super =+ all (isStructuralSubtype sub) reqs+ | TypeIntersection parts <- sub =+ any (`isStructuralSubtype` super) parts+ | TypeUnion alts <- sub =+ all (`isStructuralSubtype` super) alts+ | otherwise = case (sub, super) of+ (TypeRef Mut t1, TypeRef _ t2) -> isStructuralSubtype t1 t2+ (TypeRef Immut t1, TypeRef Immut t2) -> isStructuralSubtype t1 t2+ (TypeRef Immut _, TypeRef Mut _) -> False+ (TypePtr t1, TypePtr t2) -> isStructuralSubtype t1 t2+ (TypeTuple ts1, TypeTuple ts2) ->+ length ts1 == length ts2 && and (zipWith isStructuralSubtype ts1 ts2)+ (TypeArray a1, TypeArray a2) -> isStructuralSubtype a1 a2+ (TypeOptional o1, TypeOptional o2) -> isStructuralSubtype o1 o2+ (t1, TypeOptional o2) -> isStructuralSubtype t1 o2+ (TypeFunction p1 r1, TypeFunction p2 r2) ->+ length p1 == length p2+ && and (zipWith isStructuralSubtype p2 p1)+ && isStructuralSubtype r1 r2+ (TypeRecord f1, TypeRecord f2) ->+ all (\(k, ty2) -> maybe False (`isStructuralSubtype` ty2) (lookup k f1)) f2+ _ -> False
src/Canontra/Analysis/WholeRepoGraph.hs view
@@ -8,6 +8,8 @@ and tracks parameter-to-argument and return-value data flow propagation. -} {-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} module Canontra.Analysis.WholeRepoGraph ( DeclKind (..)@@ -16,8 +18,13 @@ , WholeRepoCallGraph (..) , InterProceduralDataFlowEdge (..) , WholeRepoDataFlowGraph (..)+ , CallFlowSite (..)+ , FileGraphSummary (..)+ , extractFileGraphSummary , buildWholeRepoCallGraph+ , buildWholeRepoCallGraphFromSummaries , buildWholeRepoDataFlow+ , buildWholeRepoDataFlowFromSummaries , toCSRCallGraph , toCSRDataFlowGraph , buildCSRCallGraph@@ -33,11 +40,11 @@ , incrementalUpdateWholeRepoGraphs ) where +import Control.DeepSeq (NFData) import Data.Bits ((.|.))-import Data.List (nub, sort, sortBy)+import Data.List (foldl', sortBy) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map-import Data.Maybe (mapMaybe) import Data.Ord (comparing) import Data.Set (Set) import qualified Data.Set as Set@@ -45,7 +52,8 @@ import qualified Data.Text as T import qualified Data.Vector as V import Data.Word (Word32)-import System.FilePath (dropExtension, normalise, splitDirectories)+import GHC.Generics (Generic)+import System.FilePath (dropExtension, normalise, splitDirectories, takeDirectory, takeExtension, takeFileName) import Canontra.Analysis.CSRGraph ( CSRGraph (..)@@ -98,11 +106,6 @@ other -> reverse other in T.intercalate "." (map T.pack effectiveDirs) --- | Collect all top-level and member declarations across repository modules.-collectGlobalSymbols :: [(FilePath, Program)] -> [GlobalSymbol]-collectGlobalSymbols modules =- concatMap (\(fp, prog) -> extractProgramSymbols fp prog) modules- extractProgramSymbols :: FilePath -> Program -> [GlobalSymbol] extractProgramSymbols fp (Program mods _) = let pathMod = filePathToModuleName fp@@ -110,16 +113,140 @@ extractModuleSymbols :: FilePath -> Text -> Module -> [GlobalSymbol] extractModuleSymbols fp pathMod (Module mName _ decls _) =- let isPathLike t =- T.null t- || t == "main"- || t == T.pack fp- || T.isInfixOf "/" t- || T.isInfixOf "\\" t- || any (`T.isSuffixOf` t) [".py", ".pyi", ".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".go", ".rs"]- effectiveMod = if isPathLike mName then pathMod else mName+ let effectiveMod = effectiveModuleName fp pathMod mName in concatMap (declToGlobalSymbols fp effectiveMod) decls +-- | Compute the canonical effective module namespace for a source file.+-- For Go files, merges sibling files within the same directory that share a+-- @package@ declaration into one unified package key (avoiding false isolation+-- or blind cross-package fallback).+effectiveModuleName :: FilePath -> Text -> Text -> Text+effectiveModuleName fp pathMod mName+ | takeExtension fp == ".go" =+ let norm = map (\c -> if c == '\\' then '/' else c) (normalise fp)+ dirRaw = takeDirectory norm+ dirSegs = filter (\d -> d /= "." && d /= "/" && d /= "" && d /= "\\") (splitDirectories dirRaw)+ cleanPkg+ | T.null mName || mName == T.pack fp || T.isInfixOf "/" mName || T.isInfixOf "\\" mName =+ case reverse dirSegs of+ (d:_) -> T.pack d+ [] -> pathMod+ | otherwise = mName+ in case reverse dirSegs of+ [] -> cleanPkg+ (lastDir : _)+ | T.pack lastDir == cleanPkg -> T.intercalate "." (map T.pack dirSegs)+ | otherwise -> T.intercalate "." (map T.pack dirSegs) <> "." <> cleanPkg+ | otherwise =+ let isPathLike t =+ T.null t+ || t == "main"+ || t == T.pack fp+ || T.isInfixOf "/" t+ || T.isInfixOf "\\" t+ || any (`T.isSuffixOf` t) [".py", ".pyi", ".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".go", ".rs"]+ in if isPathLike mName then pathMod else mName++isBarrelFile :: FilePath -> Bool+isBarrelFile fp =+ let base = takeFileName fp+ in base `elem`+ [ "__init__.py"+ , "index.ts", "index.tsx", "index.js", "index.mjs", "index.cjs"+ , "mod.rs", "lib.rs"+ ]++barrelParentModule :: FilePath -> Maybe Text+barrelParentModule fp+ | not (isBarrelFile fp) = Nothing+ | otherwise =+ let norm = map (\c -> if c == '\\' then '/' else c) (normalise fp)+ dirRaw = takeDirectory norm+ dirSegs = filter (\d -> d /= "." && d /= "/" && d /= "" && d /= "\\") (splitDirectories dirRaw)+ in if null dirSegs then Nothing else Just (T.intercalate "." (map T.pack dirSegs))++-- | Normalize an import specifier (relative JS/TS/Python path or Rust crate path)+-- relative to the importing file's directory into a canonical dotted module name.+normalizeImportSpecifier :: FilePath -> Text -> Text+normalizeImportSpecifier curPath rawSpec+ | T.isPrefixOf "./" rawSpec || T.isPrefixOf "../" rawSpec =+ let normCur = map (\c -> if c == '\\' then '/' else c) (normalise curPath)+ curDir = takeDirectory normCur+ curSegs = filter (\d -> d /= "." && d /= "" && d /= "/") (splitDirectories curDir)+ rawNoExt = stripSourceExt rawSpec+ specSegs = T.splitOn "/" rawNoExt+ resolvedSegs = foldl' stepSeg curSegs specSegs+ trimmed = case reverse resolvedSegs of+ ("index" : rest) -> reverse rest+ other -> reverse other+ in T.intercalate "." (map T.pack trimmed)+ | T.isPrefixOf "." rawSpec =+ let dots = T.length (T.takeWhile (== '.') rawSpec)+ restSpec = T.drop dots rawSpec+ normCur = map (\c -> if c == '\\' then '/' else c) (normalise curPath)+ curDir = takeDirectory normCur+ curSegs = filter (\d -> d /= "." && d /= "" && d /= "/") (splitDirectories curDir)+ upCount = max 0 (dots - 1)+ baseSegs = take (max 0 (length curSegs - upCount)) curSegs+ extraSegs = if T.null restSpec then [] else map T.unpack (T.splitOn "." restSpec)+ in T.intercalate "." (map T.pack (baseSegs ++ extraSegs))+ | T.isPrefixOf "crate::" rawSpec =+ T.replace "::" "." (T.drop 7 rawSpec)+ | T.isInfixOf "::" rawSpec =+ T.replace "::" "." rawSpec+ | "/" `T.isInfixOf` rawSpec =+ let noExt = stripSourceExt rawSpec+ segs = filter (not . T.null) (T.splitOn "/" noExt)+ trimmed = case reverse segs of+ ("index" : rest) -> reverse rest+ other -> reverse other+ in T.intercalate "." trimmed+ | otherwise = rawSpec+ where+ stepSeg segs s+ | s == "." || T.null s = segs+ | s == ".." = if null segs then [] else init segs+ | otherwise = segs ++ [T.unpack s]++ stripSourceExt t =+ case filter (`T.isSuffixOf` t) [".py", ".pyi", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".go", ".rs"] of+ (ext : _) -> T.dropEnd (T.length ext) t+ [] -> t++-- | Collect normalized imported module names and barrel re-exports from a program's modules.+extractImportsAndBarrels :: FilePath -> Program -> ([Text], [(Text, Text, Text)])+extractImportsAndBarrels fp (Program mods _) =+ let allImps = concatMap modImports mods+ impMods = Set.toAscList $ Set.fromList+ [ normalizeImportSpecifier fp m+ | imp <- allImps+ , let m = case imp of+ ImportModule p _ -> p+ ImportFrom p _ -> p+ , not (T.null m)+ ]+ reExps =+ [ item+ | imp <- allImps+ , item <- impToReExports imp+ ]+ in (impMods, reExps)+ where+ impToReExports = \case+ ImportFrom srcMod ImportAll ->+ [("*", normalizeImportSpecifier fp srcMod, "*")]+ ImportFrom srcMod (ImportSymbols pairs)+ | isBarrelFile fp || isJSOrRust ->+ [ (maybe sym id mAlias, normalizeImportSpecifier fp srcMod, sym)+ | (sym, mAlias) <- pairs+ ]+ ImportModule srcMod (Just alias)+ | isBarrelFile fp ->+ [(alias, normalizeImportSpecifier fp srcMod, alias)]+ _ -> []+ isJSOrRust =+ takeExtension fp `elem` [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".rs"]+ declToGlobalSymbols :: FilePath -> Text -> Declaration -> [GlobalSymbol] declToGlobalSymbols fp modName decl = let f2 = hashBytes (canonicalizeDeclaration decl)@@ -178,72 +305,144 @@ DeclTypeAlias name _ -> [GlobalSymbol fp modName name KindTypeAlias f2] --- | Multi-index symbol lookup table for robust cross-module resolution.+-- | Barrel re-export registry: maps canonical module names (including parent barrel aliases+-- like @"pkg"@ for @"pkg/index.ts"@) to explicit re-exported symbols and wildcard source modules.+type BarrelMap = Map Text (Map Text (Text, Text), [Text])++-- | Multi-index symbol lookup table for robust, import-scoped cross-module resolution. data SymbolIndices = SymbolIndices { idxByModAndName :: !(Map (Text, Text) GlobalSymbol) , idxByPathAndName :: !(Map (FilePath, Text) GlobalSymbol) , idxByNameOnly :: !(Map Text [GlobalSymbol])+ , idxBarrelMap :: !BarrelMap } -buildSymbolIndices :: [GlobalSymbol] -> SymbolIndices-buildSymbolIndices syms =+buildBarrelMapFromSummaries :: [FileGraphSummary] -> BarrelMap+buildBarrelMapFromSummaries summaries =+ foldl' addSummary Map.empty summaries+ where+ addSummary acc s =+ let fp = fgsFilePath s+ modName = fgsModuleName s+ keys = modName : maybe [] pure (barrelParentModule fp)+ (symMap, wilds) = foldl' splitReExp (Map.empty, []) (fgsReExports s)+ in if Map.null symMap && null wilds+ then acc+ else foldl' (\m k -> Map.insertWith mergeBarrel k (symMap, wilds) m) acc keys++ splitReExp (sm, ws) (expName, srcM, origName)+ | expName == "*" = (sm, srcM : ws)+ | otherwise = (Map.insert expName (srcM, origName) sm, ws)++ mergeBarrel (s1, w1) (s2, w2) = (Map.union s1 s2, w1 ++ w2)++buildSymbolIndices :: [GlobalSymbol] -> BarrelMap -> SymbolIndices+buildSymbolIndices syms barrelMap = let byModName = Map.fromList [((symModule s, symDeclName s), s) | s <- syms] byPathName = Map.fromList [((symFilePath s, symDeclName s), s) | s <- syms] byName = Map.fromListWith (++) [(symDeclName s, [s]) | s <- syms]- in SymbolIndices byModName byPathName byName+ in SymbolIndices byModName byPathName byName barrelMap --- | Resolve an invocation target against the multi-index repository symbol table.+followBarrel+ :: SymbolIndices+ -> Set (Text, Text)+ -> Int+ -> Text+ -> Text+ -> Maybe GlobalSymbol+followBarrel _ _ depth _ _ | depth >= 16 = Nothing+followBarrel indices visited depth modName symName+ | Set.member (modName, symName) visited = Nothing+ | Just s <- Map.lookup (modName, symName) (idxByModAndName indices) = Just s+ | otherwise =+ let visited' = Set.insert (modName, symName) visited+ in case Map.lookup modName (idxBarrelMap indices) of+ Nothing -> Nothing+ Just (explicitMap, wildMods) ->+ case Map.lookup symName explicitMap of+ Just (srcMod, origSym) ->+ followBarrel indices visited' (depth + 1) srcMod origSym+ Nothing ->+ firstJust [followBarrel indices visited' (depth + 1) wm symName | wm <- wildMods]+ where+ firstJust [] = Nothing+ firstJust (Just x : _) = Just x+ firstJust (Nothing : xs) = firstJust xs++-- | Resolve an invocation target against the multi-index, import-scoped symbol table+-- and barrel re-export registry. Avoids blind cross-package fallback collisions. resolveTarget :: SymbolIndices -> Text -- ^ Current module name -> FilePath -- ^ Current file path+ -> Set Text -- ^ Explicitly imported module names for the current file -> CalleeTarget -> Maybe GlobalSymbol-resolveTarget indices curMod curPath = \case+resolveTarget indices curMod curPath curImports = \case TargetLocal name -> case Map.lookup (curMod, name) (idxByModAndName indices) of Just s -> Just s Nothing -> case Map.lookup (curPath, name) (idxByPathAndName indices) of Just s -> Just s- Nothing -> case Map.lookup name (idxByNameOnly indices) of- Just [unique] -> Just unique- _ -> Nothing+ Nothing ->+ -- Check wildcard / barrel imports scoped to curImports or curMod+ firstJust+ [ followBarrel indices Set.empty 0 impMod name+ | impMod <- Set.toList (Set.insert curMod curImports)+ ] TargetMethod cls m -> let qualifiedName = if T.null cls then m else cls <> "." <> m in case Map.lookup (curMod, qualifiedName) (idxByModAndName indices) of Just s -> Just s- Nothing -> case Map.lookup qualifiedName (idxByNameOnly indices) of- Just [unique] -> Just unique- _ -> Nothing+ Nothing ->+ case firstJust [Map.lookup (impM, qualifiedName) (idxByModAndName indices) | impM <- Set.toList curImports] of+ Just s -> Just s+ Nothing ->+ if T.null cls+ then Nothing+ else case Map.lookup qualifiedName (idxByNameOnly indices) of+ Just [unique] -> Just unique+ _ -> Nothing TargetImported impMod sym ->- case Map.lookup (impMod, sym) (idxByModAndName indices) of+ let resolvedMod = normalizeImportSpecifier curPath impMod+ candidatesMods = Set.toList (Set.fromList [resolvedMod, impMod])+ in case firstJust [followBarrel indices Set.empty 0 cm sym | cm <- candidatesMods] of Just s -> Just s Nothing ->- if T.null sym && T.isInfixOf "." impMod+ if T.null sym && T.isInfixOf "." resolvedMod then- let parts = T.splitOn "." impMod+ let parts = T.splitOn "." resolvedMod subMod = T.intercalate "." (init parts) subSym = last parts- in case Map.lookup (subMod, subSym) (idxByModAndName indices) of- Just s -> Just s- Nothing -> Map.lookup (impMod, sym) (idxByModAndName indices)+ in followBarrel indices Set.empty 0 subMod subSym else- let strippedMod = T.dropWhile (== '.') (T.dropWhile (/= '.') impMod)- in case Map.lookup (strippedMod, sym) (idxByModAndName indices) of+ let strippedMod = T.dropWhile (== '.') (T.dropWhile (/= '.') resolvedMod)+ in case followBarrel indices Set.empty 0 strippedMod sym of Just s -> Just s Nothing -> case Map.lookup sym (idxByNameOnly indices) of- Just [unique] -> Just unique Just candidates ->- case filter (\c -> symModule c == impMod || T.isSuffixOf (symModule c) impMod || T.isSuffixOf impMod (symModule c)) candidates of+ case filter (matchesImportSpec resolvedMod impMod . symModule) candidates of (matched : _) -> Just matched [] -> Nothing Nothing -> Nothing TargetDynamic _ -> Nothing+ where+ firstJust [] = Nothing+ firstJust (Just x : _) = Just x+ firstJust (Nothing : xs) = firstJust xs + matchesImportSpec resM rawM symM =+ symM == resM+ || symM == rawM+ || ("." <> resM) `T.isSuffixOf` ("." <> symM)+ || ("." <> symM) `T.isSuffixOf` ("." <> resM)+ || ("." <> rawM) `T.isSuffixOf` ("." <> symM)+ || ("." <> symM) `T.isSuffixOf` ("." <> rawM)+ -- | Resolve caller node to a GlobalSymbol. resolveCaller :: SymbolIndices -> Text -> FilePath -> CallerNode -> GlobalSymbol resolveCaller indices curMod curPath = \case@@ -262,32 +461,19 @@ -- | Build the unified repository-level Call Graph across all modules. buildWholeRepoCallGraph :: [(FilePath, Program)] -> WholeRepoCallGraph buildWholeRepoCallGraph modules =- let allSymbols = collectGlobalSymbols modules- indices = buildSymbolIndices allSymbols- rawEdges = concatMap (extractModuleEdges indices) modules- consolidatedEdges = consolidateWholeRepoEdges rawEdges- allNodes = sort (nub (allSymbols ++ map wceCaller consolidatedEdges ++ map wceCallee consolidatedEdges))- sccs = tarjanWholeRepoSCC allNodes consolidatedEdges- in WholeRepoCallGraph allNodes consolidatedEdges sccs--extractModuleEdges- :: SymbolIndices- -> (FilePath, Program)- -> [WholeRepoCallEdge]-extractModuleEdges indices (fp, prog) =- let curMod = filePathToModuleName fp- localCG = buildCallGraph prog- in mapMaybe (convertLocalEdge indices curMod fp) (cgEdges localCG)+ let summaries = map (uncurry extractFileGraphSummary) modules+ in buildWholeRepoCallGraphFromSummaries summaries convertLocalEdge :: SymbolIndices -> Text -> FilePath+ -> Set Text -> CallEdge -> Maybe WholeRepoCallEdge-convertLocalEdge indices curMod curPath (CallEdge caller callee cnt isAsync) =+convertLocalEdge indices curMod curPath curImports (CallEdge caller callee cnt isAsync) = let callerSym = resolveCaller indices curMod curPath caller- in case resolveTarget indices curMod curPath callee of+ in case resolveTarget indices curMod curPath curImports callee of Nothing -> Nothing Just calleeSym -> let isCross = symModule callerSym /= symModule calleeSym@@ -415,157 +601,8 @@ -- | Extract inter-procedural data-flow graphs across module boundaries. buildWholeRepoDataFlow :: [(FilePath, Program)] -> WholeRepoDataFlowGraph buildWholeRepoDataFlow modules =- let allSymbols = collectGlobalSymbols modules- indices = buildSymbolIndices allSymbols- edges = concatMap (extractModuleDataFlow indices) modules- uniqueEdges = sort (nub edges)- nodes = sort (nub (allSymbols ++ map ipdfSourceSymbol uniqueEdges ++ map ipdfTargetSymbol uniqueEdges))- in WholeRepoDataFlowGraph nodes uniqueEdges--extractModuleDataFlow- :: SymbolIndices- -> (FilePath, Program)- -> [InterProceduralDataFlowEdge]-extractModuleDataFlow indices (fp, prog) =- let curMod = filePathToModuleName fp- allImports = concatMap modImports (progModules prog)- impMap = buildImportMap allImports- in concatMap (extractModuleDeclsDataFlow indices curMod fp impMap) (progModules prog)--extractModuleDeclsDataFlow- :: SymbolIndices- -> Text- -> FilePath- -> Map Text (Text, Text)- -> Module- -> [InterProceduralDataFlowEdge]-extractModuleDeclsDataFlow indices curMod curPath impMap (Module _ _ decls stmts) =- let topSym = GlobalSymbol curPath curMod "<top-level>" KindFunction (Fingerprint "top")- topEdges = concatMap (extractStmtDataFlow indices curMod curPath impMap topSym) stmts- declEdges = concatMap (extractDeclDataFlow indices curMod curPath impMap) decls- in topEdges ++ declEdges--extractDeclDataFlow- :: SymbolIndices- -> Text- -> FilePath- -> Map Text (Text, Text)- -> Declaration- -> [InterProceduralDataFlowEdge]-extractDeclDataFlow indices curMod curPath impMap = \case- DeclFunction fn ->- let callerSym = resolveCaller indices curMod curPath (CallFunction (fnName fn))- in concatMap (extractStmtDataFlow indices curMod curPath impMap callerSym) (fnBody fn)-- DeclClass cls ->- let extractMethod m =- let callerSym = resolveCaller indices curMod curPath (CallMethod (clsName cls) (fnName m))- in concatMap (extractStmtDataFlow indices curMod curPath impMap callerSym) (fnBody m)- in concatMap extractMethod (clsMethods cls)-- DeclStruct st ->- let extractMethod m =- let callerSym = resolveCaller indices curMod curPath (CallMethod (stName st) (fnName m))- in concatMap (extractStmtDataFlow indices curMod curPath impMap callerSym) (fnBody m)- in concatMap extractMethod (stMethods st)-- DeclTrait tr ->- let extractMethod m =- let callerSym = resolveCaller indices curMod curPath (CallMethod (trName tr) (fnName m))- in concatMap (extractStmtDataFlow indices curMod curPath impMap callerSym) (fnBody m)- in concatMap extractMethod (trMethods tr)-- DeclImpl imp ->- let extractMethod m =- let callerSym = resolveCaller indices curMod curPath (CallMethod (impTarget imp) (fnName m))- in concatMap (extractStmtDataFlow indices curMod curPath impMap callerSym) (fnBody m)- in concatMap extractMethod (impMethods imp)-- DeclReceiver rc fn ->- let callerSym = resolveCaller indices curMod curPath (CallMethod (rcTypeName rc) (fnName fn))- in concatMap (extractStmtDataFlow indices curMod curPath impMap callerSym) (fnBody fn)-- _ -> []--extractStmtDataFlow- :: SymbolIndices- -> Text- -> FilePath- -> Map Text (Text, Text)- -> GlobalSymbol- -> Stmt- -> [InterProceduralDataFlowEdge]-extractStmtDataFlow indices curMod curPath impMap callerSym stmt =- let calls = collectStmtCalls stmt- in concatMap (callToFlowEdges indices curMod curPath impMap callerSym) calls--callToFlowEdges- :: SymbolIndices- -> Text- -> FilePath- -> Map Text (Text, Text)- -> GlobalSymbol- -> (Expr, [Expr], [(Text, Expr)])- -> [InterProceduralDataFlowEdge]-callToFlowEdges indices curMod curPath impMap callerSym (calleeExpr, args, kwargs) =- let target = resolveExprCalleeTarget impMap calleeExpr- in case resolveTarget indices curMod curPath target of- Nothing -> []- Just calleeSym ->- let argEdges = concat- [ let vars = collectExprVars arg- in if Set.null vars- then [ InterProceduralDataFlowEdge- { ipdfSourceSymbol = callerSym- , ipdfTargetSymbol = calleeSym- , ipdfParamIndex = idx- , ipdfVarName = "<const>"- , ipdfIsReturnFlow = False- }- ]- else [ InterProceduralDataFlowEdge- { ipdfSourceSymbol = callerSym- , ipdfTargetSymbol = calleeSym- , ipdfParamIndex = idx- , ipdfVarName = v- , ipdfIsReturnFlow = False- }- | v <- Set.toList vars- ]- | (idx, arg) <- zip [0..] args- ]- kwEdges = concat- [ let vars = collectExprVars val- in if Set.null vars- then [ InterProceduralDataFlowEdge- { ipdfSourceSymbol = callerSym- , ipdfTargetSymbol = calleeSym- , ipdfParamIndex = -2- , ipdfVarName = k <> "=<const>"- , ipdfIsReturnFlow = False- }- ]- else [ InterProceduralDataFlowEdge- { ipdfSourceSymbol = callerSym- , ipdfTargetSymbol = calleeSym- , ipdfParamIndex = -2- , ipdfVarName = k <> "=" <> v- , ipdfIsReturnFlow = False- }- | v <- Set.toList vars- ]- | (k, val) <- kwargs- ]- returnEdge =- [ InterProceduralDataFlowEdge- { ipdfSourceSymbol = calleeSym- , ipdfTargetSymbol = callerSym- , ipdfParamIndex = -1- , ipdfVarName = "<return>"- , ipdfIsReturnFlow = True- }- ]- in argEdges ++ kwEdges ++ returnEdge+ let summaries = map (uncurry extractFileGraphSummary) modules+ in buildWholeRepoDataFlowFromSummaries summaries collectExprCalls :: Expr -> [(Expr, [Expr], [(Text, Expr)])] collectExprCalls = \case@@ -785,20 +822,26 @@ incrementalUpdateWholeRepoCallGraph oldWCG allModules modifiedFiles | null modifiedFiles = oldWCG | otherwise =- let modifiedMods = Set.fromList (map filePathToModuleName modifiedFiles)- -- Retain all edges whose caller is NOT in the modified modules+ let summaries = map (uncurry extractFileGraphSummary) allModules+ allSymbols = concatMap fgsSymbols summaries+ barrelMap = buildBarrelMapFromSummaries summaries+ indices = buildSymbolIndices allSymbols barrelMap+ modSet = Set.fromList modifiedFiles retainedEdges = [ e | e <- wcgEdges oldWCG- , not (Set.member (symModule (wceCaller e)) modifiedMods)+ , not (Set.member (symFilePath (wceCaller e)) modSet) ]- -- Extract new outgoing edges from modified programs- modifiedPrograms = filter (\(fp, _) -> fp `elem` modifiedFiles) allModules- allSymbols = collectGlobalSymbols allModules- indices = buildSymbolIndices allSymbols- newEdges = concatMap (extractModuleEdges indices) modifiedPrograms+ modSummaries = filter (\s -> Set.member (fgsFilePath s) modSet) summaries+ newEdges =+ [ edge+ | s <- modSummaries+ , let curImps = Set.fromList (fgsImportedMods s)+ , ce <- fgsCallEdges s+ , Just edge <- [convertLocalEdge indices (fgsModuleName s) (fgsFilePath s) curImps ce]+ ] combinedEdges = consolidateWholeRepoEdges (retainedEdges ++ newEdges)- nodes = sort (nub (allSymbols ++ map wceCaller combinedEdges ++ map wceCallee combinedEdges))+ nodes = Set.toAscList (Set.fromList (allSymbols ++ map wceCaller combinedEdges ++ map wceCallee combinedEdges)) sccs = tarjanWholeRepoSCC nodes combinedEdges in WholeRepoCallGraph nodes combinedEdges sccs @@ -811,18 +854,20 @@ incrementalUpdateWholeRepoDataFlow oldWDF allModules modifiedFiles | null modifiedFiles = oldWDF | otherwise =- let modifiedMods = Set.fromList (map filePathToModuleName modifiedFiles)+ let summaries = map (uncurry extractFileGraphSummary) allModules+ allSymbols = concatMap fgsSymbols summaries+ barrelMap = buildBarrelMapFromSummaries summaries+ indices = buildSymbolIndices allSymbols barrelMap+ modSet = Set.fromList modifiedFiles retainedEdges = [ e | e <- wdfEdges oldWDF- , not (Set.member (symModule (ipdfSourceSymbol e)) modifiedMods)+ , not (Set.member (symFilePath (ipdfSourceSymbol e)) modSet) ]- modifiedPrograms = filter (\(fp, _) -> fp `elem` modifiedFiles) allModules- allSymbols = collectGlobalSymbols allModules- indices = buildSymbolIndices allSymbols- newEdges = concatMap (extractModuleDataFlow indices) modifiedPrograms- uniqueEdges = sort (nub (retainedEdges ++ newEdges))- nodes = sort (nub (allSymbols ++ map ipdfSourceSymbol uniqueEdges ++ map ipdfTargetSymbol uniqueEdges))+ modSummaries = filter (\s -> Set.member (fgsFilePath s) modSet) summaries+ newEdges = concatMap (summaryToDataFlowEdges indices) modSummaries+ uniqueEdges = Set.toAscList (Set.fromList (retainedEdges ++ newEdges))+ nodes = Set.toAscList (Set.fromList (allSymbols ++ map ipdfSourceSymbol uniqueEdges ++ map ipdfTargetSymbol uniqueEdges)) in WholeRepoDataFlowGraph nodes uniqueEdges -- | Incrementally updates WholeRepoCallGraph, WholeRepoDataFlowGraph, and their CSR graphs@@ -848,3 +893,137 @@ !fwcg = hashBytes (canonicalizeWholeRepoCallGraph newWCG) !fwdf = hashBytes (canonicalizeWholeRepoDataFlow newWDF) in (newWCG, newWDF, cgCSR, dfCSR, fwcg, fwdf)++-- ============================================================================+-- Per-File Graph Summaries for CNTR\x07 Incremental Whole-Repo Synthesis+-- ============================================================================++-- | Compact serializable inter-procedural call-site data-flow summary.+data CallFlowSite = CallFlowSite+ { cfsCaller :: !CallerNode+ , cfsCallee :: !CalleeTarget+ , cfsPosArgs :: ![[Text]] -- ^ Empty list indicates "<const>"+ , cfsKwArgs :: ![(Text, [Text])] -- ^ Empty list indicates k <> "=<const>"+ } deriving stock (Eq, Ord, Show, Generic)+ deriving anyclass (NFData)++-- | Compact per-file symbol, import, barrel re-export, call-edge, and data-flow summary persisted in CNTR\x07.+-- Enables whole-repository graph synthesis on warm/dirty runs without re-parsing+-- untouched files from disk.+data FileGraphSummary = FileGraphSummary+ { fgsFilePath :: !FilePath+ , fgsModuleName :: !Text+ , fgsImportedMods :: ![Text]+ , fgsReExports :: ![(Text, Text, Text)]+ , fgsSymbols :: ![GlobalSymbol]+ , fgsCallEdges :: ![CallEdge]+ , fgsFlowSites :: ![CallFlowSite]+ } deriving stock (Eq, Ord, Show, Generic)+ deriving anyclass (NFData)++isDynamicTarget :: CalleeTarget -> Bool+isDynamicTarget (TargetDynamic _) = True+isDynamicTarget _ = False++-- | Extract a compact 'FileGraphSummary' from a single parsed 'Program'.+extractFileGraphSummary :: FilePath -> Program -> FileGraphSummary+extractFileGraphSummary fp prog =+ let !pathMod = filePathToModuleName fp+ !curMod = case progModules prog of+ (m : _) -> effectiveModuleName fp pathMod (modName m)+ [] -> pathMod+ !(impMods, reExps) = extractImportsAndBarrels fp prog+ !syms = extractProgramSymbols fp prog+ !localCG = buildCallGraph prog+ !callEdges = filter (not . isDynamicTarget . edgeCallee) (cgEdges localCG)+ !allImports = concatMap modImports (progModules prog)+ !impMap = buildImportMap allImports+ !flowSites = concatMap (extractModFlowSites impMap) (progModules prog)+ in FileGraphSummary fp curMod impMods reExps syms callEdges flowSites+ where+ extractModFlowSites impMap (Module _ _ decls stmts) =+ let topSites = concatMap (stmtToFlowSites impMap CallTopLevel) stmts+ declSites = concatMap (declToFlowSites impMap) decls+ in topSites ++ declSites++ declToFlowSites impMap = \case+ DeclFunction fn ->+ concatMap (stmtToFlowSites impMap (CallFunction (fnName fn))) (fnBody fn)+ DeclClass cls ->+ concatMap (\m -> concatMap (stmtToFlowSites impMap (CallMethod (clsName cls) (fnName m))) (fnBody m)) (clsMethods cls)+ DeclStruct st ->+ concatMap (\m -> concatMap (stmtToFlowSites impMap (CallMethod (stName st) (fnName m))) (fnBody m)) (stMethods st)+ DeclTrait tr ->+ concatMap (\m -> concatMap (stmtToFlowSites impMap (CallMethod (trName tr) (fnName m))) (fnBody m)) (trMethods tr)+ DeclImpl imp ->+ concatMap (\m -> concatMap (stmtToFlowSites impMap (CallMethod (impTarget imp) (fnName m))) (fnBody m)) (impMethods imp)+ DeclReceiver rc fn ->+ concatMap (stmtToFlowSites impMap (CallMethod (rcTypeName rc) (fnName fn))) (fnBody fn)+ _ -> []++ stmtToFlowSites impMap caller stmt =+ [ CallFlowSite caller target posArgs kwArgs+ | (calleeExpr, args, kwargs) <- collectStmtCalls stmt+ , let target = resolveExprCalleeTarget impMap calleeExpr+ , not (isDynamicTarget target)+ , let posArgs = [Set.toAscList (collectExprVars arg) | arg <- args]+ , let kwArgs = [(k, Set.toAscList (collectExprVars val)) | (k, val) <- kwargs]+ ]++-- | Synthesize 'WholeRepoCallGraph' directly from cached 'FileGraphSummary' records+-- with zero AST re-parsing. Produces bit-identical output to 'buildWholeRepoCallGraph'.+buildWholeRepoCallGraphFromSummaries :: [FileGraphSummary] -> WholeRepoCallGraph+buildWholeRepoCallGraphFromSummaries summaries =+ let allSymbols = concatMap fgsSymbols summaries+ barrelMap = buildBarrelMapFromSummaries summaries+ indices = buildSymbolIndices allSymbols barrelMap+ rawEdges =+ [ edge+ | s <- summaries+ , let curImps = Set.fromList (fgsImportedMods s)+ , ce <- fgsCallEdges s+ , Just edge <- [convertLocalEdge indices (fgsModuleName s) (fgsFilePath s) curImps ce]+ ]+ consolidatedEdges = consolidateWholeRepoEdges rawEdges+ allNodes = Set.toAscList (Set.fromList (allSymbols ++ map wceCaller consolidatedEdges ++ map wceCallee consolidatedEdges))+ sccs = tarjanWholeRepoSCC allNodes consolidatedEdges+ in WholeRepoCallGraph allNodes consolidatedEdges sccs++-- | Synthesize 'WholeRepoDataFlowGraph' directly from cached 'FileGraphSummary' records+-- with zero AST re-parsing. Produces bit-identical output to 'buildWholeRepoDataFlow'.+buildWholeRepoDataFlowFromSummaries :: [FileGraphSummary] -> WholeRepoDataFlowGraph+buildWholeRepoDataFlowFromSummaries summaries =+ let allSymbols = concatMap fgsSymbols summaries+ barrelMap = buildBarrelMapFromSummaries summaries+ indices = buildSymbolIndices allSymbols barrelMap+ edges = concatMap (summaryToDataFlowEdges indices) summaries+ uniqueEdges = Set.toAscList (Set.fromList edges)+ nodes = Set.toAscList (Set.fromList (allSymbols ++ map ipdfSourceSymbol uniqueEdges ++ map ipdfTargetSymbol uniqueEdges))+ in WholeRepoDataFlowGraph nodes uniqueEdges++summaryToDataFlowEdges :: SymbolIndices -> FileGraphSummary -> [InterProceduralDataFlowEdge]+summaryToDataFlowEdges indices s =+ let curMod = fgsModuleName s+ curPath = fgsFilePath s+ curImps = Set.fromList (fgsImportedMods s)+ in concatMap (siteToEdges curMod curPath curImps) (fgsFlowSites s)+ where+ siteToEdges curMod curPath curImps CallFlowSite{..} =+ let callerSym = resolveCaller indices curMod curPath cfsCaller+ in case resolveTarget indices curMod curPath curImps cfsCallee of+ Nothing -> []+ Just calleeSym ->+ let argEdges = concat+ [ if null vars+ then [InterProceduralDataFlowEdge callerSym calleeSym idx "<const>" False]+ else [InterProceduralDataFlowEdge callerSym calleeSym idx v False | v <- vars]+ | (idx, vars) <- zip [0..] cfsPosArgs+ ]+ kwEdges = concat+ [ if null vars+ then [InterProceduralDataFlowEdge callerSym calleeSym (-2) (k <> "=<const>") False]+ else [InterProceduralDataFlowEdge callerSym calleeSym (-2) (k <> "=" <> v) False | v <- vars]+ | (k, vars) <- cfsKwArgs+ ]+ retEdge = [InterProceduralDataFlowEdge calleeSym callerSym (-1) "<return>" True]+ in argEdges ++ kwEdges ++ retEdge
src/Canontra/CLI/Cache.hs view
@@ -3,10 +3,10 @@ {- | Module : Canontra.CLI.Cache-Description : Cache maintenance tooling for canontra v0.3.0.+Description : Cache maintenance tooling for canontra v0.4.0. Provides subcommands for inspecting, verifying, cleaning, and pruning-the CNTR\x06 memory-mapped slab cache (.canontra/cache.bin).+CNTR\x07, CNTR\x06, and CNTR\x05 binary caches (.canontra/cache.bin). -} module Canontra.CLI.Cache ( CacheAction (..)@@ -20,19 +20,65 @@ import qualified Data.ByteString.Lazy.Char8 as LBSC import qualified Data.Map.Strict as Map import qualified Data.Text as T+import Data.Word (Word16, Word32) import System.Directory (doesFileExist, removeFile) import System.Exit (ExitCode (..), exitWith) import System.FilePath ((</>)) import System.IO (hPutStrLn, stderr) -import Canontra.Cache.Common (MerkleCache (..))+import Canontra.Cache.Common (MerkleCache (..), readWord16LE, readWord32LE) import Canontra.Cache.PagedCache ( decodeBinaryCacheV5WithRecovery , readPagedCacheFileResilient , verifyHeaderCRC , writePagedCacheFile )+import Canontra.Cache.SlabV6+ ( decodeSlabV6Resilient+ , readSlabCacheFileResilient+ , verifySlabHeaderCRC+ , writeSlabCacheFile+ )+import Canontra.Cache.SlabV7+ ( decodeSlabV7Resilient+ , readSlabV7FileResilient+ , verifySlabV7HeaderCRC+ , writeSlabV7File+ ) +detectCacheVersion :: BS.ByteString -> Word16+detectCacheVersion bs+ | BS.length bs >= 6 && BS.take 4 bs == "CNTR" = readWord16LE bs 4+ | otherwise = 0++inspectCacheStats :: BS.ByteString -> (T.Text, T.Text, Bool, Int, Int, [Word32])+inspectCacheStats rawBytes =+ let sizeBytes = BS.length rawBytes+ ver = detectCacheVersion rawBytes+ in case ver of+ 7 ->+ let headerOk = verifySlabV7HeaderCRC rawBytes+ (entries, _, corrupted) = decodeSlabV7Resilient rawBytes+ cap = if BS.length rawBytes >= 16 then fromIntegral (readWord32LE rawBytes 12) else 0+ slabStart = 2080 + cap * 64+ slabCount = if sizeBytes > slabStart then (sizeBytes - slabStart + 4095) `div` 4096 else 0+ in ("CNTR\\x07", "4KB Incremental Graph Slab Cache", headerOk, Map.size entries, slabCount, corrupted)+ 6 ->+ let headerOk = verifySlabHeaderCRC rawBytes+ (entries, _, corrupted) = decodeSlabV6Resilient rawBytes+ cap = if BS.length rawBytes >= 16 then fromIntegral (readWord32LE rawBytes 12) else 0+ slabStart = 2080 + cap * 64+ slabCount = if sizeBytes > slabStart then (sizeBytes - slabStart + 4095) `div` 4096 else 0+ in ("CNTR\\x06", "4KB Memory-Mapped Slab Cache", headerOk, Map.size entries, slabCount, corrupted)+ _ ->+ let headerOk = verifyHeaderCRC rawBytes+ (mCache, corrupted) = decodeBinaryCacheV5WithRecovery rawBytes+ entryCount = case mCache of+ Just c -> Map.size (unMerkleCache c)+ Nothing -> 0+ slabCount = sizeBytes `div` 4096+ in ("CNTR\\x05", "4KB Paged Radix Cache", headerOk, entryCount, slabCount, corrupted)+ -- | Target operation for the 'canontra cache' command. data CacheAction = CacheInfo@@ -74,12 +120,7 @@ else do rawBytes <- BS.readFile cacheFile let sizeBytes = BS.length rawBytes- headerOk = verifyHeaderCRC rawBytes- (mCache, corrupted) = decodeBinaryCacheV5WithRecovery rawBytes- entryCount = case mCache of- Just c -> Map.size (unMerkleCache c)- Nothing -> 0- slabCount = sizeBytes `div` 4096+ (verLabel, verDesc, headerOk, entryCount, slabCount, corrupted) = inspectCacheStats rawBytes if asJson then LBSC.putStrLn $ AesonPretty.encodePretty $ object@@ -88,7 +129,7 @@ , "size_bytes" .= sizeBytes , "entries_count" .= entryCount , "slab_pages_count" .= slabCount- , "format_version" .= ("CNTR\\x05" :: T.Text)+ , "format_version" .= verLabel , "header_crc_valid" .= headerOk , "corrupted_pages_count".= length corrupted ]@@ -97,7 +138,7 @@ putStrLn " CANONTRA CACHE INFO" putStrLn "================================================================================" putStrLn $ " Cache File: " ++ cacheFile- putStrLn $ " Format Version: CNTR\\x05 (4KB Paged Radix Cache)"+ putStrLn $ " Format Version: " ++ T.unpack verLabel ++ " (" ++ T.unpack verDesc ++ ")" putStrLn $ " File Size: " ++ show sizeBytes ++ " bytes (" ++ show (sizeBytes `div` 1024) ++ " KB)" putStrLn $ " Indexed Files: " ++ show entryCount ++ " records" putStrLn $ " Slab Pages: " ++ show slabCount ++ " pages (4096 bytes/page)"@@ -124,11 +165,8 @@ exitWith (ExitFailure 4) else do rawBytes <- BS.readFile cacheFile- let sizeBytes = BS.length rawBytes- headerOk = verifyHeaderCRC rawBytes- (_, corrupted) = decodeBinaryCacheV5WithRecovery rawBytes- totalSlabs = sizeBytes `div` 4096- validSlabs = totalSlabs - length corrupted+ let (_, _, headerOk, _, totalSlabs, corrupted) = inspectCacheStats rawBytes+ validSlabs = max 0 (totalSlabs - length corrupted) isClean = headerOk && null corrupted if asJson@@ -206,18 +244,40 @@ else do putStrLn $ "No active cache to prune at: " ++ cacheFile else do- cache <- readPagedCacheFileResilient cacheFile- let allEntries = Map.toList (unMerkleCache cache)- originalCount = length allEntries- keptEntries <- filterM (\(normPath, _) -> doesFileExist (rootDir </> normPath)) allEntries- let retainedCount = length keptEntries- prunedCount = originalCount - retainedCount-- if prunedCount > 0- then do- let updatedCache = MerkleCache (Map.fromList keptEntries)- writePagedCacheFile cacheFile updatedCache- else pure ()+ rawBytes <- BS.readFile cacheFile+ let ver = detectCacheVersion rawBytes+ (originalCount, retainedCount) <- case ver of+ 7 -> do+ (entriesMap, mRepo, _) <- readSlabV7FileResilient cacheFile+ let allEntries = Map.toList entriesMap+ origCount = length allEntries+ keptEntries <- filterM (\(normPath, _) -> doesFileExist (rootDir </> normPath)) allEntries+ let retCount = length keptEntries+ if origCount - retCount > 0+ then writeSlabV7File cacheFile (map snd keptEntries) mRepo+ else pure ()+ pure (origCount, retCount)+ 6 -> do+ (entriesMap, mRepo, _) <- readSlabCacheFileResilient cacheFile+ let allEntries = Map.toList entriesMap+ origCount = length allEntries+ keptEntries <- filterM (\(normPath, _) -> doesFileExist (rootDir </> normPath)) allEntries+ let retCount = length keptEntries+ if origCount - retCount > 0+ then writeSlabCacheFile cacheFile [(p, m, b) | (p, (m, b)) <- keptEntries] mRepo+ else pure ()+ pure (origCount, retCount)+ _ -> do+ cache <- readPagedCacheFileResilient cacheFile+ let allEntries = Map.toList (unMerkleCache cache)+ origCount = length allEntries+ keptEntries <- filterM (\(normPath, _) -> doesFileExist (rootDir </> normPath)) allEntries+ let retCount = length keptEntries+ if origCount - retCount > 0+ then writePagedCacheFile cacheFile (MerkleCache (Map.fromList keptEntries))+ else pure ()+ pure (origCount, retCount)+ let prunedCount = originalCount - retainedCount if asJson then LBSC.putStrLn $ AesonPretty.encodePretty $ object
src/Canontra/CLI/Commands.hs view
@@ -3,17 +3,19 @@ {- | Module : Canontra.CLI.Commands-Description : Command-line argument parsing and command dispatch for v0.3.0.+Description : Command-line argument parsing and command dispatch for v0.4.0. This module provides the entrypoint parser for all canontra CLI operations, dispatching commands for polyglot multi-tier fingerprinting (including stdin streaming), invariant comparison, fine-grained structural diff diagnostics, graph inspections, determinism verification, repository manifest generation, incremental caching,-cache maintenance (info, verify, clean, prune), machine interchange exports (SARIF, DOT),+cache maintenance (info, verify, clean, prune), stateless AI harness semantic+sub-versioning (@canontra snap@), machine interchange exports (SARIF, DOT), shell autocompletions (bash, zsh, fish, powershell), and git history evolution tracking. -} module Canontra.CLI.Commands ( Command (..)+ , SnapAction (..) , OutputFormat (..) , ExportFormat (..) , runCLI@@ -28,7 +30,6 @@ import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Lazy.Char8 as LBSC-import Data.List (nub, sort) import qualified Data.Map.Strict as Map import qualified Data.Set as Set import qualified Data.Text as T@@ -69,6 +70,31 @@ import Canontra.Export.SARIF (exportDiffSARIF, renderSARIF) import Canontra.Fingerprint.Bundle (computeBundle, computeManifest) import Canontra.Fingerprint.Dependency (extractRichDependencyGraph)+import Canontra.Harness.Guard+ ( formatSnapGuard+ , formatSnapGuardJson+ , parseGuardTiers+ , sgrPassed+ , snapGuard+ )+import Canontra.Harness.SubVersion+ ( formatSnapDiff+ , formatSnapDiffJson+ , formatSnapGC+ , formatSnapGCJson+ , formatSnapLog+ , formatSnapLogJson+ , formatSnapManifest+ , formatSnapManifestJson+ , formatSnapRewind+ , formatSnapRewindJson+ , snapDiff+ , snapGC+ , snapInit+ , snapLog+ , snapMark+ , snapRewind+ ) import Canontra.IR.Program (Program) import Canontra.Normalize.Rules (engineName, engineVersion) import Canontra.Parser.Polyglot (parsePolyglotSource)@@ -86,6 +112,17 @@ data ExportFormat = ExportSARIF | ExportDOT deriving stock (Eq, Show) +-- | Subcommands for the stateless AI harness semantic sub-versioning engine (@canontra snap@).+data SnapAction+ = SnapInit+ | SnapMark !(Maybe T.Text) !(Maybe T.Text) !Bool+ | SnapDiff !T.Text !T.Text !Bool+ | SnapGuard !T.Text !T.Text ![T.Text]+ | SnapRewind !T.Text ![FilePath] !Bool+ | SnapLog !Int+ | SnapGC !Int+ deriving stock (Eq, Show)+ data Command = CmdFingerprint FilePath (Maybe String) OutputFormat | CmdCompare FilePath FilePath Bool Bool@@ -100,6 +137,7 @@ | CmdEvolution String String Bool | CmdWatch FilePath Int Int Bool -- path, debounceMs, pollMs, verbose | CmdCache CacheAction FilePath Bool+ | CmdSnap SnapAction FilePath Bool | CmdExport FilePath ExportFormat (Maybe FilePath) (Maybe FilePath) (Maybe String) | CmdCompletions ShellType | CmdVersion@@ -311,6 +349,10 @@ d <- validateSafePath dir runCacheCommand cAct d asJson + CmdSnap sAct dir asJson -> do+ d <- validateSafePath dir+ runSnapCommand sAct d asJson+ CmdExport path fmt mOut mBase mGraph -> do runExport path fmt mOut mBase mGraph @@ -490,6 +532,81 @@ then LBSC.putStrLn (AesonPretty.encodePretty manifest) else TIO.putStrLn (formatRepositoryManifest manifest) +runSnapCommand :: SnapAction -> FilePath -> Bool -> IO ()+runSnapCommand snapAct repoDir asJson = case snapAct of+ SnapInit -> do+ res <- snapInit repoDir+ case res of+ Left err -> outputIOError err+ Right man -> do+ if asJson+ then LBSC.putStrLn (formatSnapManifestJson man)+ else TIO.putStrLn (formatSnapManifest False man)+ exitSuccess++ SnapMark mLabel mAgent skipNoop -> do+ res <- snapMark repoDir mLabel mAgent skipNoop+ case res of+ Left err -> outputIOError err+ Right (man, noop) -> do+ if asJson+ then LBSC.putStrLn (formatSnapManifestJson man)+ else TIO.putStrLn (formatSnapManifest noop man)+ exitSuccess++ SnapDiff refA refB compact -> do+ res <- snapDiff repoDir refA refB compact+ case res of+ Left err -> outputIOError err+ Right rep -> do+ if asJson+ then LBSC.putStrLn (formatSnapDiffJson compact rep)+ else TIO.putStrLn (formatSnapDiff compact rep)+ exitSuccess++ SnapGuard againstRef forbidRaw allowGlobs ->+ case parseGuardTiers forbidRaw of+ Left err -> outputIOError err+ Right tiers -> do+ res <- snapGuard repoDir againstRef tiers allowGlobs+ case res of+ Left err -> outputIOError err+ Right rep -> do+ if asJson+ then LBSC.putStrLn (formatSnapGuardJson rep)+ else TIO.putStrLn (formatSnapGuard rep)+ if sgrPassed rep then exitSuccess else exitWith (ExitFailure 1)++ SnapRewind targetRef files dryRun -> do+ res <- snapRewind repoDir targetRef files dryRun+ case res of+ Left err -> outputIOError err+ Right rep -> do+ if asJson+ then LBSC.putStrLn (formatSnapRewindJson rep)+ else TIO.putStrLn (formatSnapRewind rep)+ exitSuccess++ SnapLog limitN -> do+ res <- snapLog repoDir limitN+ case res of+ Left err -> outputIOError err+ Right (mHead, entries) -> do+ if asJson+ then LBSC.putStrLn (formatSnapLogJson mHead entries)+ else TIO.putStrLn (formatSnapLog mHead entries)+ exitSuccess++ SnapGC keepLast -> do+ res <- snapGC repoDir keepLast+ case res of+ Left err -> outputIOError err+ Right rep -> do+ if asJson+ then LBSC.putStrLn (formatSnapGCJson rep)+ else TIO.putStrLn (formatSnapGC rep)+ exitSuccess+ loadRepoPrograms :: FilePath -> [FilePath] -> IO [(FilePath, Program)] loadRepoPrograms repoDir fullPaths = do results <- forM fullPaths $ \full -> do@@ -573,7 +690,7 @@ then outputIOError ("Failed to diff against PR base '" ++ prBaseRef ++ "': " ++ stderrStr) else do let rawChanged = filter (not . null) (lines stdoutStr)- changedFiles = sort (nub [normalizePathPosix f | f <- rawChanged, isSupportedPolyglotExt f])+ changedFiles = Set.toAscList (Set.fromList [normalizePathPosix f | f <- rawChanged, isSupportedPolyglotExt f]) deltas <- forM changedFiles $ \relPath -> do let fullPath = repoDir </> relPath newExists <- doesFileExist fullPath@@ -647,7 +764,7 @@ exitWith (ExitFailure 1) else do let targetSym = head candidateMatches- directCallers = sort (nub [wceCaller e | e <- wcgEdges wcg, wceCallee e == targetSym])+ directCallers = Set.toAscList (Set.fromList [wceCaller e | e <- wcgEdges wcg, wceCallee e == targetSym]) invAdj = Map.fromListWith (++) [(wceCallee e, [wceCaller e]) | e <- wcgEdges wcg] bfs [] _ acc = acc bfs (curr:queue) visited acc@@ -657,10 +774,10 @@ newVisited = Set.insert curr visited newAcc = if curr /= targetSym then curr : acc else acc in bfs (queue ++ callers) newVisited newAcc- transitiveCallers = sort (nub (bfs [targetSym] Set.empty []))- impactedFiles = sort (nub (map (normalizePathPosix . symFilePath) (directCallers ++ transitiveCallers)))+ transitiveCallers = Set.toAscList (Set.fromList (bfs [targetSym] Set.empty []))+ impactedFiles = Set.toAscList (Set.fromList (map (normalizePathPosix . symFilePath) (directCallers ++ transitiveCallers))) impactedTests = findMatchingTests (normalizePathPosix (symFilePath targetSym) : impactedFiles) normAllFiles- callees = sort (nub [wceCallee e | e <- wcgEdges wcg, wceCaller e == targetSym])+ callees = Set.toAscList (Set.fromList [wceCallee e | e <- wcgEdges wcg, wceCaller e == targetSym]) if asJson then do@@ -733,8 +850,8 @@ cliParserInfo :: ParserInfo Command cliParserInfo = info (parseCLIArgs <**> helper) ( fullDesc- <> progDesc "canontra - High-Throughput Polyglot Deterministic Program Fingerprinting & Deep Semantic Graph Engine"- <> header "canontra v0.3.0"+ <> progDesc "canontra - Ultra-Low-Latency Polyglot Deterministic Program Fingerprinting & Deep Semantic Graph Engine"+ <> header ("canontra v" ++ T.unpack engineVersion) ) parseCLIArgs :: Parser Command@@ -755,6 +872,7 @@ <> command "commit" (info (parseCommit <**> helper) (progDesc "Fingerprint repository at a git commit")) <> command "evolution" (info (parseEvolution <**> helper) (progDesc "Compare repository evolution across two git revisions")) <> command "cache" (info (parseCache <**> helper) (progDesc "Inspect, verify, clean, or prune incremental binary cache"))+ <> command "snap" (info (parseSnap <**> helper) (progDesc "Stateless AI harness semantic sub-versioning (alpha)")) <> command "export" (info (parseExport <**> helper) (progDesc "Export diagnostics (SARIF v2.1.0) or graphs (Graphviz DOT)")) <> command "completions" (info (parseCompletions <**> helper) (progDesc "Generate shell autocompletions (bash, zsh, fish, powershell)")) <> command "version" (info (pure CmdVersion <**> helper) (progDesc "Display engine version"))@@ -851,6 +969,72 @@ ) <*> strOption (long "dir" <> short 'd' <> metavar "DIR" <> value "." <> showDefault <> help "Repository root directory") <*> switch (long "json" <> help "Output cache operation in JSON format")++data SnapOpts = SnapOpts+ { soDir :: !(Maybe FilePath)+ , soJson :: !Bool+ }++parseSnapOpts :: Parser SnapOpts+parseSnapOpts = SnapOpts+ <$> optional (strOption (long "dir" <> short 'd' <> metavar "DIR" <> help "Repository root directory (default: .)"))+ <*> switch (long "json" <> help "Output machine-readable JSON")++parseSnap :: Parser Command+parseSnap =+ combineSnap+ <$> parseSnapOpts+ <*> subparser+ ( command "init" (info (withOpts parseSnapInit <**> helper) (progDesc "Initialize .canontra/snaps/ and capture baseline snap_0"))+ <> command "mark" (info (withOpts parseSnapMark <**> helper) (progDesc "Record an incremental semantic checkpoint and classify tier deltas"))+ <> command "diff" (info (withOpts parseSnapDiff <**> helper) (progDesc "Show token-compact tiered semantic diff between snapshots"))+ <> command "guard" (info (withOpts parseSnapGuard <**> helper) (progDesc "Enforce forbidden fingerprint tiers against a baseline snapshot"))+ <> command "rewind" (info (withOpts parseSnapRewind <**> helper) (progDesc "Preflight-verified atomic workspace rollback to a snapshot"))+ <> command "log" (info (withOpts parseSnapLog <**> helper) (progDesc "Show chronological turn ledger entries"))+ <> command "gc" (info (withOpts parseSnapGC <**> helper) (progDesc "Prune old manifests and unreferenced CAS F0 blobs"))+ )+ where+ withOpts p = (,) <$> p <*> parseSnapOpts++ combineSnap outer (act, inner) =+ let dir = case soDir inner of+ Just d -> d+ Nothing -> case soDir outer of+ Just d -> d+ Nothing -> "."+ asJson = soJson outer || soJson inner+ in CmdSnap act dir asJson++ parseSnapInit = pure SnapInit++ parseSnapMark = SnapMark+ <$> optional (T.pack <$> strOption (long "label" <> short 'l' <> metavar "LABEL" <> help "Turn or checkpoint label"))+ <*> optional (T.pack <$> strOption (long "agent" <> short 'a' <> metavar "AGENT" <> help "AI harness or agent identifier"))+ <*> switch (long "skip-noop" <> help "Skip creating a new manifest when workspace F0 hashes are unchanged")++ parseSnapDiff = SnapDiff+ <$> fmap T.pack (strArgument (metavar "FROM" <> value "HEAD" <> showDefault <> help "Baseline snap ID, HEAD, or WORKTREE"))+ <*> fmap T.pack (strArgument (metavar "TO" <> value "WORKTREE" <> showDefault <> help "Target snap ID, HEAD, or WORKTREE"))+ <*> switch (long "compact" <> help "Omit trivia file listings for compact token budgets")++ parseSnapGuard = SnapGuard+ <$> fmap T.pack (strOption (long "against" <> metavar "SNAP_ID" <> value "HEAD" <> showDefault <> help "Baseline snap ID or HEAD"))+ <*> fmap T.pack (strOption (long "forbid" <> metavar "TIERS" <> help "Comma-separated forbidden tiers (e.g. F2,F3,F_T)"))+ <*> many (T.pack <$> strOption (long "allow-paths" <> metavar "GLOB" <> help "Glob pattern of paths exempt from forbidden tier checks"))++ parseSnapRewind = SnapRewind+ <$> fmap T.pack (strArgument (metavar "SNAP_ID" <> help "Target snap ID or HEAD to restore"))+ <*> ( (<>)+ <$> many (strOption (long "file" <> short 'f' <> metavar "PATH" <> help "Specific file path to restore (repeatable)"))+ <*> many (strArgument (metavar "FILES..." <> help "Optional file paths to restore (omit for full snapshot restore)"))+ )+ <*> switch (long "dry-run" <> help "Verify preflight hashes and preview restored/removed files without modifying disk")++ parseSnapLog = SnapLog+ <$> option auto (long "limit" <> short 'n' <> metavar "N" <> value 20 <> showDefault <> help "Maximum number of ledger entries to display")++ parseSnapGC = SnapGC+ <$> option auto (long "keep-last" <> metavar "N" <> value 50 <> showDefault <> help "Number of newest manifests to keep (snap_0 and HEAD always retained)") parseExportFormat :: Parser ExportFormat parseExportFormat =
src/Canontra/CLI/Completions.hs view
@@ -61,7 +61,7 @@ , " local cur prev words cword" , " _init_completion || return" , ""- , " local commands=\"fp fingerprint compare diff graph verify repository repo impact slice watch commit evolution cache export completions version\""+ , " local commands=\"fp fingerprint compare diff graph verify repository repo impact slice watch commit evolution cache export completions version snap\"" , "" , " if [ $cword -eq 1 ]; then" , " COMPREPLY=( $(compgen -W \"${commands}\" -- \"${cur}\") )"@@ -150,6 +150,15 @@ , " _filedir" , " fi" , " ;;"+ , " snap)"+ , " if [[ \"${cword}\" -eq 2 ]]; then"+ , " COMPREPLY=( $(compgen -W \"init mark diff guard rewind log gc\" -- \"${cur}\") )"+ , " elif [[ \"${cur}\" == -* ]]; then"+ , " COMPREPLY=( $(compgen -W \"--dir -d --json --label -l --agent -a --skip-noop --compact --against --forbid --allow-paths --file -f --dry-run --limit -n --keep-last --help\" -- \"${cur}\") )"+ , " else"+ , " _filedir"+ , " fi"+ , " ;;" , " *)" , " _filedir" , " ;;"@@ -183,6 +192,7 @@ , " 'commit:Fingerprint repository at a git commit'" , " 'evolution:Compare repository evolution across two git revisions'" , " 'cache:Inspect, verify, clean, or prune incremental binary cache'"+ , " 'snap:Stateless AI harness semantic sub-versioning (alpha)'" , " 'export:Export diagnostics (SARIF) or graphs (DOT)'" , " 'completions:Generate shell autocompletions'" , " 'version:Display engine version'"@@ -221,6 +231,9 @@ , " completions)" , " _arguments '1:shell:(bash zsh fish powershell)'" , " ;;"+ , " snap)"+ , " _arguments '1:subcommand:(init mark diff guard rewind log gc)' '*:option:(--dir --json --label --agent --skip-noop --compact --against --forbid --allow-paths --file --dry-run --limit --keep-last --help)'"+ , " ;;" , " *)" , " _files" , " ;;"@@ -251,6 +264,7 @@ , "complete -c canontra -n '__fish_use_subcommand' -a slice -d 'Trace upstream caller slice and dependencies'" , "complete -c canontra -n '__fish_use_subcommand' -a watch -d 'Start live terminal Merkle DAG watcher session'" , "complete -c canontra -n '__fish_use_subcommand' -a cache -d 'Inspect, verify, clean, or prune binary cache'"+ , "complete -c canontra -n '__fish_use_subcommand' -a snap -d 'Stateless AI harness semantic sub-versioning (alpha)'" , "complete -c canontra -n '__fish_use_subcommand' -a export -d 'Export diagnostics (SARIF) or graphs (DOT)'" , "complete -c canontra -n '__fish_use_subcommand' -a completions -d 'Generate shell autocompletions'" , "complete -c canontra -n '__fish_use_subcommand' -a version -d 'Display engine version'"@@ -261,6 +275,15 @@ , "complete -c canontra -n '__fish_seen_subcommand_from cache' -a clean -d 'Remove binary cache file'" , "complete -c canontra -n '__fish_seen_subcommand_from cache' -a prune -d 'Remove orphaned deleted records'" , ""+ , "# Snap subcommands"+ , "complete -c canontra -n '__fish_seen_subcommand_from snap' -a init -d 'Initialize baseline snap_0'"+ , "complete -c canontra -n '__fish_seen_subcommand_from snap' -a mark -d 'Record incremental semantic checkpoint'"+ , "complete -c canontra -n '__fish_seen_subcommand_from snap' -a diff -d 'Show token-compact tiered diff'"+ , "complete -c canontra -n '__fish_seen_subcommand_from snap' -a guard -d 'Enforce forbidden fingerprint tiers'"+ , "complete -c canontra -n '__fish_seen_subcommand_from snap' -a rewind -d 'Preflight-verified atomic rollback'"+ , "complete -c canontra -n '__fish_seen_subcommand_from snap' -a log -d 'Show chronological turn ledger'"+ , "complete -c canontra -n '__fish_seen_subcommand_from snap' -a gc -d 'Prune old manifests and CAS blobs'"+ , "" , "# Export options" , "complete -c canontra -n '__fish_seen_subcommand_from export' -s f -l format -x -a 'sarif dot' -d 'Export format'" , "complete -c canontra -n '__fish_seen_subcommand_from export' -s g -l graph -x -a 'calls cfg dfg' -d 'Graph type for DOT'"@@ -293,6 +316,7 @@ , " [System.Management.Automation.CompletionResult]::new('slice', 'slice', 'ParameterValue', 'Trace upstream caller slice and downstream dependencies')," , " [System.Management.Automation.CompletionResult]::new('watch', 'watch', 'ParameterValue', 'Start live terminal Merkle DAG watcher session')," , " [System.Management.Automation.CompletionResult]::new('cache', 'cache', 'ParameterValue', 'Inspect, verify, clean, or prune incremental binary cache'),"+ , " [System.Management.Automation.CompletionResult]::new('snap', 'snap', 'ParameterValue', 'Stateless AI harness semantic sub-versioning (alpha)')," , " [System.Management.Automation.CompletionResult]::new('export', 'export', 'ParameterValue', 'Export diagnostics (SARIF) or graphs (DOT)')," , " [System.Management.Automation.CompletionResult]::new('completions', 'completions', 'ParameterValue', 'Generate shell autocompletions')," , " [System.Management.Automation.CompletionResult]::new('version', 'version', 'ParameterValue', 'Display engine version')"@@ -309,6 +333,15 @@ , " 'cache' {" , " @('info', 'verify', 'clean', 'prune') | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {" , " [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', \"Cache $_\")"+ , " }"+ , " }"+ , " 'snap' {"+ , " if ($wordToComplete -like '-*') {"+ , " @('--dir', '-d', '--json', '--label', '-l', '--agent', '-a', '--skip-noop', '--compact', '--against', '--forbid', '--allow-paths', '--file', '-f', '--dry-run', '--limit', '-n', '--keep-last', '--help') | Where-Object { $_ -like \"$wordToComplete*\" }"+ , " } else {"+ , " @('init', 'mark', 'diff', 'guard', 'rewind', 'log', 'gc') | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {"+ , " [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', \"Snap $_\")"+ , " }" , " }" , " }" , " 'completions' {"
src/Canontra/Cache/Inode.hs view
@@ -19,11 +19,11 @@ data FileMetadata = FileMetadata { fmPath :: FilePath , fmSize :: Integer- , fmMtime :: Integer -- POSIX seconds integer+ , fmMtime :: Integer -- POSIX nanoseconds integer } deriving stock (Eq, Show, Generic) deriving anyclass (NFData) --- | Extract file size and modification time for a file path.+-- | Extract file size and nanosecond-resolution modification time for a file path. getFileMetadata :: FilePath -> IO (Maybe FileMetadata) getFileMetadata path = do exists <- doesFileExist path@@ -32,8 +32,8 @@ else do sz <- getFileSize path mtime <- getModificationTime path- let posixMtime = round (utcTimeToPOSIXSeconds mtime)- pure $ Just (FileMetadata path sz posixMtime)+ let posixNanos = floor (utcTimeToPOSIXSeconds mtime * 1000000000)+ pure $ Just (FileMetadata path sz posixNanos) -- | Check if metadata matches existing cached metadata. isMetadataUnchanged :: FileMetadata -> FileMetadata -> Bool
src/Canontra/Cache/MerkleCache.hs view
@@ -68,6 +68,7 @@ import Canontra.Cache.Inode (FileMetadata (..)) import Canontra.Cache.PagedCache (decodeBinaryCacheV5, lookupBinaryCacheV5) import Canontra.Cache.SlabV6 (decodeSlabV6Binary, lookupSlabBinaryBS)+import Canontra.Cache.SlabV7 (SlabV7Entry (..), decodeSlabV7Binary, lookupSlabV7BinaryBS) import Canontra.Types (Fingerprint (..), FingerprintBundle (..)) -- | Lookup an entry in an in-memory MerkleCache with case-folding fallback.@@ -239,6 +240,9 @@ | otherwise = let !ver = readWord16LE bs 4 in case ver of+ 7 -> case decodeSlabV7Binary bs of+ Just (entries, _) -> Just $ MerkleCache $ Map.map (\e -> MerkleCacheEntry (fmSize (sv7Meta e)) (fmMtime (sv7Meta e)) (sv7Bundle e)) entries+ Nothing -> Nothing 6 -> case decodeSlabV6Binary bs of Just (entries, _) -> Just $ MerkleCache $ Map.map (\(m, b) -> MerkleCacheEntry (fmSize m) (fmMtime m) b) entries Nothing -> Nothing@@ -383,6 +387,7 @@ | otherwise = let !version = readWord16LE bs 4 in case version of+ 7 -> fmap fst (lookupSlabV7BinaryBS path meta bs) 6 -> lookupSlabBinaryBS path meta bs 5 -> lookupBinaryCacheV5 path meta bs 4 -> lookupV4
src/Canontra/Cache/PagedCache.hs view
@@ -51,6 +51,7 @@ import qualified Data.List as List import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map+import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Data.Word (Word16, Word32, Word64, Word8)@@ -147,7 +148,7 @@ -- Returns the 4KB page-padded string table ByteString and an offset map for each path. encodePrefixDelta :: [BS.ByteString] -> (BS.ByteString, Map BS.ByteString (Word32, Word16)) encodePrefixDelta paths =- let sortedPaths = List.sort (List.nub paths)+ let sortedPaths = Set.toAscList (Set.fromList paths) go !_ !_ [] = (mempty, Map.empty) go !prevPath !curOff (p : rest) = let !prefix = if BS.null prevPath then 0 else commonPrefixLen prevPath p
+ src/Canontra/Cache/SlabV7.hs view
@@ -0,0 +1,927 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE StrictData #-}++{- |+Module : Canontra.Cache.SlabV7+Description : Incremental zero-copy memory-mapped slab cache engine (CNTR\x07) for canontra v0.4.0.++Extends the CNTR\x06 4KB-paged, 64-byte cache-line-aligned slab architecture with:+- Full 9-tier 'FingerprintBundle' storage (including F_T).+- Compact binary per-file 'FileGraphSummary' payloads inside 4KB CRC-32C protected slabs+ (with safe multi-page spanning for large modules), enabling warm and dirty incremental+ whole-repository graph synthesis without re-parsing untouched source files.+- Persistent whole-repository bundle + unboxed CSR call/data-flow graph slabs.+- Transparent read-upgrade compatibility for CNTR\x06 and CNTR\x05 caches.+-}+module Canontra.Cache.SlabV7+ ( -- * Entry & Handle Types+ SlabV7Entry (..)+ , SlabV7Handle (..)++ -- * Lifecycle+ , openSlabV7+ , closeSlabV7++ -- * Lookups & Memory-Mapped Verification+ , lookupSlabV7Warm+ , lookupSlabV7BinaryBS++ -- * Binary Encoding & Decoding+ , encodeSlabV7Binary+ , decodeSlabV7Binary+ , decodeSlabV7Resilient+ , verifySlabV7HeaderCRC++ -- * FileGraphSummary Binary Serialization+ , encodeFileGraphSummary+ , decodeFileGraphSummary++ -- * Disk File Operations+ , writeSlabV7File+ , readSlabV7File+ , readSlabV7FileResilient+ , readAnySlabCacheForV7+ ) where++import Control.DeepSeq (NFData (..))+import Control.Monad (replicateM)+import Data.Bits ((.&.), (.|.), shiftR)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Internal as BSI+import qualified Data.ByteString.Lazy as LBS+import qualified Data.List as List+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Ord (comparing)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Data.Vector.Unboxed as U+import Data.Word (Word16, Word32, Word64, Word8)+import Foreign.ForeignPtr (ForeignPtr, withForeignPtr)+import Foreign.Marshal.Utils (copyBytes)+import Foreign.Ptr (Ptr, castPtr, plusPtr)+import Foreign.Storable (peekByteOff)+import GHC.Generics (Generic)+import System.Directory (createDirectoryIfMissing, doesFileExist)+import System.FilePath (takeDirectory)+import System.Process (getCurrentPid)++import Canontra.Analysis.CSRGraph (CSRGraph (..))+import Canontra.Analysis.CallGraph (CallEdge (..), CalleeTarget (..), CallerNode (..))+import Canontra.Analysis.WholeRepoGraph (CallFlowSite (..), FileGraphSummary (..))+import Canontra.Cache.Common+ ( MerkleCache (..)+ , MerkleCacheEntry (..)+ , atomicSwapWithRetry_+ , computeCRC32+ , decodeDigest+ , encodeBundle+ , encodeDigest+ , fastPathHash64+ , normalizePathCanonical+ , readWord16LE+ , readWord32LE+ , readWord64LE+ )+import Canontra.Cache.Inode (FileMetadata (..))+import Canontra.Cache.PagedCache (decodeBinaryCacheV5)+import Canontra.Cache.SlabV6+ ( CacheRecordV6 (..)+ , decodeCSRGraph+ , decodeSlabV6Resilient+ , encodeCSRGraph+ )+import Canontra.Types+ ( DeclKind (..)+ , Fingerprint (..)+ , FingerprintBundle (..)+ , GlobalSymbol (..)+ , WholeRepoBundle (..)+ )++-- | Cached entry in CNTR\x07 holding file metadata, 9-tier bundle, and optional graph summary.+data SlabV7Entry = SlabV7Entry+ { sv7Meta :: !FileMetadata+ , sv7Bundle :: !FingerprintBundle+ , sv7Summary :: !(Maybe FileGraphSummary)+ } deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++-- | Handle to an active memory-mapped CNTR\x07 slab cache.+data SlabV7Handle = SlabV7Handle+ { sv7FilePath :: !FilePath+ , sv7ByteString :: !BS.ByteString+ , sv7BasePtr :: !(Ptr Word8)+ , sv7ForeignPtr :: !(ForeignPtr Word8)+ , sv7RecordCount :: !Word32+ , sv7RecordCapacity :: !Word32+ , sv7RadixTablePtr :: !(Ptr Word8)+ , sv7FileTablePtr :: !(Ptr CacheRecordV6)+ , sv7RepoBundle :: !(Maybe WholeRepoBundle)+ , sv7RepoCallCSR :: !(Maybe CSRGraph)+ , sv7RepoDataCSR :: !(Maybe CSRGraph)+ } deriving stock (Show, Eq, Generic)++instance NFData SlabV7Handle where+ rnf (SlabV7Handle fp bs _ _ rc cap _ _ rb rcg rdg) =+ rnf fp `seq` rnf bs `seq` rnf rc `seq` rnf cap `seq` rnf rb `seq` rnf rcg `seq` rnf rdg++-- ============================================================================+-- Binary Encoding Helpers for FileGraphSummary+-- ============================================================================++encodeTextB :: T.Text -> BB.Builder+encodeTextB t =+ let !bs = TE.encodeUtf8 t+ in BB.word32LE (fromIntegral (BS.length bs)) <> BB.byteString bs++encodeFilePathB :: FilePath -> BB.Builder+encodeFilePathB = encodeTextB . T.pack++encodeListB :: (a -> BB.Builder) -> [a] -> BB.Builder+encodeListB f xs =+ BB.word32LE (fromIntegral (length xs)) <> mconcat (map f xs)++encodeDeclKind :: DeclKind -> Word8+encodeDeclKind = \case+ KindFunction -> 0+ KindMethod -> 1+ KindClass -> 2+ KindStruct -> 3+ KindInterface -> 4+ KindTrait -> 5+ KindImpl -> 6+ KindVariable -> 7+ KindTypeAlias -> 8++decodeDeclKind :: Word8 -> Maybe DeclKind+decodeDeclKind = \case+ 0 -> Just KindFunction+ 1 -> Just KindMethod+ 2 -> Just KindClass+ 3 -> Just KindStruct+ 4 -> Just KindInterface+ 5 -> Just KindTrait+ 6 -> Just KindImpl+ 7 -> Just KindVariable+ 8 -> Just KindTypeAlias+ _ -> Nothing++encodeGlobalSymbolB :: GlobalSymbol -> BB.Builder+encodeGlobalSymbolB (GlobalSymbol fp m d k (Fingerprint t2)) =+ encodeFilePathB fp+ <> encodeTextB m+ <> encodeTextB d+ <> BB.word8 (encodeDeclKind k)+ <> encodeTextB t2++encodeCallerNodeB :: CallerNode -> BB.Builder+encodeCallerNodeB = \case+ CallTopLevel -> BB.word8 0+ CallFunction fn -> BB.word8 1 <> encodeTextB fn+ CallMethod cls m -> BB.word8 2 <> encodeTextB cls <> encodeTextB m++encodeCalleeTargetB :: CalleeTarget -> BB.Builder+encodeCalleeTargetB = \case+ TargetLocal n -> BB.word8 0 <> encodeTextB n+ TargetMethod c m -> BB.word8 1 <> encodeTextB c <> encodeTextB m+ TargetImported m s -> BB.word8 2 <> encodeTextB m <> encodeTextB s+ TargetDynamic _ -> BB.word8 3++encodeCallEdgeB :: CallEdge -> BB.Builder+encodeCallEdgeB (CallEdge caller callee cnt isAsync) =+ encodeCallerNodeB caller+ <> encodeCalleeTargetB callee+ <> BB.word32LE (fromIntegral cnt)+ <> BB.word8 (if isAsync then 1 else 0)++encodeCallFlowSiteB :: CallFlowSite -> BB.Builder+encodeCallFlowSiteB (CallFlowSite caller callee posArgs kwArgs) =+ encodeCallerNodeB caller+ <> encodeCalleeTargetB callee+ <> encodeListB (encodeListB encodeTextB) posArgs+ <> encodeListB (\(k, vs) -> encodeTextB k <> encodeListB encodeTextB vs) kwArgs++-- | Serialize a 'FileGraphSummary' to a compact binary 'BB.Builder'.+encodeFileGraphSummary :: FileGraphSummary -> BB.Builder+encodeFileGraphSummary (FileGraphSummary fp modN impMods reExps syms callEdges flowSites) =+ encodeFilePathB fp+ <> encodeTextB modN+ <> encodeListB encodeTextB impMods+ <> encodeListB (\(eN, sM, oN) -> encodeTextB eN <> encodeTextB sM <> encodeTextB oN) reExps+ <> encodeListB encodeGlobalSymbolB syms+ <> encodeListB encodeCallEdgeB callEdges+ <> encodeListB encodeCallFlowSiteB flowSites++-- | Bounds-checked ByteString cursor decoder.+newtype Decoder a = Decoder { runDecoder :: BS.ByteString -> Int -> Maybe (a, Int) }++instance Functor Decoder where+ fmap f (Decoder g) = Decoder $ \bs off -> do+ (a, off') <- g bs off+ pure (f a, off')++instance Applicative Decoder where+ pure a = Decoder $ \_ off -> Just (a, off)+ Decoder ff <*> Decoder fa = Decoder $ \bs off -> do+ (f, off1) <- ff bs off+ (a, off2) <- fa bs off1+ pure (f a, off2)++instance Monad Decoder where+ Decoder fa >>= k = Decoder $ \bs off -> do+ (a, off1) <- fa bs off+ runDecoder (k a) bs off1++decWord8 :: Decoder Word8+decWord8 = Decoder $ \bs off ->+ if off + 1 > BS.length bs+ then Nothing+ else Just (BS.index bs off, off + 1)++decWord32 :: Decoder Word32+decWord32 = Decoder $ \bs off ->+ if off + 4 > BS.length bs+ then Nothing+ else Just (readWord32LE bs off, off + 4)++decText :: Decoder T.Text+decText = do+ lenW <- decWord32+ let !len = fromIntegral lenW :: Int+ Decoder $ \bs off ->+ if off + len > BS.length bs+ then Nothing+ else+ let !slice = BS.take len (BS.drop off bs)+ in Just (TE.decodeUtf8Lenient slice, off + len)++decFilePath :: Decoder FilePath+decFilePath = T.unpack <$> decText++decList :: Decoder a -> Decoder [a]+decList itemDec = do+ cnt <- decWord32+ replicateM (fromIntegral cnt) itemDec++decGlobalSymbol :: Decoder GlobalSymbol+decGlobalSymbol = do+ fp <- decFilePath+ m <- decText+ d <- decText+ kb <- decWord8+ k <- Decoder $ \_ off -> case decodeDeclKind kb of+ Just dk -> Just (dk, off)+ Nothing -> Nothing+ t2 <- decText+ pure (GlobalSymbol fp m d k (Fingerprint t2))++decCallerNode :: Decoder CallerNode+decCallerNode = do+ t <- decWord8+ case t of+ 0 -> pure CallTopLevel+ 1 -> CallFunction <$> decText+ 2 -> CallMethod <$> decText <*> decText+ _ -> Decoder (\_ _ -> Nothing)++decCalleeTarget :: Decoder CalleeTarget+decCalleeTarget = do+ t <- decWord8+ case t of+ 0 -> TargetLocal <$> decText+ 1 -> TargetMethod <$> decText <*> decText+ 2 -> TargetImported <$> decText <*> decText+ _ -> Decoder (\_ _ -> Nothing)++decCallEdge :: Decoder CallEdge+decCallEdge = do+ caller <- decCallerNode+ callee <- decCalleeTarget+ cnt <- decWord32+ ab <- decWord8+ pure (CallEdge caller callee (fromIntegral cnt) (ab /= 0))++decCallFlowSite :: Decoder CallFlowSite+decCallFlowSite = do+ caller <- decCallerNode+ callee <- decCalleeTarget+ posArgs <- decList (decList decText)+ kwArgs <- decList ((,) <$> decText <*> decList decText)+ pure (CallFlowSite caller callee posArgs kwArgs)++-- | Deserialize a 'FileGraphSummary' from a strict 'BS.ByteString' at the given offset.+decodeFileGraphSummary :: BS.ByteString -> Int -> Maybe (FileGraphSummary, Int)+decodeFileGraphSummary bs off = runDecoder decSummary bs off+ where+ decSummary = do+ fp <- decFilePath+ modN <- decText+ impMods <- decList decText+ reExps <- decList ((,,) <$> decText <*> decText <*> decText)+ syms <- decList decGlobalSymbol+ callEdges <- decList decCallEdge+ flowSites <- decList decCallFlowSite+ pure (FileGraphSummary fp modN impMods reExps syms callEdges flowSites)++-- ============================================================================+-- CNTR\x07 Layout & Encoding+-- ============================================================================++-- | Record flag indicating the payload spans multiple contiguous 4KB slab pages.+flagMultiPagePayload :: Word64+flagMultiPagePayload = 1++-- | Encodes entries and optional repository CSR graphs into CNTR\x07 binary format.+encodeSlabV7Binary+ :: [SlabV7Entry]+ -> Maybe (WholeRepoBundle, CSRGraph, CSRGraph)+ -> BS.ByteString+encodeSlabV7Binary rawEntries mRepo =+ let !numEntries = length rawEntries+ !capacity = max 512 (fromIntegral numEntries :: Word32)+ !fileTableBytes = fromIntegral capacity * 64 :: Int+ !slabStartOffset = 2080 + fileTableBytes++ prepEntry (SlabV7Entry meta bundle mSummary) =+ let !norm = normalizePathCanonical (fmPath meta)+ !pBS = TE.encodeUtf8 (T.pack norm)+ !h = fastPathHash64 pBS+ !b = fromIntegral (h `shiftR` 56) :: Int+ in (b, h, norm, pBS, meta, bundle, mSummary)++ sorted = List.sortBy (comparing (\(b, h, norm, _, _, _, _) -> (b, h, norm))) (map prepEntry rawEntries)++ (records, slabDataBS) = buildSlabs slabStartOffset sorted+ radixBS = buildRadixDirectory sorted (fromIntegral numEntries :: Word32)++ (!repoOff, !repoLen, !repoSlabBS) = case mRepo of+ Nothing -> (0 :: Word32, 0 :: Word32, BS.empty)+ Just (wrb, cgCSR, dfCSR) ->+ let !startOff = fromIntegral (slabStartOffset + BS.length slabDataBS) :: Word32+ !body = encodeRepoBody wrb cgCSR dfCSR+ !pageBS = buildMultiPageChunk body+ in (startOff, fromIntegral (BS.length pageBS), pageBS)++ fileTableBuilder =+ mconcat [encodeRecord rec | rec <- records]+ <> BB.byteString (BS.replicate (fromIntegral (capacity - fromIntegral numEntries) * 64) 0)++ fileTableBS = LBS.toStrict (BB.toLazyByteString fileTableBuilder)++ headerNoCRC =+ BB.byteString "CNTR"+ <> BB.word16LE 7+ <> BB.word16LE (if repoOff > 0 then 1 else 0)+ <> BB.word32LE (fromIntegral numEntries)+ <> BB.word32LE capacity+ <> BB.word32LE 0+ <> BB.word32LE repoOff+ <> BB.word32LE repoLen+ <> BB.word32LE 0++ headerNoCRC_BS = LBS.toStrict (BB.toLazyByteString headerNoCRC)+ globalCRC = computeCRC32 (headerNoCRC_BS <> radixBS)++ headerFinal =+ BB.byteString "CNTR"+ <> BB.word16LE 7+ <> BB.word16LE (if repoOff > 0 then 1 else 0)+ <> BB.word32LE (fromIntegral numEntries)+ <> BB.word32LE capacity+ <> BB.word32LE globalCRC+ <> BB.word32LE repoOff+ <> BB.word32LE repoLen+ <> BB.word32LE 0++ headerFinalBS = LBS.toStrict (BB.toLazyByteString headerFinal)+ in headerFinalBS <> radixBS <> fileTableBS <> slabDataBS <> repoSlabBS+ where+ encodeRecord (CacheRecordV6 h mt nano sz off len f4 flg r1 r2) =+ BB.word64LE h+ <> BB.word64LE mt+ <> BB.word32LE nano+ <> BB.word32LE sz+ <> BB.word32LE off+ <> BB.word32LE len+ <> BB.word64LE f4+ <> BB.word64LE flg+ <> BB.word64LE r1+ <> BB.word64LE r2++ -- O(N) single-pass 256-way L1 Radix directory builder+ buildRadixDirectory sorted totalCount =+ let countsMap = Map.fromListWith (+) [(b, 1 :: Word32) | (b, _, _, _, _, _, _) <- sorted]+ (_, bucketEntries) = List.mapAccumL+ (\ !accStart b ->+ let !c = Map.findWithDefault 0 b countsMap+ !entry = if c == 0+ then BB.word32LE totalCount <> BB.word32LE 0+ else BB.word32LE accStart <> BB.word32LE c+ in (accStart + c, entry)+ ) 0 [0 .. 255 :: Int]+ in LBS.toStrict (BB.toLazyByteString (mconcat bucketEntries))++ buildSlabs baseOffset sorted =+ let encodeItem (_, h, _, pBS, meta, bundle, mSummary) =+ let !payloadBS = encodePayload pBS bundle mSummary+ !f4Hex = unFingerprint (f4Composite bundle)+ !f4Head = readWord64LE (TE.encodeUtf8 f4Hex) 0+ in (h, fromIntegral (fmMtime meta) :: Word64, fromIntegral (fmSize meta) :: Word32, f4Head, payloadBS)+ items = map encodeItem sorted+ in packItemsIntoPages baseOffset items++ packItemsIntoPages baseOffset items =+ let (recs, pages) = go baseOffset 0 [] [] items+ in (recs, BS.concat (reverse pages))+ where+ go _ _ accRecs accPages [] = (reverse accRecs, accPages)+ go curBase pageIdx accRecs accPages (x@(_, _, _, _, p) : xs)+ | BS.length p > 4088 =+ -- Oversized payload spans k contiguous 4KB pages cleanly (never loops)+ let !pageStart = curBase + pageIdx * 4096+ !numPages = (BS.length p + 4087) `div` 4088+ !chunkBS = buildMultiPageChunk p+ !(h, mt, sz, f4Head, _) = x+ !rec = CacheRecordV6 h mt 0 sz (fromIntegral pageStart) (fromIntegral (BS.length p)) f4Head flagMultiPagePayload 0 0+ in go curBase (pageIdx + numPages) (rec : accRecs) (chunkBS : accPages) xs+ | otherwise =+ let (chunk, rest) = fitIntoPage 4088 (x : xs)+ pagePayload = BS.concat [pl | (_, _, _, _, pl) <- chunk]+ padding = 4088 - BS.length pagePayload+ paddedBody = pagePayload <> BS.replicate padding 0+ crc = computeCRC32 paddedBody+ pageBS = LBS.toStrict $ BB.toLazyByteString $+ BB.word32LE crc <> BB.word32LE 1 <> BB.byteString paddedBody+ pageStart = curBase + pageIdx * 4096+ assigned = assignOffsets (pageStart + 8) chunk+ in go curBase (pageIdx + 1) (reverse assigned ++ accRecs) (pageBS : accPages) rest++ fitIntoPage _ [] = ([], [])+ fitIntoPage remSpace (y@(_, _, _, _, p) : ys)+ | BS.length p <= remSpace =+ let (fitted, rest) = fitIntoPage (remSpace - BS.length p) ys+ in (y : fitted, rest)+ | otherwise = ([], y : ys)++ assignOffsets _ [] = []+ assignOffsets off ((h, mt, sz, f4Head, p) : xs) =+ let !len = fromIntegral (BS.length p) :: Word32+ !rec = CacheRecordV6 h mt 0 sz (fromIntegral off) len f4Head 0 0 0+ in rec : assignOffsets (off + fromIntegral len) xs++ buildMultiPageChunk rawBody =+ let !totalLen = BS.length rawBody+ !numPages = max 1 ((totalLen + 4087) `div` 4088)+ mkPage !idx =+ let !slice = BS.take 4088 (BS.drop (idx * 4088) rawBody)+ !padLen = 4088 - BS.length slice+ !paddedBody = if padLen == 0 then slice else slice <> BS.replicate padLen 0+ !crc = computeCRC32 paddedBody+ !spanTag = if idx == 0 then fromIntegral numPages :: Word32 else 0+ in BB.word32LE crc <> BB.word32LE spanTag <> BB.byteString paddedBody+ in LBS.toStrict $ BB.toLazyByteString $ mconcat [mkPage i | i <- [0 .. numPages - 1]]++ encodePayload pBS bundle mSummary =+ let !normLen = fromIntegral (BS.length pBS) :: Word16+ (!flags, !b0, !b1, !b2, !b3, !bcg, !bcf, !bdf, !b4) = encodeBundle bundle+ (!isHexT, !bt) = encodeDigest (unFingerprint (fTTypeContract bundle))+ !flagsFinal = flags .|. (if isHexT then 256 else 0)+ !summaryPart = case mSummary of+ Nothing -> BB.word32LE 0+ Just s ->+ let !sBS = LBS.toStrict (BB.toLazyByteString (encodeFileGraphSummary s))+ in BB.word32LE (fromIntegral (BS.length sBS)) <> BB.byteString sBS+ in LBS.toStrict $ BB.toLazyByteString $+ BB.word16LE normLen+ <> BB.byteString pBS+ <> BB.word16LE flagsFinal+ <> BB.byteString b0+ <> BB.byteString b1+ <> BB.byteString b2+ <> BB.byteString b3+ <> BB.byteString bcg+ <> BB.byteString bcf+ <> BB.byteString bdf+ <> BB.byteString bt+ <> BB.byteString b4+ <> summaryPart++ encodeRepoBody (WholeRepoBundle (Fingerprint fr) (Fingerprint fwcg) (Fingerprint fwdf) (Fingerprint fw4)) cgCSR dfCSR =+ let (hxR, bR) = encodeDigest fr+ (hxWCG, bWCG) = encodeDigest fwcg+ (hxWDF, bWDF) = encodeDigest fwdf+ (hxW4, bW4) = encodeDigest fw4+ !rFlags = (if hxR then 1 else 0)+ .|. (if hxWCG then 2 else 0)+ .|. (if hxWDF then 4 else 0)+ .|. (if hxW4 then 8 else 0) :: Word16+ in LBS.toStrict $ BB.toLazyByteString $+ BB.byteString "REPO"+ <> BB.word16LE rFlags+ <> BB.byteString bR+ <> BB.byteString bWCG+ <> BB.byteString bWDF+ <> BB.byteString bW4+ <> encodeCSRGraph cgCSR+ <> encodeCSRGraph dfCSR++-- ============================================================================+-- Header & Page Verification+-- ============================================================================++-- | Verifies the integrity of the CNTR\x07 global header and 256-way radix directory.+verifySlabV7HeaderCRC :: BS.ByteString -> Bool+verifySlabV7HeaderCRC bs+ | BS.length bs < 2080 = False+ | BS.take 4 bs /= "CNTR" = False+ | readWord16LE bs 4 /= 7 = False+ | otherwise =+ let !storedCRC = readWord32LE bs 16+ !headerNoCRC = BS.take 16 bs <> BS.replicate 4 0 <> BS.take 12 (BS.drop 20 bs)+ !radixBS = BS.take 2048 (BS.drop 32 bs)+ !expectedCRC = computeCRC32 (headerNoCRC <> radixBS)+ in storedCRC == expectedCRC++-- | Extract contiguous payload bytes for single-page or multi-page records.+extractPayloadBytes :: BS.ByteString -> Int -> Int -> Word64 -> BS.ByteString+extractPayloadBytes bs off len flags+ | (flags .&. flagMultiPagePayload) == 0 =+ BS.take len (BS.drop off bs)+ | otherwise =+ let !numPages = max 1 ((len + 4087) `div` 4088)+ !raw = BS.concat+ [ BS.take 4088 (BS.drop (off + p * 4096 + 8) bs)+ | p <- [0 .. numPages - 1]+ ]+ in BS.take len raw++decodeRepoBodyBytes :: BS.ByteString -> Maybe (WholeRepoBundle, CSRGraph, CSRGraph)+decodeRepoBodyBytes body+ | BS.length body < 138 || BS.take 4 body /= "REPO" = Nothing+ | otherwise =+ let !rFlags = readWord16LE body 4+ !bR = decodeDigest rFlags 0 (BS.take 32 (BS.drop 6 body))+ !bWCG = decodeDigest rFlags 1 (BS.take 32 (BS.drop 38 body))+ !bWDF = decodeDigest rFlags 2 (BS.take 32 (BS.drop 70 body))+ !bW4 = decodeDigest rFlags 3 (BS.take 32 (BS.drop 102 body))+ !bundle = WholeRepoBundle (Fingerprint bR) (Fingerprint bWCG) (Fingerprint bWDF) (Fingerprint bW4)+ !cgRes = decodeCSRGraph body 134+ (!cgCSR, !nextOff) = case cgRes of+ Just (cg, n) -> (cg, n)+ Nothing -> (CSRGraph 0 0 (U.singleton 0) U.empty U.empty, 134)+ !dfRes = decodeCSRGraph body nextOff+ !dfCSR = case dfRes of+ Just (df, _) -> df+ Nothing -> CSRGraph 0 0 (U.singleton 0) U.empty U.empty+ in Just (bundle, cgCSR, dfCSR)++-- ============================================================================+-- Zero-Copy Memory-Mapped Handle & Lookups+-- ============================================================================++-- | Open a CNTR\x07 slab cache file into a memory-mapped handle.+openSlabV7 :: FilePath -> IO (Maybe SlabV7Handle)+openSlabV7 cachePath = do+ exists <- doesFileExist cachePath+ if not exists+ then pure Nothing+ else do+ bs <- BS.readFile cachePath+ if BS.length bs < 2080 || not (verifySlabV7HeaderCRC bs)+ then pure Nothing+ else do+ let !numRecords = readWord32LE bs 8+ !capacity = readWord32LE bs 12+ !repoOff = readWord32LE bs 20+ !repoLen = readWord32LE bs 24+ (!fptr, !bsOff, _) = BSI.toForeignPtr bs++ withForeignPtr fptr $ \rawPtr -> do+ let !basePtr = rawPtr `plusPtr` bsOff+ !radixPtr = basePtr `plusPtr` 32+ !fileTablePtr = castPtr (basePtr `plusPtr` 2080) :: Ptr CacheRecordV6+ (!mRepo, !mCgCSR, !mDfCSR) =+ if repoOff == 0 || fromIntegral (repoOff + repoLen) > BS.length bs+ then (Nothing, Nothing, Nothing)+ else+ let !repoBody = extractPayloadBytes bs (fromIntegral repoOff) (fromIntegral repoLen) flagMultiPagePayload+ in case decodeRepoBodyBytes repoBody of+ Just (wrb, cg, df) -> (Just wrb, Just cg, Just df)+ Nothing -> (Nothing, Nothing, Nothing)++ pure $ Just SlabV7Handle+ { sv7FilePath = cachePath+ , sv7ByteString = bs+ , sv7BasePtr = basePtr+ , sv7ForeignPtr = fptr+ , sv7RecordCount = numRecords+ , sv7RecordCapacity = capacity+ , sv7RadixTablePtr = radixPtr+ , sv7FileTablePtr = fileTablePtr+ , sv7RepoBundle = mRepo+ , sv7RepoCallCSR = mCgCSR+ , sv7RepoDataCSR = mDfCSR+ }++-- | Close an active CNTR\x07 slab handle.+closeSlabV7 :: SlabV7Handle -> IO ()+closeSlabV7 _ = pure ()++-- | Sub-microsecond warm lookup directly from an open 'SlabV7Handle'.+lookupSlabV7Warm :: SlabV7Handle -> FilePath -> FileMetadata -> IO (Maybe (FingerprintBundle, Maybe FileGraphSummary))+lookupSlabV7Warm !handle !path !meta = do+ let !norm = normalizePathCanonical path+ !pBS = TE.encodeUtf8 (T.pack norm)+ !h = fastPathHash64 pBS+ !bucket = fromIntegral (h `shiftR` 56) :: Int+ !radixPtr = sv7RadixTablePtr handle `plusPtr` (bucket * 8)+ startIdx <- peekByteOff radixPtr 0 :: IO Word32+ count <- peekByteOff radixPtr 4 :: IO Word32+ if count == 0+ then pure Nothing+ else probeRec startIdx count 0 h+ where+ !mtTarget = fromIntegral (fmMtime meta) :: Word64+ !szTarget = fromIntegral (fmSize meta) :: Word32+ probeRec !startIdx !count !slot !h+ | slot >= count = pure Nothing+ | otherwise = do+ let !recPtr = sv7FileTablePtr handle `plusPtr` (fromIntegral (startIdx + slot) * 64)+ !recH <- peekByteOff (castPtr recPtr) 0 :: IO Word64+ if recH /= h+ then probeRec startIdx count (slot + 1) h+ else do+ !mt <- peekByteOff (castPtr recPtr) 8 :: IO Word64+ !sz <- peekByteOff (castPtr recPtr) 20 :: IO Word32+ if mt /= mtTarget || sz /= szTarget+ then probeRec startIdx count (slot + 1) h+ else do+ !slabOff <- peekByteOff (castPtr recPtr) 24 :: IO Word32+ !slabLen <- peekByteOff (castPtr recPtr) 28 :: IO Word32+ !flags <- peekByteOff (castPtr recPtr) 40 :: IO Word64+ if slabOff == 0 || slabLen == 0+ then pure Nothing+ else if (flags .&. flagMultiPagePayload) == 0+ then do+ let !payloadPtr = sv7BasePtr handle `plusPtr` fromIntegral slabOff+ payloadBS <- BSI.create (fromIntegral slabLen) $ \buf ->+ copyBytes buf payloadPtr (fromIntegral slabLen)+ let (_, !bundle, !mSummary) = decodePayloadBS payloadBS+ pure (Just (bundle, mSummary))+ else do+ let !payloadBS = extractPayloadBytes (sv7ByteString handle) (fromIntegral slabOff) (fromIntegral slabLen) flags+ (_, !bundle, !mSummary) = decodePayloadBS payloadBS+ pure (Just (bundle, mSummary))++-- | Pure zero-copy binary lookup directly in a CNTR\x07 ByteString.+lookupSlabV7BinaryBS :: FilePath -> FileMetadata -> BS.ByteString -> Maybe (FingerprintBundle, Maybe FileGraphSummary)+lookupSlabV7BinaryBS !path !meta !bs+ | BS.length bs < 2080 = Nothing+ | BS.take 4 bs /= "CNTR" = Nothing+ | readWord16LE bs 4 /= 7 = Nothing+ | otherwise =+ let !norm = normalizePathCanonical path+ !pBS = TE.encodeUtf8 (T.pack norm)+ !h = fastPathHash64 pBS+ !bucket = fromIntegral (h `shiftR` 56) :: Int+ !radixOffset = 32 + bucket * 8+ !startIdx = readWord32LE bs radixOffset+ !count = readWord32LE bs (radixOffset + 4)+ in if count == 0+ then Nothing+ else probe startIdx count 0 h+ where+ !mtTarget = fromIntegral (fmMtime meta) :: Word64+ !szTarget = fromIntegral (fmSize meta) :: Word32+ probe !startIdx !count !slot !h+ | slot >= count = Nothing+ | otherwise =+ let !recOff = 2080 + fromIntegral (startIdx + slot) * 64+ in if recOff + 64 > BS.length bs+ then Nothing+ else+ let !recH = readWord64LE bs recOff+ in if recH /= h+ then probe startIdx count (slot + 1) h+ else+ let !mt = readWord64LE bs (recOff + 8)+ !sz = readWord32LE bs (recOff + 20)+ in if mt == mtTarget && sz == szTarget+ then+ let !slabOff = fromIntegral (readWord32LE bs (recOff + 24)) :: Int+ !slabLen = fromIntegral (readWord32LE bs (recOff + 28)) :: Int+ !recFlags = readWord64LE bs (recOff + 40)+ in if slabOff == 0 || slabLen == 0 || slabOff >= BS.length bs+ then Nothing+ else+ let !payloadBS = extractPayloadBytes bs slabOff slabLen recFlags+ (_, !bundle, !mSummary) = decodePayloadBS payloadBS+ in Just (bundle, mSummary)+ else probe startIdx count (slot + 1) h++decodePayloadBS :: BS.ByteString -> (FilePath, FingerprintBundle, Maybe FileGraphSummary)+decodePayloadBS bs =+ let !normLen = fromIntegral (readWord16LE bs 0) :: Int+ !pBS = BS.take normLen (BS.drop 2 bs)+ !path = T.unpack (TE.decodeUtf8Lenient pBS)+ !off = 2 + normLen+ !flags = readWord16LE bs off+ !b0 = BS.take 32 (BS.drop (off + 2) bs)+ !b1 = BS.take 32 (BS.drop (off + 34) bs)+ !b2 = BS.take 32 (BS.drop (off + 66) bs)+ !b3 = BS.take 32 (BS.drop (off + 98) bs)+ !bcg = BS.take 32 (BS.drop (off + 130) bs)+ !bcf = BS.take 32 (BS.drop (off + 162) bs)+ !bdf = BS.take 32 (BS.drop (off + 194) bs)+ !bt = BS.take 32 (BS.drop (off + 226) bs)+ !b4 = BS.take 32 (BS.drop (off + 258) bs)+ !f0 = decodeDigest flags 0 b0+ !f1 = decodeDigest flags 1 b1+ !f2 = decodeDigest flags 2 b2+ !f3 = decodeDigest flags 3 b3+ !fcg = decodeDigest flags 4 bcg+ !fcf = decodeDigest flags 5 bcf+ !fdf = decodeDigest flags 6 bdf+ !ft = decodeDigest flags 8 bt+ !f4 = decodeDigest flags 7 b4+ !bundle = FingerprintBundle (Fingerprint f0) (Fingerprint f1) (Fingerprint f2) (Fingerprint f3)+ (Fingerprint fcg) (Fingerprint fcf) (Fingerprint fdf) (Fingerprint ft)+ (Fingerprint f4)+ !sumLenOff = off + 290+ !mSummary =+ if sumLenOff + 4 > BS.length bs+ then Nothing+ else+ let !sumLen = fromIntegral (readWord32LE bs sumLenOff) :: Int+ in if sumLen == 0 || sumLenOff + 4 + sumLen > BS.length bs+ then Nothing+ else fmap fst (decodeFileGraphSummary bs (sumLenOff + 4))+ in (path, bundle, mSummary)++-- ============================================================================+-- Full Binary Decoding & Resilient 4KB Bit-Rot Recovery+-- ============================================================================++-- | Decode all entries from a CNTR\x07 ByteString (strictly requiring 0 corrupted pages).+decodeSlabV7Binary+ :: BS.ByteString+ -> Maybe (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph))+decodeSlabV7Binary bs+ | BS.length bs < 2080 || not (verifySlabV7HeaderCRC bs) = Nothing+ | otherwise =+ let (entries, mRepo, corrupted) = decodeSlabV7Resilient bs+ in if null corrupted then Just (entries, mRepo) else Nothing++-- | Decode a CNTR\x07 slab cache with isolated 4KB page bit-rot recovery.+decodeSlabV7Resilient+ :: BS.ByteString+ -> (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph), [Word32])+decodeSlabV7Resilient bs+ | BS.length bs < 2080 || not (verifySlabV7HeaderCRC bs) = (Map.empty, Nothing, [0])+ | otherwise =+ let !numRecords = readWord32LE bs 8+ !capacity = readWord32LE bs 12+ !repoOff = readWord32LE bs 20+ !repoLen = readWord32LE bs 24+ !totalBytes = BS.length bs+ !slabStart = 2080 + fromIntegral capacity * 64 :: Int+ !totalSlabPages = if totalBytes > slabStart then (totalBytes - slabStart + 4095) `div` 4096 else 0++ checkPage p =+ let !pageOff = slabStart + p * 4096+ in if pageOff + 4096 > totalBytes+ then False+ else+ let !storedCRC = readWord32LE bs pageOff+ !body = BS.take 4088 (BS.drop (pageOff + 8) bs)+ in storedCRC == computeCRC32 body++ corruptedPages =+ [ fromIntegral p+ | p <- [0 .. totalSlabPages - 1]+ , not (checkPage p)+ ]+ corruptedSet = Map.fromList [(p, ()) | p <- corruptedPages]++ anyPageCorrupt startPage numP =+ any (\dp -> Map.member (startPage + dp) corruptedSet) [0 .. numP - 1]++ decodeRecord slot+ | slot >= fromIntegral numRecords = Nothing+ | otherwise =+ let !recOff = 2080 + slot * 64+ !mt = readWord64LE bs (recOff + 8)+ !sz = readWord32LE bs (recOff + 20)+ !off = fromIntegral (readWord32LE bs (recOff + 24)) :: Int+ !len = fromIntegral (readWord32LE bs (recOff + 28)) :: Int+ !recFlags = readWord64LE bs (recOff + 40)+ !startPage = fromIntegral ((off - slabStart) `div` 4096) :: Word32+ !numP = if (recFlags .&. flagMultiPagePayload) == 0+ then 1+ else fromIntegral (max 1 ((len + 4087) `div` 4088))+ in if off < slabStart || len == 0 || off + 4 > totalBytes || anyPageCorrupt startPage numP+ then Nothing+ else+ let !payloadBS = extractPayloadBytes bs off len recFlags+ !(path, bundle, mSummary) = decodePayloadBS payloadBS+ !meta = FileMetadata path (fromIntegral sz) (fromIntegral mt)+ in Just (path, SlabV7Entry meta bundle mSummary)++ validEntries = Map.fromList+ [ item+ | slot <- [0 .. fromIntegral numRecords - 1]+ , Just item <- [decodeRecord slot]+ ]++ mRepo =+ if repoOff == 0 || fromIntegral repoOff < slabStart || fromIntegral repoOff >= totalBytes+ then Nothing+ else+ let !repoStartPage = fromIntegral ((fromIntegral repoOff - slabStart) `div` 4096) :: Word32+ !repoSpan = max 1 (readWord32LE bs (fromIntegral repoOff + 4)) :: Word32+ in if anyPageCorrupt repoStartPage repoSpan+ then Nothing+ else+ let !repoBody = extractPayloadBytes bs (fromIntegral repoOff) (fromIntegral repoLen) flagMultiPagePayload+ in decodeRepoBodyBytes repoBody+ in (validEntries, mRepo, corruptedPages)++-- ============================================================================+-- Disk File Operations & Transparent Cache Migration+-- ============================================================================++-- | Write CNTR\x07 entries and optional repository graphs atomically to disk.+writeSlabV7File+ :: FilePath+ -> [SlabV7Entry]+ -> Maybe (WholeRepoBundle, CSRGraph, CSRGraph)+ -> IO ()+writeSlabV7File cachePath entries mRepo = do+ createDirectoryIfMissing True (takeDirectory cachePath)+ pid <- getCurrentPid+ let !encoded = encodeSlabV7Binary entries mRepo+ !tmpPath = cachePath ++ ".tmp." ++ show pid+ BS.writeFile tmpPath encoded+ atomicSwapWithRetry_ tmpPath cachePath++-- | Read a CNTR\x07 slab cache file from disk.+readSlabV7File+ :: FilePath+ -> IO (Maybe (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph)))+readSlabV7File cachePath = do+ exists <- doesFileExist cachePath+ if not exists+ then pure Nothing+ else do+ bs <- BS.readFile cachePath+ case decodeSlabV7Binary bs of+ Just res -> pure (Just res)+ Nothing -> do+ let (validEntries, mRepo, corruptedPages) = decodeSlabV7Resilient bs+ if Map.null validEntries && null corruptedPages+ then pure Nothing+ else pure (Just (validEntries, mRepo))++-- | Read a CNTR\x07 slab cache file with isolated 4KB page bit-rot recovery.+readSlabV7FileResilient+ :: FilePath+ -> IO (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph), [Word32])+readSlabV7FileResilient cachePath = do+ exists <- doesFileExist cachePath+ if not exists+ then pure (Map.empty, Nothing, [])+ else do+ bs <- BS.readFile cachePath+ pure (decodeSlabV7Resilient bs)++-- | Read CNTR\x07, CNTR\x06, or CNTR\x05 binary buffers transparently into 'SlabV7Entry' maps.+-- Returns 'Nothing' for older versions (<= 4 or legacy JSON) so callers can fall back cleanly.+readAnySlabCacheForV7+ :: BS.ByteString+ -> Maybe (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph))+readAnySlabCacheForV7 bs+ | BS.length bs < 32 || BS.take 4 bs /= "CNTR" = Nothing+ | otherwise = case readWord16LE bs 4 of+ 7 ->+ let (entries, mRepo, corrupted) = decodeSlabV7Resilient bs+ in if Map.null entries && not (null corrupted) && corrupted == [0]+ then Nothing+ else Just (entries, mRepo)+ 6 ->+ let (entries, mRepo, corrupted) = decodeSlabV6Resilient bs+ in if Map.null entries && not (null corrupted) && corrupted == [0]+ then Nothing+ else Just (Map.map (\(m, b) -> SlabV7Entry m b Nothing) entries, mRepo)+ 5 -> case decodeBinaryCacheV5 bs of+ Nothing -> Nothing+ Just (MerkleCache mc) ->+ Just (Map.mapWithKey (\p (MerkleCacheEntry sz mt b) -> SlabV7Entry (FileMetadata p sz mt) b Nothing) mc, Nothing)+ _ -> Nothing
src/Canontra/Canonical/FastScan.hs view
@@ -1,4 +1,7 @@ {-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StrictData #-}@@ -20,6 +23,7 @@ , isPureAsciiUnix ) where +import Control.DeepSeq (NFData) import Data.Bits ((.&.), complement, xor) import qualified Data.ByteString as BS import qualified Data.ByteString.Unsafe as BSU@@ -29,6 +33,7 @@ import Data.Word (Word64, Word8) import Foreign.Ptr (Ptr, castPtr, plusPtr) import Foreign.Storable (peek)+import GHC.Generics (Generic) import System.IO.Unsafe (unsafePerformIO) import Canontra.Canonical.Unicode (canonicalizeText, normalizeLineEndings)@@ -38,7 +43,8 @@ = PureAsciiUnix -- ^ 100% pure ASCII with standard Unix '\n' line endings (Zero transformation needed). | ContainsCRLF -- ^ ASCII or UTF-8 but contains '\r' (Requires line ending normalization). | RequiresUnicodeNFC -- ^ Contains non-ASCII bytes >= 0x80 (Requires Unicode NFC normalization).- deriving stock (Eq, Show, Enum, Bounded)+ deriving stock (Eq, Show, Enum, Bounded, Generic)+ deriving anyclass (NFData) -- | Scans a ByteString 8 bytes per CPU cycle using 64-bit SWAR bit-twiddling. {-# INLINE scanAsciiAndLineEndings #-}
src/Canontra/Canonical/FusedStream.hs view
@@ -15,6 +15,7 @@ -} module Canontra.Canonical.FusedStream ( fusedStreamProgram+ , fusedStreamNormalizedProgram , fusedStreamDeclarations , fusedStreamModule , fusedStreamDeclarationStructural@@ -22,6 +23,7 @@ , fusedStreamStmt , fusedStreamExpr , fusedHashProgram+ , fusedHashNormalizedProgram , fusedHashDeclarations ) where @@ -40,14 +42,20 @@ import Canontra.IR.Dependency import Canontra.IR.Expression import Canontra.IR.Program-import Canontra.Normalize.Normalize (isReflectionDocstring, normalizeModule, normalizeModuleDeclarations, preservesDocstrings)+import Canontra.Normalize.Normalize (CanonicalProgram (..), isReflectionDocstring, normalizeModule, normalizeModuleDeclarations, preservesDocstrings, toCanonicalProgram) import Canontra.Types (Fingerprint) -- | Compute F1 Structural fingerprint directly from IR with fused single-pass normalization and hashing. {-# INLINE fusedHashProgram #-} fusedHashProgram :: Program -> Fingerprint-fusedHashProgram = hashBuilderDirect . fusedStreamProgram+fusedHashProgram = fusedHashNormalizedProgram . toCanonicalProgram +-- | Compute F1 Structural fingerprint directly from an already-normalized 'CanonicalProgram'+-- without repeating AST normalization passes.+{-# INLINE fusedHashNormalizedProgram #-}+fusedHashNormalizedProgram :: CanonicalProgram -> Fingerprint+fusedHashNormalizedProgram = hashBuilderDirect . fusedStreamNormalizedProgram+ -- | Compute F2 Declaration fingerprint directly from declarations with fused single-pass normalization and hashing. {-# INLINE fusedHashDeclarations #-} fusedHashDeclarations :: [Declaration] -> Fingerprint@@ -56,10 +64,16 @@ -- | Serialize a Program directly to a Builder applying normalization on-the-fly. {-# INLINE fusedStreamProgram #-} fusedStreamProgram :: Program -> BB.Builder-fusedStreamProgram (Program modules lang) =+fusedStreamProgram = fusedStreamNormalizedProgram . toCanonicalProgram++-- | Serialize an already-normalized 'CanonicalProgram' directly to a Builder+-- without re-running 'normalizeModule'.+{-# INLINE fusedStreamNormalizedProgram #-}+fusedStreamNormalizedProgram :: CanonicalProgram -> BB.Builder+fusedStreamNormalizedProgram (CanonicalProgram (Program modules lang)) = tag 0x01 <> encodeText lang <>- encodeList fusedStreamModuleB modules+ encodeList fusedStreamNormalizedModuleB modules -- | Serialize a list of declarations directly to a Builder applying normalization on-the-fly (F2 format). {-# INLINE fusedStreamDeclarations #-}@@ -72,13 +86,15 @@ fusedStreamModule = fusedStreamModuleB fusedStreamModuleB :: Module -> BB.Builder-fusedStreamModuleB rawMod =- let Module _ normImps normDecls cleanStmts = normalizeModule rawMod- in tag 0x10 <>- encodeText "" <>- encodeList fusedStreamImportB normImps <>- encodeList fusedStreamDeclarationStructuralB normDecls <>- encodeList fusedStreamStmtB cleanStmts+fusedStreamModuleB = fusedStreamNormalizedModuleB . normalizeModule++fusedStreamNormalizedModuleB :: Module -> BB.Builder+fusedStreamNormalizedModuleB (Module _ normImps normDecls cleanStmts) =+ tag 0x10 <>+ encodeText "" <>+ encodeList fusedStreamImportB normImps <>+ encodeList fusedStreamDeclarationStructuralB normDecls <>+ encodeList fusedStreamStmtB cleanStmts fusedStreamImportB :: ImportDecl -> BB.Builder fusedStreamImportB = \case
src/Canontra/Export/Graph.hs view
@@ -16,7 +16,7 @@ , sanitizeDOTId ) where -import Data.List (nub)+import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T @@ -79,8 +79,16 @@ ++ [ "}" ] where allCallers = cgNodes cg- allCallees = nub [edgeCallee e | e <- cgEdges cg]+ allCallees = nubOrd [edgeCallee e | e <- cgEdges cg] allNodes = map Left allCallers ++ [Right c | c <- allCallees, not (calleeIsCaller c)]++ nubOrd :: Ord a => [a] -> [a]+ nubOrd = go Set.empty+ where+ go _ [] = []+ go seen (x:xs)+ | Set.member x seen = go seen xs+ | otherwise = x : go (Set.insert x seen) xs calleeIsCaller (TargetLocal n) = CallFunction n `elem` allCallers calleeIsCaller _ = False
src/Canontra/Fingerprint/Bundle.hs view
@@ -1,14 +1,17 @@+{-# LANGUAGE BangPatterns #-} {- | Module : Canontra.Fingerprint.Bundle-Description : Orchestrator for all 8 polyglot fingerprint tiers and manifest construction.+Description : Orchestrator for all 9 polyglot fingerprint tiers and manifest construction. This module unifies the full analysis pipeline for a given source unit across-Python, JavaScript, TypeScript, Go, and Rust. It runs parsing, normalization,-scope, call graph, control-flow (CFG), and data-flow (DFG) tier calculation.+Python, JavaScript, TypeScript, Go, and Rust. It normalizes the parsed AST+exactly once via 'CanonicalProgram' and feeds all structural/graph tiers in+a single fused pass. -} module Canontra.Fingerprint.Bundle ( computeBundle , computeBundleAndProgram+ , computeBundleFromCanonical , computeManifest , computeBundleFromSource , computeProgramFingerprints@@ -17,35 +20,38 @@ import qualified Data.ByteString as BS import Data.Text (Text)+import qualified Data.Text as T import qualified Data.Text.Encoding as TE -import Canontra.Fingerprint.CallGraph (computeFCG)+import Canontra.Fingerprint.CallGraph (computeFCGNormalized) import Canontra.Fingerprint.Composite (computeF4)-import Canontra.Fingerprint.ControlFlow (computeFCF)-import Canontra.Fingerprint.DataFlow (computeFDF)+import Canontra.Fingerprint.ControlFlow (computeFCFNormalized)+import Canontra.Fingerprint.DataFlow (computeFDFNormalized) import Canontra.Fingerprint.Declaration (computeF2, extractDeclarations) import Canontra.Fingerprint.Dependency (computeF3) import Canontra.Fingerprint.Source (computeF0)-import Canontra.Fingerprint.Structural (computeF1)+import Canontra.Fingerprint.Structural (computeF1Normalized) import Canontra.Fingerprint.TypeContract (computeFT) import Canontra.IR.Program (Program (..))+import Canontra.Normalize.Normalize (CanonicalProgram, toCanonicalProgram) import Canontra.Normalize.Rules (engineName, engineVersion, normalizationVersion)-import Canontra.Parser.Polyglot (parsePolyglotSource)+import Canontra.Parser.Polyglot (parsePolyglotByteString, parsePolyglotSource) import Canontra.Types --- | Compute multi-tier fingerprint bundle directly from an IR 'Program'.+-- | Compute multi-tier fingerprint bundle directly from an IR 'Program'+-- using single-pass normalization. computeProgramFingerprints :: Program -> FingerprintBundle computeProgramFingerprints prog =- let f0 = computeF1 prog- f1 = computeF1 prog- f2 = computeF2 prog- f3 = computeF3 prog- fcg = computeFCG prog- fcf = computeFCF prog- fdf = computeFDF prog- ft = computeFT prog- f4 = computeF4 f1 f2 f3 fcg fcf fdf ft- in FingerprintBundle f0 f1 f2 f3 fcg fcf fdf ft f4+ let !canonProg = toCanonicalProgram prog+ !f1 = computeF1Normalized canonProg+ !f2 = computeF2 prog+ !f3 = computeF3 prog+ !fcg = computeFCGNormalized canonProg+ !fcf = computeFCFNormalized canonProg+ !fdf = computeFDFNormalized canonProg+ !ft = computeFT prog+ !f4 = computeF4 f1 f2 f3 fcg fcf fdf ft+ in FingerprintBundle f1 f1 f2 f3 fcg fcf fdf ft f4 computeBundleFromSource :: FilePath -> Text -> Either ParseError FingerprintBundle computeBundleFromSource filePath src =@@ -55,25 +61,35 @@ computeBundle filePath rawBytes src = fmap fst (computeBundleAndProgram filePath rawBytes src) +-- | Compute multi-tier fingerprint bundle from raw bytes, parsed 'Program',+-- and its single-pass 'CanonicalProgram'.+computeBundleFromCanonical :: BS.ByteString -> Program -> CanonicalProgram -> FingerprintBundle+computeBundleFromCanonical rawBytes prog !canonProg =+ let !f0 = computeF0 rawBytes+ !f1 = computeF1Normalized canonProg+ !f2 = computeF2 prog+ !f3 = computeF3 prog+ !fcg = computeFCGNormalized canonProg+ !fcf = computeFCFNormalized canonProg+ !fdf = computeFDFNormalized canonProg+ !ft = computeFT prog+ !f4 = computeF4 f1 f2 f3 fcg fcf fdf ft+ in FingerprintBundle f0 f1 f2 f3 fcg fcf fdf ft f4+ -- | Compute multi-tier fingerprint bundle and retain the parsed IR 'Program'. computeBundleAndProgram :: FilePath -> BS.ByteString -> Text -> Either ParseError (FingerprintBundle, Program) computeBundleAndProgram filePath rawBytes src = do- prog <- parsePolyglotSource filePath src- let f0 = computeF0 rawBytes- f1 = computeF1 prog- f2 = computeF2 prog- f3 = computeF3 prog- fcg = computeFCG prog- fcf = computeFCF prog- fdf = computeFDF prog- ft = computeFT prog- f4 = computeF4 f1 f2 f3 fcg fcf fdf ft- Right (FingerprintBundle f0 f1 f2 f3 fcg fcf fdf ft f4, prog)+ prog <-+ if BS.null rawBytes && not (T.null src)+ then parsePolyglotSource filePath src+ else parsePolyglotByteString filePath rawBytes+ let !canonProg = toCanonicalProgram prog+ !bundle = computeBundleFromCanonical rawBytes prog canonProg+ Right (bundle, prog) computeManifest :: FilePath -> BS.ByteString -> Text -> Either ParseError Manifest computeManifest filePath rawBytes src = do- prog@(Program modules lang) <- parsePolyglotSource filePath src- bundle <- computeBundle filePath rawBytes src+ (bundle, prog@(Program modules lang)) <- computeBundleAndProgram filePath rawBytes src let decls = extractDeclarations prog meta = ManifestMetadata { mmFileCount = 1
src/Canontra/Fingerprint/CallGraph.hs view
@@ -9,6 +9,7 @@ -} module Canontra.Fingerprint.CallGraph ( computeFCG+ , computeFCGNormalized , extractCallGraph ) where @@ -16,13 +17,16 @@ import Canontra.Canonical.Serialize (canonicalizeCallGraph) import Canontra.Fingerprint.Source (hashBytes) import Canontra.IR.Program (Program)-import Canontra.Normalize.Normalize (normalizeProgram)+import Canontra.Normalize.Normalize (CanonicalProgram (..), toCanonicalProgram) import Canontra.Types (Fingerprint) computeFCG :: Program -> Fingerprint -- e.g. computeFCG prog -> F_CG call graph hash-computeFCG prog =- let normProg = normalizeProgram prog- cg = extractCallGraph normProg+computeFCG = computeFCGNormalized . toCanonicalProgram++-- | Compute F_CG directly from an already-normalized 'CanonicalProgram'.+computeFCGNormalized :: CanonicalProgram -> Fingerprint+computeFCGNormalized (CanonicalProgram normProg) =+ let cg = extractCallGraph normProg canonBytes = canonicalizeCallGraph cg in hashBytes canonBytes
src/Canontra/Fingerprint/ControlFlow.hs view
@@ -7,6 +7,7 @@ -} module Canontra.Fingerprint.ControlFlow ( computeFCF+ , computeFCFNormalized ) where import Canontra.Analysis.CFG (buildCFGs)@@ -14,13 +15,16 @@ import Canontra.Canonical.Serialize (canonicalizeCFGs) import Canontra.Fingerprint.Source (hashBytes) import Canontra.IR.Program (Program)-import Canontra.Normalize.Normalize (normalizeProgram)+import Canontra.Normalize.Normalize (CanonicalProgram (..), toCanonicalProgram) import Canontra.Types (Fingerprint) -- | Compute the F_CF control-flow fingerprint for a Program. computeFCF :: Program -> Fingerprint-computeFCF prog =- let normProg = normalizeProgram prog- cfgs = map canonicalizeCFGRPO (buildCFGs normProg)+computeFCF = computeFCFNormalized . toCanonicalProgram++-- | Compute F_CF directly from an already-normalized 'CanonicalProgram'.+computeFCFNormalized :: CanonicalProgram -> Fingerprint+computeFCFNormalized (CanonicalProgram normProg) =+ let cfgs = map canonicalizeCFGRPO (buildCFGs normProg) canonicalBytes = canonicalizeCFGs cfgs in hashBytes canonicalBytes
src/Canontra/Fingerprint/DataFlow.hs view
@@ -7,19 +7,23 @@ -} module Canontra.Fingerprint.DataFlow ( computeFDF+ , computeFDFNormalized ) where import Canontra.Analysis.DFG (buildDFGs) import Canontra.Canonical.Serialize (canonicalizeDFGs) import Canontra.Fingerprint.Source (hashBytes) import Canontra.IR.Program (Program)-import Canontra.Normalize.Normalize (normalizeProgram)+import Canontra.Normalize.Normalize (CanonicalProgram (..), toCanonicalProgram) import Canontra.Types (Fingerprint) -- | Compute the F_DF data-flow fingerprint for a Program. computeFDF :: Program -> Fingerprint-computeFDF prog =- let normProg = normalizeProgram prog- dfgs = buildDFGs normProg+computeFDF = computeFDFNormalized . toCanonicalProgram++-- | Compute F_DF directly from an already-normalized 'CanonicalProgram'.+computeFDFNormalized :: CanonicalProgram -> Fingerprint+computeFDFNormalized (CanonicalProgram normProg) =+ let dfgs = buildDFGs normProg canonicalBytes = canonicalizeDFGs dfgs in hashBytes canonicalBytes
src/Canontra/Fingerprint/Structural.hs view
@@ -8,11 +8,17 @@ -} module Canontra.Fingerprint.Structural ( computeF1+ , computeF1Normalized ) where -import Canontra.Canonical.FusedStream (fusedHashProgram)+import Canontra.Canonical.FusedStream (fusedHashNormalizedProgram, fusedHashProgram) import Canontra.IR.Program (Program)+import Canontra.Normalize.Normalize (CanonicalProgram) import Canontra.Types (Fingerprint) computeF1 :: Program -> Fingerprint -- e.g. computeF1 prog -> F1 hash computeF1 = fusedHashProgram++-- | Compute F1 directly from an already-normalized 'CanonicalProgram'.+computeF1Normalized :: CanonicalProgram -> Fingerprint+computeF1Normalized = fusedHashNormalizedProgram
src/Canontra/Fingerprint/TypeContract.hs view
@@ -22,6 +22,7 @@ import Canontra.Analysis.TypeContract ( InterfaceContract (..) , MethodContract (..)+ , Mutability (..) , StructuralType (..) , extractTypeContracts )@@ -86,3 +87,11 @@ in BB.word8 0x08 <> BB.word32BE (fromIntegral (BS.length b)) <> BB.byteString b <> BB.word32BE (fromIntegral (length args)) <> foldMap serializeType args TypeRecVar d -> BB.word8 0x09 <> BB.word32BE (fromIntegral d)+ TypeRef Immut inner ->+ BB.word8 0x0A <> BB.word8 0x00 <> serializeType inner+ TypeRef Mut inner ->+ BB.word8 0x0A <> BB.word8 0x01 <> serializeType inner+ TypePtr inner ->+ BB.word8 0x0B <> serializeType inner+ TypeTuple elems ->+ BB.word8 0x0C <> BB.word32BE (fromIntegral (length elems)) <> foldMap serializeType elems
+ src/Canontra/Harness/Guard.hs view
@@ -0,0 +1,259 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE StrictData #-}++{- |+Module : Canontra.Harness.Guard+Description : Deterministic semantic policy gate (@canontra snap guard@) for AI harnesses.++Evaluates the live workspace against a baseline snapshot (@snap_0@, @HEAD@, or any+@snap_id@) and rejects mutations touching forbidden fingerprint tiers (e.g. @F2,F3,F_T@+during a refactor-only agent turn). Emits machine-readable JSON diagnostics and returns+POSIX exit code 0 (pass) or 1 (violation).+-}+module Canontra.Harness.Guard+ ( GuardTier (..)+ , guardTierName+ , parseGuardTiers+ , matchesGlob+ , GuardViolation (..)+ , SnapGuardReport (..)+ , snapGuard+ , formatSnapGuard+ , formatSnapGuardJson+ ) where++import Control.DeepSeq (NFData)+import Data.Aeson (ToJSON (..), object, (.=))+import qualified Data.Aeson.Encode.Pretty as AesonPretty+import qualified Data.ByteString.Lazy as LBS+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import GHC.Clock (getMonotonicTimeNSec)+import GHC.Generics (Generic)++import Canontra.Harness.Store+ ( SnapFileDelta (..)+ , SnapManifest (..)+ , readSnapManifest+ )+import Canontra.Harness.SubVersion+ ( computeFileDeltas+ , scanWorkspaceRecords+ )+import Canontra.Normalize.Rules (snapSchemaVersion, snapStability)+import Canontra.Repository.Repository (normalizePathPosix)++-- | Fingerprint tiers enforceable by @canontra snap guard --forbid@.+data GuardTier+ = TierF0+ | TierF1+ | TierF2+ | TierF3+ | TierFCG+ | TierFCF+ | TierFDF+ | TierFT+ | TierF4+ deriving stock (Eq, Ord, Show, Generic)+ deriving anyclass (NFData)++-- | Canonical tier identifier string matching 'diffFileBundles'.+guardTierName :: GuardTier -> Text+guardTierName = \case+ TierF0 -> "F0"+ TierF1 -> "F1"+ TierF2 -> "F2"+ TierF3 -> "F3"+ TierFCG -> "F_CG"+ TierFCF -> "F_CF"+ TierFDF -> "F_DF"+ TierFT -> "F_T"+ TierF4 -> "F4"++instance ToJSON GuardTier where+ toJSON = toJSON . guardTierName++-- | Parse comma-separated tier names (e.g. @"F2,F3,F_T"@).+parseGuardTiers :: Text -> Either String [GuardTier]+parseGuardTiers raw =+ let parts = filter (not . T.null) (map T.strip (T.splitOn "," raw))+ in if null parts+ then Left "Empty --forbid tier list (expected e.g. F2,F3,F_T)"+ else mapM parseOne parts+ where+ parseOne txt = case T.toUpper txt of+ "F0" -> Right TierF0+ "F1" -> Right TierF1+ "F2" -> Right TierF2+ "F3" -> Right TierF3+ "F_CG" -> Right TierFCG+ "FCG" -> Right TierFCG+ "F_CF" -> Right TierFCF+ "FCF" -> Right TierFCF+ "F_DF" -> Right TierFDF+ "FDF" -> Right TierFDF+ "F_T" -> Right TierFT+ "FT" -> Right TierFT+ "F4" -> Right TierF4+ _ -> Left ("Unknown guard tier '" ++ T.unpack txt+ ++ "' (valid: F0, F1, F2, F3, F_CG, F_CF, F_DF, F_T, F4)")++-- | Pure POSIX glob matcher supporting @**@ (multi-segment), @*@ (single segment), and @?@.+matchesGlob :: Text -> Text -> Bool+matchesGlob rawPat rawPath =+ let patSegs = filter (not . T.null) (T.splitOn "/" (normSlashes rawPat))+ pathSegs = filter (not . T.null) (T.splitOn "/" (normSlashes rawPath))+ in matchSegs patSegs pathSegs+ where+ normSlashes = T.pack . normalizePathPosix . T.unpack++ matchSegs [] [] = True+ matchSegs ("**" : ps) xs =+ matchSegs ps xs || case xs of+ (_ : xr) -> matchSegs ("**" : ps) xr+ [] -> False+ matchSegs (p : ps) (x : xs) =+ matchWord (T.unpack p) (T.unpack x) && matchSegs ps xs+ matchSegs _ _ = False++ matchWord [] [] = True+ matchWord ('*' : ps) xs =+ matchWord ps xs || case xs of+ (_ : xr) -> matchWord ('*' : ps) xr+ [] -> False+ matchWord ('?' : ps) (_ : xs) = matchWord ps xs+ matchWord (p : ps) (x : xs) = p == x && matchWord ps xs+ matchWord _ _ = False++-- | Single file policy violation under @snap guard@.+data GuardViolation = GuardViolation+ { gvPath :: !FilePath+ , gvStatus :: !Text+ , gvSeverity :: !Text+ , gvViolatedTiers :: ![Text]+ , gvMutatedTiers :: ![Text]+ } deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++instance ToJSON GuardViolation where+ toJSON v = object+ [ "path" .= gvPath v+ , "status" .= gvStatus v+ , "severity" .= gvSeverity v+ , "violated_tiers" .= gvViolatedTiers v+ , "mutated_tiers" .= gvMutatedTiers v+ ]++-- | Full evaluation report returned by @canontra snap guard@.+data SnapGuardReport = SnapGuardReport+ { sgrSchemaVersion :: !Text+ , sgrStability :: !Text+ , sgrAgainstSnapId :: !Text+ , sgrForbiddenTiers :: ![Text]+ , sgrAllowPaths :: ![Text]+ , sgrPassed :: !Bool+ , sgrViolations :: ![GuardViolation]+ , sgrAllowedSkipped :: ![FilePath]+ , sgrElapsedMs :: !Double+ } deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++instance ToJSON SnapGuardReport where+ toJSON r = object+ [ "schema_version" .= sgrSchemaVersion r+ , "stability" .= sgrStability r+ , "against_snap_id" .= sgrAgainstSnapId r+ , "forbidden_tiers" .= sgrForbiddenTiers r+ , "allow_paths" .= sgrAllowPaths r+ , "passed" .= sgrPassed r+ , "violations" .= sgrViolations r+ , "allowed_skipped" .= sgrAllowedSkipped r+ , "elapsed_ms" .= sgrElapsedMs r+ ]++-- | Evaluate live workspace mutations against a baseline snapshot and forbidden tiers.+snapGuard+ :: FilePath+ -> Text+ -> [GuardTier]+ -> [Text]+ -> IO (Either String SnapGuardReport)+snapGuard repoDir againstRef forbiddenTiers allowGlobs = do+ t0 <- getMonotonicTimeNSec+ eBase <- readSnapManifest repoDir againstRef+ case eBase of+ Left err -> pure (Left err)+ Right baseMan -> do+ eScan <- scanWorkspaceRecords repoDir+ case eScan of+ Left err -> pure (Left err)+ Right (_, liveRecords) -> do+ let deltas = computeFileDeltas (smFiles baseMan) liveRecords+ forbiddenNames = map guardTierName forbiddenTiers+ forbiddenSet = Set.fromList forbiddenNames+ (allowedList, checkedDeltas) = foldr partitionAllow ([], []) deltas+ violations =+ [ GuardViolation+ (sfdPath d)+ (sfdStatus d)+ (sfdSeverity d)+ hits+ (sfdMutatedTiers d)+ | d <- checkedDeltas+ , let hits = filter (`Set.member` forbiddenSet) (sfdMutatedTiers d)+ , not (null hits)+ ]+ t1 <- getMonotonicTimeNSec+ let !elapsed = fromIntegral (toInteger t1 - toInteger t0) / 1000000.0+ pure $ Right SnapGuardReport+ { sgrSchemaVersion = snapSchemaVersion+ , sgrStability = snapStability+ , sgrAgainstSnapId = smSnapId baseMan+ , sgrForbiddenTiers = forbiddenNames+ , sgrAllowPaths = allowGlobs+ , sgrPassed = null violations+ , sgrViolations = violations+ , sgrAllowedSkipped = allowedList+ , sgrElapsedMs = elapsed+ }+ where+ partitionAllow d (al, chk)+ | any (\g -> matchesGlob g (T.pack (sfdPath d))) allowGlobs =+ (sfdPath d : al, chk)+ | otherwise =+ (al, d : chk)++formatSnapGuard :: SnapGuardReport -> Text+formatSnapGuard r =+ T.unlines $+ [ "================================================================================"+ , " CANONTRA SNAP GUARD (" <> T.toUpper snapStability <> ")"+ , "================================================================================"+ , " Against Snap: " <> sgrAgainstSnapId r+ , " Forbidden Tiers: " <> T.intercalate "," (sgrForbiddenTiers r)+ , " Status: " <> if sgrPassed r then "PASS (0 policy violations)" else "FAIL (" <> T.pack (show (length (sgrViolations r))) <> " violation(s))"+ , " Latency: " <> T.pack (show (round1 (sgrElapsedMs r))) <> " ms"+ ]+ ++ (if null (sgrViolations r)+ then []+ else+ [ "--------------------------------------------------------------------------------"+ , " Policy Violations:"+ ] +++ [ " [VIOLATION] " <> T.pack (gvPath v)+ <> " (" <> gvStatus v <> ", forbidden: " <> T.intercalate "," (gvViolatedTiers v) <> ")"+ | v <- sgrViolations r+ ])+ ++ [ "================================================================================" ]+ where+ round1 :: Double -> Double+ round1 x = fromIntegral (round (x * 100.0) :: Int) / 100.0++formatSnapGuardJson :: SnapGuardReport -> LBS.ByteString+formatSnapGuardJson = AesonPretty.encodePretty
+ src/Canontra/Harness/Store.hs view
@@ -0,0 +1,537 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE StrictData #-}++{- |+Module : Canontra.Harness.Store+Description : Content-addressed snapshot store (.canontra/snaps/) for AI harness sub-versioning.++Provides a zero-daemon, zero-.git-mutation local store under @.canontra/snaps/@:+ - @HEAD@ pointer to the active @snap_id@+ - @ledger.jsonl@ append-only turn metadata ledger+ - @objects/<ab>/<cdef...>@ SHA-256 content-addressed @F0@ source blobs+ - @manifests/<snap_id>.json@ complete snapshot manifests++All writes use temp files + atomic swap ('atomicSwapWithRetry_'), and all reads+for workspace restoration verify SHA-256 integrity and path containment before+any mutation occurs.+-}+module Canontra.Harness.Store+ ( -- * Schema & Classification Types+ SnapClassification (..)+ , classificationText+ , parseClassificationText+ , SnapFileRecord (..)+ , SnapFileDelta (..)+ , SnapManifest (..)+ , LedgerEntry (..)++ -- * Path Layout & Security Validators+ , canontraStateDir+ , snapsRootDir+ , objectsDir+ , manifestsDir+ , headFilePath+ , ledgerFilePath+ , manifestFilePath+ , objectBlobPath+ , isSafeSnapId+ , isValidSha256Hex+ , isSafeRelativeFilePath+ , getCurrentPidString++ -- * Store Lifecycle & Atomic I/O+ , ensureSnapStore+ , readHeadSnapId+ , writeHeadSnapId+ , storeBlobIfAbsent+ , readVerifiedBlob+ , writeSnapManifest+ , resolveSnapId+ , readSnapManifest+ , readSnapManifestDirect+ , appendLedgerEntry+ , readLedgerEntries+ , listAllManifestIds+ , removeManifestFile+ ) where++import Control.DeepSeq (NFData)+import Control.Exception (IOException, try)+import qualified Data.Aeson as Aeson+import Data.Aeson (FromJSON (..), ToJSON (..), object, (.=), (.:), (.:?))+import qualified Data.Aeson.Encode.Pretty as AesonPretty+import qualified Data.ByteString as BS+import qualified Data.ByteString.Lazy as LBS+import qualified Data.ByteString.Lazy.Char8 as LBSC+import Data.Char (isAlphaNum, isHexDigit)+import Data.List (isPrefixOf, sort)+import Data.Map.Strict (Map)+import Data.Maybe (mapMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import GHC.Generics (Generic)+import System.Directory+ ( createDirectoryIfMissing+ , doesFileExist+ , listDirectory+ , removeFile+ )+import System.FilePath+ ( dropExtension+ , splitDirectories+ , takeDirectory+ , takeExtension+ , (</>)+ )+import System.Posix.Internals (c_getpid)++import Canontra.Cache.Common (atomicSwapWithRetry_)+import Canontra.Fingerprint.Source (computeF0)+import Canontra.Types (Fingerprint (..), FingerprintBundle)++-- | Semantic classification of a snapshot transition.+data SnapClassification+ = SnapNoChange+ | SnapSemanticNoop+ | SnapInternalLogic+ | SnapContractChange+ deriving stock (Eq, Ord, Show, Generic)+ deriving anyclass (NFData)++-- | Wire string representation of 'SnapClassification'.+classificationText :: SnapClassification -> Text+classificationText = \case+ SnapNoChange -> "no_change"+ SnapSemanticNoop -> "semantic_noop"+ SnapInternalLogic -> "internal_logic"+ SnapContractChange -> "contract_change"++-- | Parse wire string representation into 'SnapClassification'.+parseClassificationText :: Text -> Maybe SnapClassification+parseClassificationText = \case+ "no_change" -> Just SnapNoChange+ "semantic_noop" -> Just SnapSemanticNoop+ "internal_logic" -> Just SnapInternalLogic+ "contract_change" -> Just SnapContractChange+ _ -> Nothing++instance ToJSON SnapClassification where+ toJSON = toJSON . classificationText++instance FromJSON SnapClassification where+ parseJSON = Aeson.withText "SnapClassification" $ \txt ->+ case parseClassificationText txt of+ Just c -> pure c+ Nothing -> fail ("Unknown SnapClassification: " ++ T.unpack txt)++-- | Stored metadata + 9-tier fingerprint bundle for a single file in a snapshot.+data SnapFileRecord = SnapFileRecord+ { sfrPath :: !FilePath+ , sfrF0 :: !Text+ , sfrSize :: !Integer+ , sfrBundle :: !FingerprintBundle+ } deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++instance ToJSON SnapFileRecord where+ toJSON r = object+ [ "path" .= sfrPath r+ , "f0" .= sfrF0 r+ , "size" .= sfrSize r+ , "bundle" .= sfrBundle r+ ]++instance FromJSON SnapFileRecord where+ parseJSON = Aeson.withObject "SnapFileRecord" $ \o ->+ SnapFileRecord+ <$> o .: "path"+ <*> o .: "f0"+ <*> o .: "size"+ <*> o .: "bundle"++-- | Per-file semantic delta entry emitted by @snap mark@ and @snap diff@.+data SnapFileDelta = SnapFileDelta+ { sfdPath :: !FilePath+ , sfdStatus :: !Text+ , sfdSeverity :: !Text+ , sfdMutatedTiers :: ![Text]+ , sfdInvariantTiers :: ![Text]+ } deriving stock (Eq, Ord, Show, Generic)+ deriving anyclass (NFData)++instance ToJSON SnapFileDelta where+ toJSON d = object+ [ "path" .= sfdPath d+ , "status" .= sfdStatus d+ , "severity" .= sfdSeverity d+ , "mutated_tiers" .= sfdMutatedTiers d+ , "invariant_tiers" .= sfdInvariantTiers d+ ]++instance FromJSON SnapFileDelta where+ parseJSON = Aeson.withObject "SnapFileDelta" $ \o ->+ SnapFileDelta+ <$> o .: "path"+ <*> o .: "status"+ <*> o .: "severity"+ <*> o .: "mutated_tiers"+ <*> o .: "invariant_tiers"++-- | Complete snapshot manifest stored under @.canontra/snaps/manifests/<snap_id>.json@.+data SnapManifest = SnapManifest+ { smSchemaVersion :: !Text+ , smStability :: !Text+ , smSnapId :: !Text+ , smParentId :: !(Maybe Text)+ , smTimestamp :: !Text+ , smLabel :: !(Maybe Text)+ , smAgent :: !(Maybe Text)+ , smClassification :: !SnapClassification+ , smRepoFR :: !Text+ , smRepoFWCG :: !(Maybe Text)+ , smRepoFWDF :: !(Maybe Text)+ , smFiles :: !(Map FilePath SnapFileRecord)+ , smChangedFiles :: ![SnapFileDelta]+ , smRecommendedTests :: ![Text]+ , smElapsedMs :: !Double+ } deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++instance ToJSON SnapManifest where+ toJSON m = object+ [ "schema_version" .= smSchemaVersion m+ , "stability" .= smStability m+ , "snap_id" .= smSnapId m+ , "parent_id" .= smParentId m+ , "timestamp" .= smTimestamp m+ , "label" .= smLabel m+ , "agent" .= smAgent m+ , "classification" .= smClassification m+ , "repo_f_r" .= smRepoFR m+ , "repo_f_wcg" .= smRepoFWCG m+ , "repo_f_wdf" .= smRepoFWDF m+ , "files" .= smFiles m+ , "changed_files" .= smChangedFiles m+ , "recommended_tests" .= smRecommendedTests m+ , "elapsed_ms" .= smElapsedMs m+ ]++instance FromJSON SnapManifest where+ parseJSON = Aeson.withObject "SnapManifest" $ \o ->+ SnapManifest+ <$> o .: "schema_version"+ <*> o .: "stability"+ <*> o .: "snap_id"+ <*> o .:? "parent_id"+ <*> o .: "timestamp"+ <*> o .:? "label"+ <*> o .:? "agent"+ <*> o .: "classification"+ <*> o .: "repo_f_r"+ <*> o .:? "repo_f_wcg"+ <*> o .:? "repo_f_wdf"+ <*> o .: "files"+ <*> o .: "changed_files"+ <*> o .: "recommended_tests"+ <*> o .: "elapsed_ms"++-- | Compact line entry appended to @.canontra/snaps/ledger.jsonl@.+data LedgerEntry = LedgerEntry+ { leSnapId :: !Text+ , leParentId :: !(Maybe Text)+ , leTimestamp :: !Text+ , leLabel :: !(Maybe Text)+ , leAgent :: !(Maybe Text)+ , leClassification :: !SnapClassification+ , leRepoFR :: !Text+ , leFileCount :: !Int+ , leChangedCount :: !Int+ , leElapsedMs :: !Double+ } deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++instance ToJSON LedgerEntry where+ toJSON e = object+ [ "snap_id" .= leSnapId e+ , "parent_id" .= leParentId e+ , "timestamp" .= leTimestamp e+ , "label" .= leLabel e+ , "agent" .= leAgent e+ , "classification" .= leClassification e+ , "repo_f_r" .= leRepoFR e+ , "file_count" .= leFileCount e+ , "changed_count" .= leChangedCount e+ , "elapsed_ms" .= leElapsedMs e+ ]++instance FromJSON LedgerEntry where+ parseJSON = Aeson.withObject "LedgerEntry" $ \o ->+ LedgerEntry+ <$> o .: "snap_id"+ <*> o .:? "parent_id"+ <*> o .: "timestamp"+ <*> o .:? "label"+ <*> o .:? "agent"+ <*> o .: "classification"+ <*> o .: "repo_f_r"+ <*> o .: "file_count"+ <*> o .: "changed_count"+ <*> o .: "elapsed_ms"++-- ============================================================================+-- Path Layout & Validation Helpers+-- ============================================================================++canontraStateDir :: FilePath -> FilePath+canontraStateDir repoDir = repoDir </> ".canontra"++snapsRootDir :: FilePath -> FilePath+snapsRootDir repoDir = canontraStateDir repoDir </> "snaps"++objectsDir :: FilePath -> FilePath+objectsDir repoDir = snapsRootDir repoDir </> "objects"++manifestsDir :: FilePath -> FilePath+manifestsDir repoDir = snapsRootDir repoDir </> "manifests"++headFilePath :: FilePath -> FilePath+headFilePath repoDir = snapsRootDir repoDir </> "HEAD"++ledgerFilePath :: FilePath -> FilePath+ledgerFilePath repoDir = snapsRootDir repoDir </> "ledger.jsonl"++manifestFilePath :: FilePath -> Text -> FilePath+manifestFilePath repoDir snapId =+ manifestsDir repoDir </> (T.unpack snapId ++ ".json")++-- | Validate that a snapshot identifier contains only safe filename characters+-- (@[A-Za-z0-9_-]@) and bounded length, eliminating traversal risk.+isSafeSnapId :: Text -> Bool+isSafeSnapId sid =+ not (T.null sid)+ && T.length sid <= 128+ && T.all (\c -> isAlphaNum c || c == '_' || c == '-') sid++-- | Validate canonical 64-character SHA-256 hex digest.+isValidSha256Hex :: Text -> Bool+isValidSha256Hex txt =+ T.length txt == 64 && T.all isHexDigit txt++-- | Validate that a workspace-relative POSIX path cannot traverse outside root.+isSafeRelativeFilePath :: FilePath -> Bool+isSafeRelativeFilePath fp+ | null fp = False+ | any (== '\0') fp = False+ | head fp == '/' || head fp == '\\' = False+ | otherwise =+ let dirs = splitDirectories (map (\c -> if c == '\\' then '/' else c) fp)+ in not (null dirs)+ && all (\seg -> seg /= ".." && seg /= ".") dirs+ && not (any (':' `elem`) dirs)++-- | Compute sharded content-addressed blob path (@objects/<ab>/<rest>@).+objectBlobPath :: FilePath -> Text -> Maybe FilePath+objectBlobPath repoDir f0Hex+ | not (isValidSha256Hex f0Hex) = Nothing+ | otherwise =+ let lowerHex = T.toLower f0Hex+ dirPart = T.unpack (T.take 2 lowerHex)+ filePart = T.unpack (T.drop 2 lowerHex)+ in Just (objectsDir repoDir </> dirPart </> filePart)++getCurrentPidString :: IO String+getCurrentPidString = do+ pid <- c_getpid+ pure (show pid)++-- ============================================================================+-- Store Initialization & Atomic I/O+-- ============================================================================++-- | Initialize @.canontra/snaps/{objects,manifests}@ and drop a protective+-- @.canontra/.gitignore@ so AI snap/cache state is never accidentally committed.+ensureSnapStore :: FilePath -> IO ()+ensureSnapStore repoDir = do+ createDirectoryIfMissing True (objectsDir repoDir)+ createDirectoryIfMissing True (manifestsDir repoDir)+ let giPath = canontraStateDir repoDir </> ".gitignore"+ exists <- doesFileExist giPath+ if exists+ then pure ()+ else writeFile giPath "# Generated by Canontra — do not commit local cache or snap state\n*\n"++-- | Read the active @snap_id@ pointed to by @.canontra/snaps/HEAD@.+readHeadSnapId :: FilePath -> IO (Maybe Text)+readHeadSnapId repoDir = do+ let hp = headFilePath repoDir+ exists <- doesFileExist hp+ if not exists+ then pure Nothing+ else do+ eBytes <- try (BS.readFile hp) :: IO (Either IOException BS.ByteString)+ case eBytes of+ Left _ -> pure Nothing+ Right raw ->+ let sid = T.strip (TE.decodeUtf8Lenient raw)+ in if isSafeSnapId sid then pure (Just sid) else pure Nothing++-- | Atomically update @.canontra/snaps/HEAD@.+writeHeadSnapId :: FilePath -> Text -> IO ()+writeHeadSnapId repoDir sid = do+ let hp = headFilePath repoDir+ pidStr <- getCurrentPidString+ let tmp = hp ++ ".tmp." ++ pidStr+ BS.writeFile tmp (TE.encodeUtf8 (sid <> "\n"))+ atomicSwapWithRetry_ tmp hp++-- | Store raw bytes into content-addressed @objects/<ab>/<rest>@ only if absent.+-- Returns 'True' when a new blob was written and 'False' on deduplicated skip.+storeBlobIfAbsent :: FilePath -> Text -> BS.ByteString -> IO Bool+storeBlobIfAbsent repoDir f0Hex rawBytes =+ case objectBlobPath repoDir f0Hex of+ Nothing -> pure False+ Just blobPath -> do+ exists <- doesFileExist blobPath+ if exists+ then pure False+ else do+ createDirectoryIfMissing True (takeDirectory blobPath)+ pidStr <- getCurrentPidString+ let tmp = blobPath ++ ".tmp." ++ pidStr+ BS.writeFile tmp rawBytes+ atomicSwapWithRetry_ tmp blobPath+ pure True++-- | Read a stored blob and verify its SHA-256 matches @expectedF0@ before returning.+readVerifiedBlob :: FilePath -> Text -> IO (Either String BS.ByteString)+readVerifiedBlob repoDir expectedF0 =+ case objectBlobPath repoDir expectedF0 of+ Nothing -> pure (Left ("Invalid SHA-256 blob key: " ++ T.unpack expectedF0))+ Just blobPath -> do+ exists <- doesFileExist blobPath+ if not exists+ then pure (Left ("Missing blob in .canontra/snaps/objects for digest " ++ T.unpack expectedF0))+ else do+ eBytes <- try (BS.readFile blobPath) :: IO (Either IOException BS.ByteString)+ case eBytes of+ Left err -> pure (Left ("Failed reading blob " ++ blobPath ++ ": " ++ show err))+ Right rawBytes ->+ let actualF0 = T.toLower (unFingerprint (computeF0 rawBytes))+ normExpected = T.toLower expectedF0+ in if actualF0 == normExpected+ then pure (Right rawBytes)+ else pure (Left ("SHA-256 verification failed for blob " ++ T.unpack expectedF0+ ++ " (computed " ++ T.unpack actualF0 ++ ")"))++-- | Atomically persist a 'SnapManifest' JSON document.+writeSnapManifest :: FilePath -> SnapManifest -> IO ()+writeSnapManifest repoDir manifest = do+ let mp = manifestFilePath repoDir (smSnapId manifest)+ createDirectoryIfMissing True (takeDirectory mp)+ pidStr <- getCurrentPidString+ let tmp = mp ++ ".tmp." ++ pidStr+ LBS.writeFile tmp (AesonPretty.encodePretty manifest)+ atomicSwapWithRetry_ tmp mp++-- | List all valid snapshot IDs sorted lexicographically.+listAllManifestIds :: FilePath -> IO [Text]+listAllManifestIds repoDir = do+ let mDir = manifestsDir repoDir+ eEntries <- try (listDirectory mDir) :: IO (Either IOException [FilePath])+ case eEntries of+ Left _ -> pure []+ Right entries ->+ pure $ sort+ [ T.pack stem+ | f <- entries+ , takeExtension f == ".json"+ , let stem = dropExtension f+ , isSafeSnapId (T.pack stem)+ ]++-- | Resolve @"HEAD"@, @"latest"@, an exact @snap_id@, or a unique prefix to a canonical @snap_id@.+resolveSnapId :: FilePath -> Text -> IO (Either String Text)+resolveSnapId repoDir rawRef+ | rawRef == "HEAD" || rawRef == "latest" = do+ mHead <- readHeadSnapId repoDir+ case mHead of+ Just sid -> pure (Right sid)+ Nothing -> pure (Left "No snapshot HEAD found. Run 'canontra snap init' first.")+ | not (isSafeSnapId rawRef) =+ pure (Left ("Security/validation error: unsafe snapshot identifier '" ++ T.unpack rawRef ++ "'"))+ | otherwise = do+ let exactPath = manifestFilePath repoDir rawRef+ exactExists <- doesFileExist exactPath+ if exactExists+ then pure (Right rawRef)+ else do+ allIds <- listAllManifestIds repoDir+ let matches = filter (T.unpack rawRef `isPrefixOf`) (map T.unpack allIds)+ case matches of+ [unique] -> pure (Right (T.pack unique))+ [] -> pure (Left ("Snapshot not found: '" ++ T.unpack rawRef ++ "'"))+ manyMatches ->+ pure (Left ("Ambiguous snapshot prefix '" ++ T.unpack rawRef ++ "' matches: "+ ++ unwords (take 5 manyMatches)))++-- | Resolve and decode a 'SnapManifest'.+readSnapManifest :: FilePath -> Text -> IO (Either String SnapManifest)+readSnapManifest repoDir ref = do+ eSid <- resolveSnapId repoDir ref+ case eSid of+ Left err -> pure (Left err)+ Right sid -> readSnapManifestDirect repoDir sid++-- | Read and decode a manifest by exact validated @snap_id@.+readSnapManifestDirect :: FilePath -> Text -> IO (Either String SnapManifest)+readSnapManifestDirect repoDir sid+ | not (isSafeSnapId sid) = pure (Left ("Unsafe snapshot identifier: " ++ T.unpack sid))+ | otherwise = do+ let mp = manifestFilePath repoDir sid+ eBytes <- try (LBS.readFile mp) :: IO (Either IOException LBS.ByteString)+ case eBytes of+ Left err -> pure (Left ("Failed reading manifest " ++ mp ++ ": " ++ show err))+ Right lbs ->+ case Aeson.eitherDecode lbs of+ Left decErr -> pure (Left ("Corrupt snapshot manifest " ++ mp ++ ": " ++ decErr))+ Right m -> pure (Right m)++-- | Append a compact JSON line to @.canontra/snaps/ledger.jsonl@.+appendLedgerEntry :: FilePath -> LedgerEntry -> IO ()+appendLedgerEntry repoDir entry = do+ let lp = ledgerFilePath repoDir+ lineBS = LBS.toStrict (Aeson.encode entry <> "\n")+ BS.appendFile lp lineBS++-- | Read all valid ledger entries in chronological append order.+readLedgerEntries :: FilePath -> IO [LedgerEntry]+readLedgerEntries repoDir = do+ let lp = ledgerFilePath repoDir+ exists <- doesFileExist lp+ if not exists+ then pure []+ else do+ eBytes <- try (LBS.readFile lp) :: IO (Either IOException LBS.ByteString)+ case eBytes of+ Left _ -> pure []+ Right lbs ->+ pure $ mapMaybe decodeLine (LBSC.lines lbs)+ where+ decodeLine line+ | LBS.null line = Nothing+ | otherwise = Aeson.decode line++-- | Safely remove a manifest JSON file by exact validated ID.+removeManifestFile :: FilePath -> Text -> IO ()+removeManifestFile repoDir sid+ | not (isSafeSnapId sid) = pure ()+ | otherwise = do+ let mp = manifestFilePath repoDir sid+ exists <- doesFileExist mp+ if exists then removeFile mp else pure ()
+ src/Canontra/Harness/SubVersion.hs view
@@ -0,0 +1,982 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE StrictData #-}++{- |+Module : Canontra.Harness.SubVersion+Description : Stateless AI harness semantic sub-versioning engine (@canontra snap@).++Implements zero-daemon, zero-.git-mutation semantic checkpoints and recovery:+ - @snapInit@: capture baseline @snap_0@ under @.canontra/snaps/@+ - @snapMark@: incremental warm scan (< 25 ms target) + 9-tier semantic classification+ - @snapDiff@: token-compact 3-level delta + symbol diff + blast-radius test slicing+ - @snapRewind@: preflight SHA-256 + path-containment verified atomic workspace rollback+ - @snapLog@: chronological turn history inspection+ - @snapGC@: mark-and-sweep garbage collection over unreferenced @F0@ blobs+-}+module Canontra.Harness.SubVersion+ ( -- * Report Types+ SnapSymbolChange (..)+ , SnapDiffReport (..)+ , SnapRewindReport (..)+ , SnapGCReport (..)++ -- * Core Delta & Classification Functions+ , allTierNames+ , diffFileBundles+ , computeFileDeltas+ , classifySnapDeltas+ , scanWorkspaceRecords+ , recommendTestsForDeltas+ , toRunnableTestCommand++ -- * Harness Operations+ , snapInit+ , snapMark+ , snapDiff+ , snapRewind+ , snapLog+ , snapGC++ -- * Human & JSON Formatting+ , formatSnapManifest+ , formatSnapManifestJson+ , formatSnapDiff+ , formatSnapDiffJson+ , formatSnapRewind+ , formatSnapRewindJson+ , formatSnapLog+ , formatSnapLogJson+ , formatSnapGC+ , formatSnapGCJson+ ) where++import Control.DeepSeq (NFData)+import Control.Exception (IOException, try)+import Control.Monad (forM, when)+import Data.Aeson (ToJSON (..), object, (.=))+import qualified Data.Aeson.Encode.Pretty as AesonPretty+import qualified Data.ByteString as BS+import qualified Data.ByteString.Lazy as LBS+import Data.List (sort)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import Data.Time.Clock (getCurrentTime)+import Data.Time.Format (defaultTimeLocale, formatTime)+import GHC.Clock (getMonotonicTimeNSec)+import GHC.Generics (Generic)+import System.Directory+ ( createDirectoryIfMissing+ , doesDirectoryExist+ , doesFileExist+ , getFileSize+ , listDirectory+ , removeFile+ )+import System.FilePath ((</>), takeDirectory, takeExtension)+import Text.Printf (printf)++import Canontra.Analysis.Impact (findMatchingTests)+import Canontra.Analysis.WholeRepoGraph (buildWholeRepoCallGraphFromSummaries)+import Canontra.Cache.Common (atomicSwapWithRetry_)+import Canontra.Cache.MerkleCache (defaultCachePath)+import Canontra.Cache.SlabV7 (SlabV7Entry (..), readAnySlabCacheForV7)+import Canontra.Comparison.Diff (DeclDiff (..), DiffResult (..), diffPrograms)+import Canontra.Fingerprint.Source (computeF0)+import Canontra.Harness.Store+import Canontra.IR.Program (Module (..), Program (..))+import Canontra.Normalize.Rules (snapSchemaVersion, snapStability)+import Canontra.Parser.Polyglot (parsePolyglotByteString)+import Canontra.Repository.Repository+ ( fingerprintDirectoryWithCache+ , normalizePathPosix+ )+import Canontra.Security.Path (canonicalizeSafePath)+import Canontra.Types+ ( FileEntry (..)+ , Fingerprint (..)+ , FingerprintBundle (..)+ , ParseError (..)+ , RepositoryManifest (..)+ , WholeRepoCallEdge (..)+ , WholeRepoCallGraph (..)+ , symFilePath+ )++-- | Symbol-level change extracted between two snapshots using 'diffPrograms'.+data SnapSymbolChange = SnapSymbolChange+ { sscFile :: !FilePath+ , sscAction :: !Text+ , sscSymbol :: !Text+ , sscDetail :: !Text+ } deriving stock (Eq, Ord, Show, Generic)+ deriving anyclass (NFData)++instance ToJSON SnapSymbolChange where+ toJSON s = object+ [ "file" .= sscFile s+ , "action" .= sscAction s+ , "symbol" .= sscSymbol s+ , "detail" .= sscDetail s+ ]++-- | Semantic delta report produced by @canontra snap diff@.+data SnapDiffReport = SnapDiffReport+ { sdrSchemaVersion :: !Text+ , sdrStability :: !Text+ , sdrFromSnap :: !Text+ , sdrToSnap :: !Text+ , sdrClassification :: !SnapClassification+ , sdrCompact :: !Bool+ , sdrLevel1Trivia :: ![SnapFileDelta]+ , sdrLevel2Logic :: ![SnapFileDelta]+ , sdrLevel3Contract :: ![SnapFileDelta]+ , sdrSymbolChanges :: ![SnapSymbolChange]+ , sdrRecommendedTests :: ![Text]+ , sdrElapsedMs :: !Double+ } deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++instance ToJSON SnapDiffReport where+ toJSON r = object+ [ "schema_version" .= sdrSchemaVersion r+ , "stability" .= sdrStability r+ , "from_snap" .= sdrFromSnap r+ , "to_snap" .= sdrToSnap r+ , "classification" .= sdrClassification r+ , "compact" .= sdrCompact r+ , "level1_trivia" .= if sdrCompact r then ([] :: [SnapFileDelta]) else sdrLevel1Trivia r+ , "level1_count" .= length (sdrLevel1Trivia r)+ , "level2_logic" .= sdrLevel2Logic r+ , "level3_contract" .= sdrLevel3Contract r+ , "symbol_changes" .= sdrSymbolChanges r+ , "recommended_tests" .= sdrRecommendedTests r+ , "elapsed_ms" .= sdrElapsedMs r+ ]++-- | Workspace restoration report emitted by @canontra snap rewind@.+data SnapRewindReport = SnapRewindReport+ { srrSchemaVersion :: !Text+ , srrStability :: !Text+ , srrTargetSnapId :: !Text+ , srrDryRun :: !Bool+ , srrRestoredFiles :: ![FilePath]+ , srrRemovedFiles :: ![FilePath]+ , srrUnchangedSkip :: !Int+ , srrElapsedMs :: !Double+ } deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++instance ToJSON SnapRewindReport where+ toJSON r = object+ [ "schema_version" .= srrSchemaVersion r+ , "stability" .= srrStability r+ , "target_snap_id" .= srrTargetSnapId r+ , "dry_run" .= srrDryRun r+ , "restored_files" .= srrRestoredFiles r+ , "removed_files" .= srrRemovedFiles r+ , "unchanged_files" .= srrUnchangedSkip r+ , "elapsed_ms" .= srrElapsedMs r+ ]++-- | Garbage collection report emitted by @canontra snap gc@.+data SnapGCReport = SnapGCReport+ { gcrSchemaVersion :: !Text+ , gcrStability :: !Text+ , gcrRetainedSnaps :: !Int+ , gcrPrunedSnaps :: !Int+ , gcrLiveBlobs :: !Int+ , gcrRemovedBlobs :: !Int+ , gcrReclaimedBytes :: !Integer+ } deriving stock (Eq, Show, Generic)+ deriving anyclass (NFData)++instance ToJSON SnapGCReport where+ toJSON r = object+ [ "schema_version" .= gcrSchemaVersion r+ , "stability" .= gcrStability r+ , "retained_snaps" .= gcrRetainedSnaps r+ , "pruned_snaps" .= gcrPrunedSnaps r+ , "live_blobs" .= gcrLiveBlobs r+ , "removed_blobs" .= gcrRemovedBlobs r+ , "reclaimed_bytes" .= gcrReclaimedBytes r+ ]++-- ============================================================================+-- 9-Tier Semantic Delta & Classification+-- ============================================================================++-- | Ordered list of all 9 Canontra fingerprint tier names.+allTierNames :: [Text]+allTierNames = ["F0", "F1", "F2", "F3", "F_CG", "F_CF", "F_DF", "F_T", "F4"]++-- | Compare two 'FingerprintBundle' values returning @(mutated, invariant, severity)@.+diffFileBundles :: FingerprintBundle -> FingerprintBundle -> ([Text], [Text], Text)+diffFileBundles bOld bNew =+ let checks =+ [ ("F0", f0Source bOld /= f0Source bNew)+ , ("F1", f1Structural bOld /= f1Structural bNew)+ , ("F2", f2Declaration bOld /= f2Declaration bNew)+ , ("F3", f3Dependency bOld /= f3Dependency bNew)+ , ("F_CG", fCGCallGraph bOld /= fCGCallGraph bNew)+ , ("F_CF", fCFControlFlow bOld /= fCFControlFlow bNew)+ , ("F_DF", fDFDataFlow bOld /= fDFDataFlow bNew)+ , ("F_T", fTTypeContract bOld /= fTTypeContract bNew)+ , ("F4", f4Composite bOld /= f4Composite bNew)+ ]+ mutated = [name | (name, True) <- checks]+ invariant = [name | (name, False) <- checks]+ hasContract = any (\t -> t == "F2" || t == "F3" || t == "F_T") mutated+ hasLogic = any (\t -> t == "F1" || t == "F_CG" || t == "F_CF" || t == "F_DF" || t == "F4") mutated+ severity+ | hasContract = "Level3_Contract"+ | hasLogic = "Level2_Logic"+ | otherwise = "Level1_Trivia"+ in (mutated, invariant, severity)++-- | Compute deterministic sorted per-file deltas between two snapshot maps.+computeFileDeltas+ :: Map FilePath SnapFileRecord+ -> Map FilePath SnapFileRecord+ -> [SnapFileDelta]+computeFileDeltas oldMap newMap =+ let allPaths = Set.toAscList (Set.union (Map.keysSet oldMap) (Map.keysSet newMap))+ in foldr step [] allPaths+ where+ step p acc = case (Map.lookup p oldMap, Map.lookup p newMap) of+ (Nothing, Just _) ->+ SnapFileDelta p "added" "Level3_Contract" allTierNames [] : acc+ (Just _, Nothing) ->+ SnapFileDelta p "deleted" "Level3_Contract" allTierNames [] : acc+ (Just rOld, Just rNew)+ | sfrF0 rOld == sfrF0 rNew && sfrBundle rOld == sfrBundle rNew -> acc+ | otherwise ->+ let (muts, invs, sev) = diffFileBundles (sfrBundle rOld) (sfrBundle rNew)+ in SnapFileDelta p "modified" sev muts invs : acc+ (Nothing, Nothing) -> acc++-- | Collapse per-file deltas into an overall snapshot classification.+classifySnapDeltas :: [SnapFileDelta] -> SnapClassification+classifySnapDeltas [] = SnapNoChange+classifySnapDeltas deltas+ | any (\d -> sfdSeverity d == "Level3_Contract") deltas = SnapContractChange+ | any (\d -> sfdSeverity d == "Level2_Logic") deltas = SnapInternalLogic+ | otherwise = SnapSemanticNoop++-- | Scan the workspace using the warm @CNTR\\x07@ slab cache and build normalized records.+scanWorkspaceRecords+ :: FilePath+ -> IO (Either String (RepositoryManifest, Map FilePath SnapFileRecord))+scanWorkspaceRecords repoDir = do+ res <- fingerprintDirectoryWithCache repoDir True+ case res of+ Left err -> pure (Left ("Parse error in " ++ peFile err ++ ": " ++ T.unpack (peReason err)))+ Right manifest -> do+ pairs <- forM (rmFiles manifest) $ \fe -> do+ let rel = normalizePathPosix (fePath fe)+ fullPath = repoDir </> rel+ eSz <- try (getFileSize fullPath) :: IO (Either IOException Integer)+ let sz = either (const 0) id eSz+ b = feFingerprints fe+ pure (rel, SnapFileRecord rel (unFingerprint (f0Source b)) sz b)+ pure (Right (manifest, Map.fromList pairs))++-- | Compute runnable test recommendations for a set of deltas using cached @CNTR\\x07@+-- summaries (for contract-level transitive expansion) + fast basename test matching.+recommendTestsForDeltas :: FilePath -> [FilePath] -> [SnapFileDelta] -> IO [Text]+recommendTestsForDeltas repoDir allFiles deltas = do+ let logicOrContract = [sfdPath d | d <- deltas, sfdSeverity d /= "Level1_Trivia"]+ contractPaths = [sfdPath d | d <- deltas, sfdSeverity d == "Level3_Contract"]+ if null logicOrContract+ then pure []+ else do+ expandedAffected <- if null contractPaths+ then pure logicOrContract+ else expandContractCallers repoDir logicOrContract contractPaths+ let rawTests = findMatchingTests expandedAffected allFiles+ pure $ Set.toAscList (Set.fromList (map toRunnableTestCommand rawTests))++expandContractCallers :: FilePath -> [FilePath] -> [FilePath] -> IO [FilePath]+expandContractCallers repoDir baseAffected contractPaths = do+ let cachePath = defaultCachePath repoDir+ exists <- doesFileExist cachePath+ if not exists+ then pure baseAffected+ else do+ eBytes <- try (BS.readFile cachePath) :: IO (Either IOException BS.ByteString)+ case eBytes of+ Left _ -> pure baseAffected+ Right bs -> case readAnySlabCacheForV7 bs of+ Just (entryMap, _) ->+ let summaries = [sm | e <- Map.elems entryMap, Just sm <- [sv7Summary e]]+ in if null summaries+ then pure baseAffected+ else+ let wcg = buildWholeRepoCallGraphFromSummaries summaries+ targetSet = Set.fromList (map normalizePathPosix contractPaths)+ callers =+ [ normalizePathPosix (symFilePath (wceCaller e))+ | e <- wcgEdges wcg+ , Set.member (normalizePathPosix (symFilePath (wceCallee e))) targetSet+ ]+ in pure (Set.toAscList (Set.fromList (baseAffected ++ callers)))+ Nothing -> pure baseAffected++-- | Format a discovered test path into an actionable runner invocation when unambiguous.+toRunnableTestCommand :: FilePath -> Text+toRunnableTestCommand fp =+ let norm = normalizePathPosix fp+ ext = map toLowerAscii (takeExtension norm)+ in case ext of+ ".py" -> "pytest " <> T.pack norm+ ".ts" -> "npx jest " <> T.pack norm+ ".tsx" -> "npx jest " <> T.pack norm+ ".js" -> "npx jest " <> T.pack norm+ ".jsx" -> "npx jest " <> T.pack norm+ ".go" ->+ let dir = takeDirectory norm+ in if dir == "." || null dir+ then "go test ./..."+ else "go test ./" <> T.pack dir+ ".rs" -> "cargo test"+ _ -> T.pack norm+ where+ toLowerAscii c+ | c >= 'A' && c <= 'Z' = toEnum (fromEnum c + 32)+ | otherwise = c++elapsedMsSince :: Integral a => a -> a -> Double+elapsedMsSince startNs endNs =+ fromIntegral (toInteger endNs - toInteger startNs) / 1000000.0++formatUtcTimestamp :: IO (Text, Text)+formatUtcTimestamp = do+ now <- getCurrentTime+ let isoTxt = T.pack (formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ" now)+ compactTxt = T.pack (formatTime defaultTimeLocale "%Y%m%dT%H%M%S%3qZ" now)+ pure (isoTxt, compactTxt)++makeLedgerEntry :: SnapManifest -> LedgerEntry+makeLedgerEntry m = LedgerEntry+ { leSnapId = smSnapId m+ , leParentId = smParentId m+ , leTimestamp = smTimestamp m+ , leLabel = smLabel m+ , leAgent = smAgent m+ , leClassification = smClassification m+ , leRepoFR = smRepoFR m+ , leFileCount = Map.size (smFiles m)+ , leChangedCount = length (smChangedFiles m)+ , leElapsedMs = smElapsedMs m+ }++-- ============================================================================+-- Sub-Versioning Operations+-- ============================================================================++-- | Initialize @.canontra/snaps/@ and capture baseline @snap_0@.+snapInit :: FilePath -> IO (Either String SnapManifest)+snapInit repoDir = do+ t0 <- getMonotonicTimeNSec+ ensureSnapStore repoDir+ eScan <- scanWorkspaceRecords repoDir+ case eScan of+ Left err -> pure (Left err)+ Right (repoMan, fileRecords) -> do+ _ <- storeChangedBlobs repoDir Map.empty fileRecords+ (isoTs, _) <- formatUtcTimestamp+ t1 <- getMonotonicTimeNSec+ let !elapsed = elapsedMsSince t0 t1+ manifest = SnapManifest+ { smSchemaVersion = snapSchemaVersion+ , smStability = snapStability+ , smSnapId = "snap_0"+ , smParentId = Nothing+ , smTimestamp = isoTs+ , smLabel = Just "baseline"+ , smAgent = Nothing+ , smClassification = SnapNoChange+ , smRepoFR = unFingerprint (rmRepositoryFingerprint repoMan)+ , smRepoFWCG = fmap unFingerprint (rmWholeRepoCallGraph repoMan)+ , smRepoFWDF = fmap unFingerprint (rmWholeRepoDataFlow repoMan)+ , smFiles = fileRecords+ , smChangedFiles = []+ , smRecommendedTests = []+ , smElapsedMs = elapsed+ }+ writeSnapManifest repoDir manifest+ writeHeadSnapId repoDir "snap_0"+ appendLedgerEntry repoDir (makeLedgerEntry manifest)+ pure (Right manifest)++-- | Capture an incremental checkpoint comparing against @HEAD@.+-- When @skipNoop@ is 'True' and classification is 'SnapNoChange', returns+-- @Right (parentManifest, True)@ without writing a new snapshot.+snapMark+ :: FilePath+ -> Maybe Text+ -> Maybe Text+ -> Bool+ -> IO (Either String (SnapManifest, Bool))+snapMark repoDir mLabel mAgent skipNoop = do+ t0 <- getMonotonicTimeNSec+ mHeadId <- readHeadSnapId repoDir+ case mHeadId of+ Nothing ->+ pure (Left "Snap store is not initialized in this workspace. Run 'canontra snap init' first.")+ Just parentId -> do+ eParent <- readSnapManifestDirect repoDir parentId+ case eParent of+ Left err -> pure (Left err)+ Right parentMan -> do+ eScan <- scanWorkspaceRecords repoDir+ case eScan of+ Left err -> pure (Left err)+ Right (repoMan, newRecords) -> do+ let deltas = computeFileDeltas (smFiles parentMan) newRecords+ classification = classifySnapDeltas deltas+ if skipNoop && classification == SnapNoChange+ then pure (Right (parentMan, True))+ else do+ ensureSnapStore repoDir+ _ <- storeChangedBlobs repoDir (smFiles parentMan) newRecords+ recTests <- recommendTestsForDeltas repoDir (Map.keys newRecords) deltas+ (isoTs, compactTs) <- formatUtcTimestamp+ let frHex = unFingerprint (rmRepositoryFingerprint repoMan)+ baseId = "snap_" <> compactTs <> "_" <> T.take 8 frHex+ snapId <- ensureUniqueSnapId repoDir baseId+ t1 <- getMonotonicTimeNSec+ let !elapsed = elapsedMsSince t0 t1+ manifest = SnapManifest+ { smSchemaVersion = snapSchemaVersion+ , smStability = snapStability+ , smSnapId = snapId+ , smParentId = Just parentId+ , smTimestamp = isoTs+ , smLabel = mLabel+ , smAgent = mAgent+ , smClassification = classification+ , smRepoFR = frHex+ , smRepoFWCG = fmap unFingerprint (rmWholeRepoCallGraph repoMan)+ , smRepoFWDF = fmap unFingerprint (rmWholeRepoDataFlow repoMan)+ , smFiles = newRecords+ , smChangedFiles = deltas+ , smRecommendedTests = recTests+ , smElapsedMs = elapsed+ }+ writeSnapManifest repoDir manifest+ writeHeadSnapId repoDir snapId+ appendLedgerEntry repoDir (makeLedgerEntry manifest)+ pure (Right (manifest, False))++ensureUniqueSnapId :: FilePath -> Text -> IO Text+ensureUniqueSnapId repoDir candidate = go (0 :: Int) candidate+ where+ go n cur = do+ exists <- doesFileExist (manifestFilePath repoDir cur)+ if not exists+ then pure cur+ else let nextN = n + 1+ in go nextN (candidate <> "_" <> T.pack (show nextN))++storeChangedBlobs+ :: FilePath+ -> Map FilePath SnapFileRecord+ -> Map FilePath SnapFileRecord+ -> IO Int+storeChangedBlobs repoDir oldMap newMap = do+ results <- forM (Map.toList newMap) $ \(relPath, rec) ->+ case Map.lookup relPath oldMap of+ Just oldRec | sfrF0 oldRec == sfrF0 rec -> do+ -- Ensure blob still exists even if hash matched+ case objectBlobPath repoDir (sfrF0 rec) of+ Just bp -> do+ exists <- doesFileExist bp+ if exists+ then pure 0+ else writeFromDisk relPath (sfrF0 rec)+ Nothing -> pure 0+ _ -> writeFromDisk relPath (sfrF0 rec)+ pure (sum results)+ where+ writeFromDisk relPath f0Hex = do+ let fullPath = repoDir </> relPath+ eBytes <- try (BS.readFile fullPath) :: IO (Either IOException BS.ByteString)+ case eBytes of+ Left _ -> pure 0+ Right raw -> do+ let actualF0 = unFingerprint (computeF0 raw)+ wrote <- storeBlobIfAbsent repoDir actualF0 raw+ when (actualF0 /= f0Hex) $+ storeBlobIfAbsent repoDir f0Hex raw >> pure ()+ pure (if wrote then 1 else 0)++-- | Compare two snapshots (or @WORKTREE@) returning partitioned semantic deltas,+-- symbol-level changes, and affected test commands.+snapDiff :: FilePath -> Text -> Text -> Bool -> IO (Either String SnapDiffReport)+snapDiff repoDir refA refB compact = do+ t0 <- getMonotonicTimeNSec+ eA <- loadSide refA+ case eA of+ Left err -> pure (Left err)+ Right (idA, mapA, isWorktreeA) -> do+ eB <- loadSide refB+ case eB of+ Left err -> pure (Left err)+ Right (idB, mapB, isWorktreeB) -> do+ let deltas = computeFileDeltas mapA mapB+ classification = classifySnapDeltas deltas+ l1 = [d | d <- deltas, sfdSeverity d == "Level1_Trivia"]+ l2 = [d | d <- deltas, sfdSeverity d == "Level2_Logic"]+ l3 = [d | d <- deltas, sfdSeverity d == "Level3_Contract"]+ allKnownFiles = Set.toAscList (Set.union (Map.keysSet mapA) (Map.keysSet mapB))+ recTests <- recommendTestsForDeltas repoDir allKnownFiles deltas+ symChanges <- extractSymbolChanges repoDir mapA mapB isWorktreeA isWorktreeB (l2 ++ l3)+ t1 <- getMonotonicTimeNSec+ pure $ Right SnapDiffReport+ { sdrSchemaVersion = snapSchemaVersion+ , sdrStability = snapStability+ , sdrFromSnap = idA+ , sdrToSnap = idB+ , sdrClassification = classification+ , sdrCompact = compact+ , sdrLevel1Trivia = l1+ , sdrLevel2Logic = l2+ , sdrLevel3Contract = l3+ , sdrSymbolChanges = symChanges+ , sdrRecommendedTests = recTests+ , sdrElapsedMs = elapsedMsSince t0 t1+ }+ where+ loadSide ref+ | ref == "WORKTREE" || ref == "worktree" = do+ eScan <- scanWorkspaceRecords repoDir+ pure (fmap (\(_, recs) -> ("WORKTREE", recs, True)) eScan)+ | otherwise = do+ eMan <- readSnapManifest repoDir ref+ pure (fmap (\m -> (smSnapId m, smFiles m, False)) eMan)++extractSymbolChanges+ :: FilePath+ -> Map FilePath SnapFileRecord+ -> Map FilePath SnapFileRecord+ -> Bool+ -> Bool+ -> [SnapFileDelta]+ -> IO [SnapSymbolChange]+extractSymbolChanges repoDir mapA mapB isWtA isWtB deltas = do+ nested <- forM deltas $ \d -> do+ let p = sfdPath d+ mOldProg <- loadSideProg isWtA (Map.lookup p mapA) p+ mNewProg <- loadSideProg isWtB (Map.lookup p mapB) p+ pure $ case (mOldProg, mNewProg) of+ (Just oldP, Just newP) ->+ [ SnapSymbolChange p (ddAction dd) (ddTarget dd) (ddDetails dd)+ | dd <- drDeclarationDiffs (diffPrograms oldP newP)+ ]+ (Nothing, Just newP) ->+ [ SnapSymbolChange p "added" (ddTarget dd) (ddDetails dd)+ | dd <- drDeclarationDiffs (diffPrograms (emptyProgLike newP) newP)+ ]+ (Just oldP, Nothing) ->+ [ SnapSymbolChange p "removed" (ddTarget dd) (ddDetails dd)+ | dd <- drDeclarationDiffs (diffPrograms oldP (emptyProgLike oldP))+ ]+ (Nothing, Nothing) -> []+ pure (concat nested)+ where+ emptyProgLike (Program _ lang) = Program [Module "" [] [] []] lang++ loadSideProg _ Nothing _ = pure Nothing+ loadSideProg isWt (Just rec) relPath = do+ eBytes <- if isWt+ then do+ eRaw <- try (BS.readFile (repoDir </> relPath)) :: IO (Either IOException BS.ByteString)+ pure (either (Left . show) Right eRaw)+ else readVerifiedBlob repoDir (sfrF0 rec)+ case eBytes of+ Left _ -> pure Nothing+ Right raw -> case parsePolyglotByteString relPath raw of+ Left _ -> pure Nothing+ Right prog -> pure (Just prog)++-- | Preflight-verified atomic rollback to a target snapshot.+-- Validates path containment for every restored/removed file and SHA-256 verifies+-- every blob BEFORE touching any file in the working tree. Never deletes+-- unrelated untracked files.+snapRewind+ :: FilePath+ -> Text+ -> [FilePath]+ -> Bool+ -> IO (Either String SnapRewindReport)+snapRewind repoDir ref filesFilter dryRun = do+ t0 <- getMonotonicTimeNSec+ eTarget <- readSnapManifest repoDir ref+ case eTarget of+ Left err -> pure (Left err)+ Right targetMan -> do+ let normFilter = Set.fromList (map normalizePathPosix filesFilter)+ requestedFiles =+ if null filesFilter+ then Map.toList (smFiles targetMan)+ else+ [ (p, r)+ | (p, r) <- Map.toList (smFiles targetMan)+ , Set.member p normFilter+ ]+ -- Verify explicitly requested files all exist in target snapshot+ let missingFromTarget =+ [ f+ | f <- Set.toList normFilter+ , Map.notMember f (smFiles targetMan)+ ]+ if not (null filesFilter) && not (null missingFromTarget)+ then pure (Left ("Requested file(s) not present in snapshot "+ ++ T.unpack (smSnapId targetMan) ++ ": " ++ unwords missingFromTarget))+ else do+ -- Identify tracked files from current HEAD that were created after target snap+ removeCandidates <- if not (null filesFilter)+ then pure []+ else do+ mHeadId <- readHeadSnapId repoDir+ case mHeadId of+ Nothing -> pure []+ Just headId -> do+ eHeadMan <- readSnapManifestDirect repoDir headId+ case eHeadMan of+ Left _ -> pure []+ Right headMan ->+ pure+ [ p+ | p <- Map.keys (smFiles headMan)+ , Map.notMember p (smFiles targetMan)+ ]++ -- Step 1 (Preflight): Validate paths + verify blobs before ANY mutation+ ePlan <- preflightRewind requestedFiles removeCandidates+ case ePlan of+ Left err -> pure (Left err)+ Right (toWrite, toDelete, skippedCount) -> do+ when (not dryRun) $ do+ pidStr <- getCurrentPidString+ forM_ toWrite $ \(_, safeAbsPath, rawBytes) -> do+ createDirectoryIfMissing True (takeDirectory safeAbsPath)+ let tmp = safeAbsPath ++ ".tmp." ++ pidStr+ BS.writeFile tmp rawBytes+ atomicSwapWithRetry_ tmp safeAbsPath+ forM_ toDelete $ \(_, safeAbsPath) -> do+ exists <- doesFileExist safeAbsPath+ when exists (removeFile safeAbsPath)+ when (null filesFilter) $+ writeHeadSnapId repoDir (smSnapId targetMan)++ t1 <- getMonotonicTimeNSec+ pure $ Right SnapRewindReport+ { srrSchemaVersion = snapSchemaVersion+ , srrStability = snapStability+ , srrTargetSnapId = smSnapId targetMan+ , srrDryRun = dryRun+ , srrRestoredFiles = sort [p | (p, _, _) <- toWrite]+ , srrRemovedFiles = sort [p | (p, _) <- toDelete]+ , srrUnchangedSkip = skippedCount+ , srrElapsedMs = elapsedMsSince t0 t1+ }+ where+ forM_ = flip mapM_++ validateTargetPath relPath+ | not (isSafeRelativeFilePath relPath) =+ pure (Left ("Security violation: unsafe relative path in snapshot: " ++ relPath))+ | otherwise = do+ let absCand = repoDir </> relPath+ -- Check existing parent containment + full candidate containment+ eSafe <- canonicalizeSafePath repoDir absCand+ case eSafe of+ Left secErr -> pure (Left secErr)+ Right safeCand -> do+ let pDir = takeDirectory absCand+ dirExists <- doesDirectoryExist pDir+ if dirExists+ then do+ eSafeDir <- canonicalizeSafePath repoDir pDir+ case eSafeDir of+ Left secErr -> pure (Left secErr)+ Right _ -> pure (Right safeCand)+ else pure (Right safeCand)++ preflightRewind writeItems deleteItems = do+ wRes <- goWrites [] 0 writeItems+ case wRes of+ Left err -> pure (Left err)+ Right (writes, skips) -> do+ dRes <- goDeletes [] deleteItems+ case dRes of+ Left err -> pure (Left err)+ Right dels -> pure (Right (writes, dels, skips))++ goWrites acc !skips [] = pure (Right (reverse acc, skips))+ goWrites acc !skips ((relPath, rec) : rest) = do+ ePath <- validateTargetPath relPath+ case ePath of+ Left err -> pure (Left err)+ Right safeAbs -> do+ eBlob <- readVerifiedBlob repoDir (sfrF0 rec)+ case eBlob of+ Left err -> pure (Left err)+ Right rawBytes -> do+ onDisk <- try (BS.readFile safeAbs) :: IO (Either IOException BS.ByteString)+ let unchanged = case onDisk of+ Right cur -> T.toLower (unFingerprint (computeF0 cur)) == T.toLower (sfrF0 rec)+ Left _ -> False+ if unchanged+ then goWrites acc (skips + 1) rest+ else goWrites ((relPath, safeAbs, rawBytes) : acc) skips rest++ goDeletes acc [] = pure (Right (reverse acc))+ goDeletes acc (relPath : rest) = do+ ePath <- validateTargetPath relPath+ case ePath of+ Left err -> pure (Left err)+ Right safeAbs -> goDeletes ((relPath, safeAbs) : acc) rest++-- | Read snapshot ledger history (most recent first, bounded to @limit@).+snapLog :: FilePath -> Int -> IO (Either String (Maybe Text, [LedgerEntry]))+snapLog repoDir limitCount = do+ mHead <- readHeadSnapId repoDir+ entries <- readLedgerEntries repoDir+ let capped = if limitCount <= 0 then entries else take limitCount (reverse entries)+ pure (Right (mHead, capped))++-- | Garbage-collect manifests beyond the last @keepLast@ snapshots (always retaining+-- @HEAD@ and @snap_0@) and sweep unreferenced @F0@ blobs under @objects/@.+snapGC :: FilePath -> Int -> IO (Either String SnapGCReport)+snapGC repoDir keepLast = do+ mHead <- readHeadSnapId repoDir+ ledger <- readLedgerEntries repoDir+ allIds <- listAllManifestIds repoDir+ let recentIds = take (max 1 keepLast) (reverse (map leSnapId ledger))+ protected = Set.fromList ("snap_0" : maybe [] pure mHead ++ recentIds)+ pruneIds = filter (`Set.notMember` protected) allIds+ keepIds = filter (`Set.member` protected) allIds+ mapM_ (removeManifestFile repoDir) pruneIds++ -- Collect live F0 hashes from retained manifests+ liveF0Lists <- forM keepIds $ \sid -> do+ eMan <- readSnapManifestDirect repoDir sid+ case eMan of+ Left _ -> pure []+ Right m -> pure [T.toLower (sfrF0 r) | r <- Map.elems (smFiles m)]+ let liveSet = Set.fromList (concat liveF0Lists)++ -- Walk 2-char object fanout buckets+ let oDir = objectsDir repoDir+ eBuckets <- try (listDirectory oDir) :: IO (Either IOException [FilePath])+ (removedCnt, reclaimed) <- case eBuckets of+ Left _ -> pure (0, 0)+ Right buckets -> do+ counts <- forM buckets $ \bucket -> do+ let bPath = oDir </> bucket+ isDir <- doesDirectoryExist bPath+ if not isDir || length bucket /= 2+ then pure (0, 0)+ else do+ eObjs <- try (listDirectory bPath) :: IO (Either IOException [FilePath])+ case eObjs of+ Left _ -> pure (0, 0)+ Right objs -> foldMObjects bPath bucket liveSet objs+ pure (sum (map fst counts), sum (map snd counts))++ pure $ Right SnapGCReport+ { gcrSchemaVersion = snapSchemaVersion+ , gcrStability = snapStability+ , gcrRetainedSnaps = length keepIds+ , gcrPrunedSnaps = length pruneIds+ , gcrLiveBlobs = Set.size liveSet+ , gcrRemovedBlobs = removedCnt+ , gcrReclaimedBytes = reclaimed+ }+ where+ foldMObjects bPath bucket liveSet objs = do+ res <- forM objs $ \objFile -> do+ let hexKey = T.pack (bucket ++ objFile)+ fullObj = bPath </> objFile+ if Set.member (T.toLower hexKey) liveSet+ then pure (0, 0)+ else do+ eSz <- try (getFileSize fullObj) :: IO (Either IOException Integer)+ _ <- try (removeFile fullObj) :: IO (Either IOException ())+ pure (1, either (const 0) id eSz)+ pure (sum (map fst res), sum (map snd res))++-- ============================================================================+-- Human & JSON Formatters+-- ============================================================================++formatDurationMs :: Double -> String+formatDurationMs ms = printf "%.2f ms" ms++formatSnapManifest :: Bool -> SnapManifest -> Text+formatSnapManifest skipped m =+ T.unlines $+ [ "================================================================================"+ , " CANONTRA SNAP — SEMANTIC SUB-VERSIONING (" <> T.toUpper snapStability <> ")"+ , "================================================================================"+ , " Snap ID: " <> smSnapId m <> if skipped then " (unchanged — skipped new node)" else ""+ , " Parent ID: " <> maybe "null (baseline)" id (smParentId m)+ , " Timestamp: " <> smTimestamp m+ , " Classification: " <> classificationText (smClassification m)+ , " Repo Hash (F_R): " <> smRepoFR m+ , " Tracked Files: " <> T.pack (show (Map.size (smFiles m)))+ , " Changed Files: " <> T.pack (show (length (smChangedFiles m)))+ , " Latency: " <> T.pack (formatDurationMs (smElapsedMs m))+ ]+ ++ maybe [] (\l -> [" Label: " <> l]) (smLabel m)+ ++ maybe [] (\a -> [" Agent: " <> a]) (smAgent m)+ ++ (if null (smChangedFiles m)+ then []+ else+ [ "--------------------------------------------------------------------------------"+ , " Changed Files:"+ ] +++ [ " [" <> sfdSeverity d <> "] " <> T.pack (sfdPath d)+ <> " (" <> sfdStatus d <> "; mutated: " <> T.intercalate "," (sfdMutatedTiers d) <> ")"+ | d <- smChangedFiles m+ ])+ ++ (if null (smRecommendedTests m)+ then []+ else+ [ "--------------------------------------------------------------------------------"+ , " Recommended Tests:"+ ] ++ [" " <> t | t <- smRecommendedTests m])+ ++ [ "================================================================================" ]++formatSnapManifestJson :: SnapManifest -> LBS.ByteString+formatSnapManifestJson = AesonPretty.encodePretty++formatSnapDiff :: Bool -> SnapDiffReport -> Text+formatSnapDiff compact r =+ T.unlines $+ [ "================================================================================"+ , " CANONTRA SNAP DIFF (" <> T.toUpper snapStability <> ")"+ , "================================================================================"+ , " From Snap: " <> sdrFromSnap r+ , " To Snap: " <> sdrToSnap r+ , " Classification: " <> classificationText (sdrClassification r)+ , " Level 3 Contract: " <> T.pack (show (length (sdrLevel3Contract r))) <> " files"+ , " Level 2 Logic: " <> T.pack (show (length (sdrLevel2Logic r))) <> " files"+ , " Level 1 Trivia: " <> T.pack (show (length (sdrLevel1Trivia r))) <> " files"+ <> if compact then " (omitted in compact mode)" else ""+ , " Latency: " <> T.pack (formatDurationMs (sdrElapsedMs r))+ ]+ ++ renderSection "Level 3 (Contract / Dependency):" (sdrLevel3Contract r)+ ++ renderSection "Level 2 (Internal Logic):" (sdrLevel2Logic r)+ ++ (if compact then [] else renderSection "Level 1 (Formatting / Semantic No-op):" (sdrLevel1Trivia r))+ ++ (if null (sdrSymbolChanges r)+ then []+ else+ [ "--------------------------------------------------------------------------------"+ , " Symbol Changes:"+ ] +++ [ " [" <> sscAction s <> "] " <> T.pack (sscFile s) <> "::" <> sscSymbol s <> " — " <> sscDetail s+ | s <- sdrSymbolChanges r+ ])+ ++ (if null (sdrRecommendedTests r)+ then []+ else+ [ "--------------------------------------------------------------------------------"+ , " Recommended Tests:"+ ] ++ [" " <> t | t <- sdrRecommendedTests r])+ ++ [ "================================================================================" ]+ where+ renderSection _ [] = []+ renderSection title xs =+ [ "--------------------------------------------------------------------------------"+ , " " <> title+ ] +++ [ " " <> T.pack (sfdPath d) <> " (" <> sfdStatus d <> ": " <> T.intercalate "," (sfdMutatedTiers d) <> ")"+ | d <- xs+ ]++formatSnapDiffJson :: Bool -> SnapDiffReport -> LBS.ByteString+formatSnapDiffJson _ = AesonPretty.encodePretty++formatSnapRewind :: SnapRewindReport -> Text+formatSnapRewind r =+ T.unlines $+ [ "================================================================================"+ , " CANONTRA SNAP REWIND" <> if srrDryRun r then " (DRY RUN)" else ""+ , "================================================================================"+ , " Target Snap ID: " <> srrTargetSnapId r+ , " Restored Files: " <> T.pack (show (length (srrRestoredFiles r)))+ , " Removed Files: " <> T.pack (show (length (srrRemovedFiles r)))+ , " Unchanged Skipped: " <> T.pack (show (srrUnchangedSkip r))+ , " Latency: " <> T.pack (formatDurationMs (srrElapsedMs r))+ ]+ ++ (if null (srrRestoredFiles r)+ then []+ else "--------------------------------------------------------------------------------"+ : [" Restored: " <> T.pack p | p <- srrRestoredFiles r])+ ++ (if null (srrRemovedFiles r)+ then []+ else "--------------------------------------------------------------------------------"+ : [" Removed: " <> T.pack p | p <- srrRemovedFiles r])+ ++ [ "================================================================================" ]++formatSnapRewindJson :: SnapRewindReport -> LBS.ByteString+formatSnapRewindJson = AesonPretty.encodePretty++formatSnapLog :: Maybe Text -> [LedgerEntry] -> Text+formatSnapLog mHead entries =+ T.unlines $+ [ "================================================================================"+ , " CANONTRA SNAP LEDGER (" <> T.toUpper snapStability <> ")"+ , "================================================================================"+ , " Active HEAD: " <> maybe "(none)" id mHead+ , " Entries Shown: " <> T.pack (show (length entries))+ , "--------------------------------------------------------------------------------"+ ]+ +++ [ " " <> (if Just (leSnapId e) == mHead then "* " else " ")+ <> leSnapId e+ <> " [" <> classificationText (leClassification e) <> "]"+ <> " files=" <> T.pack (show (leFileCount e))+ <> " changed=" <> T.pack (show (leChangedCount e))+ <> maybe "" (\l -> " label=" <> l) (leLabel e)+ <> maybe "" (\a -> " agent=" <> a) (leAgent e)+ | e <- entries+ ]+ ++ [ "================================================================================" ]++formatSnapLogJson :: Maybe Text -> [LedgerEntry] -> LBS.ByteString+formatSnapLogJson mHead entries =+ AesonPretty.encodePretty $ object+ [ "schema_version" .= snapSchemaVersion+ , "stability" .= snapStability+ , "head" .= mHead+ , "entries" .= entries+ ]++formatSnapGC :: SnapGCReport -> Text+formatSnapGC r =+ T.unlines+ [ "================================================================================"+ , " CANONTRA SNAP GARBAGE COLLECTION"+ , "================================================================================"+ , " Retained Snaps: " <> T.pack (show (gcrRetainedSnaps r))+ , " Pruned Snaps: " <> T.pack (show (gcrPrunedSnaps r))+ , " Live Blobs: " <> T.pack (show (gcrLiveBlobs r))+ , " Removed Blobs: " <> T.pack (show (gcrRemovedBlobs r))+ , " Reclaimed Bytes: " <> T.pack (show (gcrReclaimedBytes r))+ , "================================================================================"+ ]++formatSnapGCJson :: SnapGCReport -> LBS.ByteString+formatSnapGCJson = AesonPretty.encodePretty
src/Canontra/Normalize/Algebraic.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-}@@ -20,6 +21,8 @@ , normalizeBinaryExpr , normalizeCollectionLiteral , isProvablyPureExpr+ , isNonTrappingPureExpr+ , containsFloatOperand , isCommutativeOp , hashExprB ) where@@ -56,14 +59,24 @@ -- | Compute a deterministic 64-bit FNV-1a hash of an 'Expr' for canonical ordering. hashExprB :: Expr -> Word64-hashExprB = fnv1aHash64 . canonicalizeExpr- where- fnv1aHash64 :: BS.ByteString -> Word64- fnv1aHash64 =- BS.foldl'- (\h b -> (h `xor` fromIntegral b) * 1099511628211)- 14695981039346656037+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@@ -83,6 +96,31 @@ 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@@ -249,89 +287,132 @@ 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 = \case- ExprLit lit -> ExprLit lit- ExprId ident -> ExprId ident+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' = normalizeAlgebraicExpr lhs- rhs' = normalizeAlgebraicExpr rhs- in normalizeBinaryExpr 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' = normalizeAlgebraicExpr operand- in case (op, op') of- (OpNot, ExprUnary OpNot inner) -> inner- _ -> ExprUnary op op'+ 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 ->- ExprCall- (normalizeAlgebraicExpr callee)- (map normalizeAlgebraicExpr args)- [(k, normalizeAlgebraicExpr v) | (k, v) <- 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)+ (ExprLambda params (normalizeAlgebraicExpr body), False) ExprTernary cond thenE elseE ->- ExprTernary- (normalizeAlgebraicExpr cond)- (normalizeAlgebraicExpr thenE)- (normalizeAlgebraicExpr elseE)+ let !(c', pC) = normalizeAlgebraicExprWithPurity cond+ !(t', pT) = normalizeAlgebraicExprWithPurity thenE+ !(e', pE) = normalizeAlgebraicExprWithPurity elseE+ in (ExprTernary c' t' e', pC && pT && pE) ExprList items ->- ExprList (map normalizeAlgebraicExpr items)+ let !normed = map normalizeAlgebraicExprWithPurity items+ in (ExprList (map fst normed), all snd normed) ExprTuple items ->- ExprTuple (map normalizeAlgebraicExpr items)+ let !normed = map normalizeAlgebraicExprWithPurity items+ in (ExprTuple (map fst normed), all snd normed) ExprSet items ->- normalizeCollectionLiteral (ExprSet (map normalizeAlgebraicExpr 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 ->- normalizeCollectionLiteral- (ExprDict [(normalizeAlgebraicExpr k, normalizeAlgebraicExpr v) | (k, v) <- 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)+ (ExprListComp (normalizeAlgebraicExpr elt) (map normalizeComp comps), False) ExprSetComp elt comps ->- ExprSetComp (normalizeAlgebraicExpr elt) (map normalizeComp comps)+ (ExprSetComp (normalizeAlgebraicExpr elt) (map normalizeComp comps), False) ExprGenerator elt comps ->- ExprGenerator (normalizeAlgebraicExpr elt) (map normalizeComp comps)+ (ExprGenerator (normalizeAlgebraicExpr elt) (map normalizeComp comps), False) ExprDictComp kExpr vExpr comps ->- ExprDictComp- (normalizeAlgebraicExpr kExpr)- (normalizeAlgebraicExpr vExpr)- (map normalizeComp comps)+ ( ExprDictComp+ (normalizeAlgebraicExpr kExpr)+ (normalizeAlgebraicExpr vExpr)+ (map normalizeComp comps)+ , False+ ) ExprAttr obj attr ->- ExprAttr (normalizeAlgebraicExpr obj) attr+ let !(obj', pO) = normalizeAlgebraicExprWithPurity obj+ in (ExprAttr obj' attr, pO) ExprOptChain obj attr ->- ExprOptChain (normalizeAlgebraicExpr obj) attr+ let !(obj', pO) = normalizeAlgebraicExprWithPurity obj+ in (ExprOptChain obj' attr, pO) ExprNullish lhs rhs ->- ExprNullish (normalizeAlgebraicExpr lhs) (normalizeAlgebraicExpr rhs)+ let !(lhs', pL) = normalizeAlgebraicExprWithPurity lhs+ !(rhs', pR) = normalizeAlgebraicExprWithPurity rhs+ in (ExprNullish lhs' rhs', pL && pR) ExprSubscript obj idx ->- ExprSubscript (normalizeAlgebraicExpr obj) (normalizeAlgebraicExpr 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)+ ( ExprSlice+ (fmap normalizeAlgebraicExpr mLower)+ (fmap normalizeAlgebraicExpr mUpper)+ (fmap normalizeAlgebraicExpr mStep)+ , False+ ) ExprAwait operand ->- ExprAwait (normalizeAlgebraicExpr operand)+ (ExprAwait (normalizeAlgebraicExpr operand), False) ExprYield mOperand ->- ExprYield (fmap normalizeAlgebraicExpr mOperand)+ (ExprYield (fmap normalizeAlgebraicExpr mOperand), False) ExprYieldFrom operand ->- ExprYieldFrom (normalizeAlgebraicExpr operand)+ (ExprYieldFrom (normalizeAlgebraicExpr operand), False) ExprStarred operand ->- ExprStarred (normalizeAlgebraicExpr operand)+ (ExprStarred (normalizeAlgebraicExpr operand), False) ExprKwStarred operand ->- ExprKwStarred (normalizeAlgebraicExpr operand)+ (ExprKwStarred (normalizeAlgebraicExpr operand), False) ExprWalrus name val ->- ExprWalrus name (normalizeAlgebraicExpr val)+ (ExprWalrus name (normalizeAlgebraicExpr val), False) ExprFormattedString parts ->- ExprFormattedString (map normalizeFPart parts)+ (ExprFormattedString (map normalizeFPart parts), False) ExprChanRecv ch ->- ExprChanRecv (normalizeAlgebraicExpr ch)+ (ExprChanRecv (normalizeAlgebraicExpr ch), False) ExprTryOp operand ->- ExprTryOp (normalizeAlgebraicExpr operand)+ (ExprTryOp (normalizeAlgebraicExpr operand), False) ExprJSX tag attrs children ->- ExprJSX- tag- [(k, normalizeAlgebraicExpr v) | (k, v) <- attrs]- (map normalizeAlgebraicExpr children)+ ( ExprJSX+ tag+ [(k, normalizeAlgebraicExpr v) | (k, v) <- attrs]+ (map normalizeAlgebraicExpr children)+ , False+ ) ExprMacroCall name args ->- ExprMacroCall name (map normalizeAlgebraicExpr args)+ (ExprMacroCall name (map normalizeAlgebraicExpr args), False) where normalizeComp (CompFor tgt iter ifs) = CompFor@@ -342,64 +423,92 @@ 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 = case op of+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- | isProvablyPureExpr e1 && isProvablyPureExpr e2 ->- ExprBinary OpLt e2 e1- | otherwise ->- ExprBinary OpGt e1 e2+ | p1 && p2 -> ExprBinary OpLt e2 e1+ | otherwise -> ExprBinary OpGt e1 e2 OpGtE- | isProvablyPureExpr e1 && isProvablyPureExpr e2 ->- ExprBinary OpLtE e2 e1- | otherwise ->- ExprBinary OpGtE e1 e2+ | p1 && p2 -> ExprBinary OpLtE e2 e1+ | otherwise -> ExprBinary OpGtE e1 e2 _- | isAssociativeCommutativeOp op && canCommute op 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 = sortBy (comparing hashExprB) terms+ sortedTerms = sortBySchwartzian terms in case sortedTerms of (t:ts) -> foldl (ExprBinary op) t ts [] -> ExprBinary op e1 e2- | isCommutativeOp op && canCommute op e1 e2 ->- if hashExprB e1 <= hashExprB 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 b =- isProvablyPureExpr a- && isProvablyPureExpr b- && not (isConcatenationOperand a)- && not (isConcatenationOperand b)- canCommute _ a b =- isProvablyPureExpr a && isProvablyPureExpr b+ 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 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 when all elements are pure.+-- 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 (sortBy (comparing hashExprB) items)+ ExprSet (sortBySchwartzian items) | otherwise -> ExprSet items ExprDict pairs | all (\(k, v) -> isProvablyPureExpr k && isProvablyPureExpr v) pairs ->- ExprDict (sortBy (comparing (\(k, v) -> (hashExprB k, hashExprB 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
src/Canontra/Normalize/Alpha.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-}@@ -18,9 +19,12 @@ module Canontra.Normalize.Alpha ( AlphaEnv (..) , emptyAlphaEnv+ , emptyAlphaEnvForLang , canonicalizeAlphaProgram , canonicalizeAlphaModule+ , canonicalizeAlphaModuleForLang , canonicalizeFunctionLocals+ , canonicalizeFunctionLocalsForLang , canonicalizeStmtAlpha , canonicalizeExprAlpha , isCanonicalBoundId@@ -64,27 +68,37 @@ -- | Lexical scoping environment for de Bruijn alpha-canonicalization. data AlphaEnv = AlphaEnv- { aeDepth :: !Int+ { aeDepth :: !Int -- ^ Current lexical nesting depth (0 = module, 1 = function body, >=2 = nested blocks).- , aeOrd :: !Int+ , aeOrd :: !Int -- ^ Monotonic binder ordinal within the current lexical depth.- , aeBindings :: !(Map Text Text)+ , aeBindings :: !(Map Text Text) -- ^ Active mapping from source variable name to canonical @v<depth>.<ord>.- , aeGlobals :: !(Set Text)+ , aeBindingDepths :: !(Map Text Int)+ -- ^ Depth at which each active source variable was bound (for block-scoped shadowing).+ , aeGlobals :: !(Set Text) -- ^ Protected global, imported, parameter, and receiver symbols (never renamed).- , aeDepthOrds :: !(Map Int Int)+ , aeDepthOrds :: !(Map Int Int) -- ^ Per-depth monotonic ordinal watermark within a function to prevent cross-block collisions.+ , aeLanguage :: !Text+ -- ^ Source language identifier enabling language-accurate scoping (Rust/Go/JS/Python). } deriving stock (Eq, Show) -- | Construct an initial 'AlphaEnv' with the given protected global symbol set. emptyAlphaEnv :: Set Text -> AlphaEnv-emptyAlphaEnv globals = AlphaEnv- { aeDepth = 1- , aeOrd = 0- , aeBindings = Map.empty- , aeGlobals = Set.union builtinProtected globals- , aeDepthOrds = Map.empty+emptyAlphaEnv = emptyAlphaEnvForLang ""++-- | Construct a language-aware initial 'AlphaEnv'.+emptyAlphaEnvForLang :: Text -> Set Text -> AlphaEnv+emptyAlphaEnvForLang lang globals = AlphaEnv+ { aeDepth = 1+ , aeOrd = 0+ , aeBindings = Map.empty+ , aeBindingDepths = Map.empty+ , aeGlobals = Set.union builtinProtected globals+ , aeDepthOrds = Map.empty+ , aeLanguage = T.toLower lang } builtinProtected :: Set Text@@ -108,15 +122,19 @@ -- | Apply scope-aware bound lexical alpha-canonicalization across an entire 'Program'. canonicalizeAlphaProgram :: Program -> Program canonicalizeAlphaProgram (Program modules lang) =- Program (map canonicalizeAlphaModule modules) lang+ Program (map (canonicalizeAlphaModuleForLang lang) modules) lang -- | Apply scope-aware bound lexical alpha-canonicalization across a 'Module'. -- Top-level module statements and module-level exported symbols are preserved; -- bound local variables inside function and method bodies are canonicalized. canonicalizeAlphaModule :: Module -> Module-canonicalizeAlphaModule (Module name imps decls stmts) =+canonicalizeAlphaModule = canonicalizeAlphaModuleForLang ""++-- | Language-aware 'canonicalizeAlphaModule'.+canonicalizeAlphaModuleForLang :: Text -> Module -> Module+canonicalizeAlphaModuleForLang lang (Module name imps decls stmts) = let modGlobals = collectModuleGlobals imps decls stmts- decls' = map (canonicalizeDeclAlpha modGlobals) decls+ decls' = map (canonicalizeDeclAlpha lang modGlobals) decls in Module name imps decls' stmts collectModuleGlobals :: [ImportDecl] -> [Declaration] -> [Stmt] -> Set Text@@ -170,40 +188,44 @@ StmtAnnAssign target _ _ -> extractTargetNames target _ -> [] -canonicalizeDeclAlpha :: Set Text -> Declaration -> Declaration-canonicalizeDeclAlpha modGlobals = \case+canonicalizeDeclAlpha :: Text -> Set Text -> Declaration -> Declaration+canonicalizeDeclAlpha lang modGlobals = \case DeclFunction fn ->- DeclFunction (canonicalizeFunctionLocals modGlobals fn)+ DeclFunction (canonicalizeFunctionLocalsForLang lang modGlobals fn) DeclClass cls -> let clsGlobals = Set.insert (clsName cls) modGlobals in DeclClass cls- { clsMethods = map (canonicalizeFunctionLocals clsGlobals) (clsMethods cls)+ { clsMethods = map (canonicalizeFunctionLocalsForLang lang clsGlobals) (clsMethods cls) } DeclStruct st -> let stGlobals = Set.insert (stName st) modGlobals in DeclStruct st- { stMethods = map (canonicalizeFunctionLocals stGlobals) (stMethods st)+ { stMethods = map (canonicalizeFunctionLocalsForLang lang stGlobals) (stMethods st) } DeclTrait tr -> let trGlobals = Set.insert (trName tr) modGlobals in DeclTrait tr- { trMethods = map (canonicalizeFunctionLocals trGlobals) (trMethods tr)+ { trMethods = map (canonicalizeFunctionLocalsForLang lang trGlobals) (trMethods tr) } DeclImpl imp -> let impGlobals = Set.insert (impTarget imp) modGlobals in DeclImpl imp- { impMethods = map (canonicalizeFunctionLocals impGlobals) (impMethods imp)+ { impMethods = map (canonicalizeFunctionLocalsForLang lang impGlobals) (impMethods imp) } DeclReceiver rc fn -> let rcGlobals = Set.fromList (filter (not . T.null) [rcVarName rc, rcTypeName rc]) `Set.union` modGlobals- in DeclReceiver rc (canonicalizeFunctionLocals rcGlobals fn)+ in DeclReceiver rc (canonicalizeFunctionLocalsForLang lang rcGlobals fn) other -> other -- | Canonicalize all bound local variables inside a 'Function' declaration -- while preserving its public signature (function name and parameter names). canonicalizeFunctionLocals :: Set Text -> Function -> Function-canonicalizeFunctionLocals outerGlobals fn =+canonicalizeFunctionLocals = canonicalizeFunctionLocalsForLang ""++-- | Language-aware local alpha-canonicalization inside a 'Function'.+canonicalizeFunctionLocalsForLang :: Text -> Set Text -> Function -> Function+canonicalizeFunctionLocalsForLang lang outerGlobals fn = let paramNames = concatMap extractParamNames (fnParams fn) explicitGlobals = collectExplicitGlobals (fnBody fn) fnGlobals = Set.unions@@ -212,7 +234,7 @@ , Set.fromList paramNames , explicitGlobals ]- env0 = emptyAlphaEnv fnGlobals+ env0 = emptyAlphaEnvForLang lang fnGlobals (body', _) = canonicalizeStmts env0 (fnBody fn) in fn { fnBody = body' } @@ -270,6 +292,35 @@ let o = Map.findWithDefault 0 d (aeDepthOrds env) in env { aeDepth = d, aeOrd = o } +isBlockScopedLanguage :: AlphaEnv -> Bool+isBlockScopedLanguage env =+ let lang = aeLanguage env+ in lang == "rust" || lang == "go" || lang == "javascript" || lang == "typescript"++type SavedScopeState = (Map Text Text, Map Text Int)++captureBlockScope :: AlphaEnv -> SavedScopeState+captureBlockScope env = (aeBindings env, aeBindingDepths env)++-- | Restore lexical bindings when exiting a block in block-scoped languages,+-- while preserving function-hoisted bindings (e.g. JS @var@ at depth 1) and+-- monotonic depth ordinals ('aeDepthOrds') to prevent cross-block ID collisions.+restoreBlockScope :: Int -> SavedScopeState -> AlphaEnv -> AlphaEnv+restoreBlockScope savedDepth (savedBindings, savedBDepths) env+ | not (isBlockScopedLanguage env) = restoreDepth savedDepth env+ | aeLanguage env == "javascript" || aeLanguage env == "typescript" =+ let hoistedBindings = Map.filterWithKey (\k _ -> Map.lookup k (aeBindingDepths env) == Just 1) (aeBindings env)+ hoistedDepths = Map.filter (== 1) (aeBindingDepths env)+ in restoreDepth savedDepth env+ { aeBindings = Map.union hoistedBindings savedBindings+ , aeBindingDepths = Map.union hoistedDepths savedBDepths+ }+ | otherwise =+ restoreDepth savedDepth env+ { aeBindings = savedBindings+ , aeBindingDepths = savedBDepths+ }+ -- | Bind a local variable in the current scope if not already bound or protected. bindLocal :: Text -> AlphaEnv -> (Text, AlphaEnv) bindLocal ident env@@ -278,13 +329,22 @@ | otherwise = allocateFresh ident env -- | Force-allocate a fresh binder at the current lexical depth (used for loop--- targets, comprehension induction variables, lambda parameters, and exception aliases)--- unless the identifier is protected in 'aeGlobals'.+-- targets, comprehension induction variables, lambda parameters, exception aliases,+-- and Rust sequential @let@ shadowing) unless the identifier is protected in 'aeGlobals'. bindFreshLocal :: Text -> AlphaEnv -> (Text, AlphaEnv) bindFreshLocal ident env | T.null ident || Set.member ident (aeGlobals env) = (ident, env) | otherwise = allocateFresh ident env +-- | Bind in the current lexical frame: reuses an existing binding ONLY if it was bound+-- at the exact current depth ('aeDepth'); if bound in an enclosing block, shadows it cleanly.+bindInCurrentFrame :: Text -> AlphaEnv -> (Text, AlphaEnv)+bindInCurrentFrame ident env+ | T.null ident || Set.member ident (aeGlobals env) = (ident, env)+ | Map.lookup ident (aeBindingDepths env) == Just (aeDepth env)+ , Just existing <- Map.lookup ident (aeBindings env) = (existing, env)+ | otherwise = allocateFresh ident env+ allocateFresh :: Text -> AlphaEnv -> (Text, AlphaEnv) allocateFresh ident env = let d = aeDepth env@@ -292,9 +352,10 @@ canon = "@v" <> T.pack (show d) <> "." <> T.pack (show o) nextOrd = o + 1 env' = env- { aeOrd = nextOrd- , aeBindings = Map.insert ident canon (aeBindings env)- , aeDepthOrds = Map.insert d nextOrd (aeDepthOrds env)+ { aeOrd = nextOrd+ , aeBindings = Map.insert ident canon (aeBindings env)+ , aeBindingDepths = Map.insert ident d (aeBindingDepths env)+ , aeDepthOrds = Map.insert d nextOrd (aeDepthOrds env) } in (canon, env') @@ -313,22 +374,19 @@ ExprWalrus v _ -> [v] _ -> [] -bindTargetExpr :: Bool -> AlphaEnv -> Expr -> (Expr, AlphaEnv)-bindTargetExpr forceFresh env = \case+bindTargetExprWith :: (Text -> AlphaEnv -> (Text, AlphaEnv)) -> AlphaEnv -> Expr -> (Expr, AlphaEnv)+bindTargetExprWith binderFn env = \case ExprId name ->- let (name', env') =- if forceFresh- then bindFreshLocal name env- else bindLocal name env+ let (name', env') = binderFn name env in (ExprId name', env') ExprTuple es ->- let (es', env') = mapAccumAlpha (bindTargetExpr forceFresh) env es+ let (es', env') = mapAccumAlpha (bindTargetExprWith binderFn) env es in (ExprTuple es', env') ExprList es ->- let (es', env') = mapAccumAlpha (bindTargetExpr forceFresh) env es+ let (es', env') = mapAccumAlpha (bindTargetExprWith binderFn) env es in (ExprList es', env') ExprStarred e ->- let (e', env') = bindTargetExpr forceFresh env e+ let (e', env') = bindTargetExprWith binderFn env e in (ExprStarred e', env') ExprAttr obj attr -> let (obj', env') = canonicalizeExprWithEnv env obj@@ -340,6 +398,10 @@ other -> canonicalizeExprWithEnv env other +bindTargetExpr :: Bool -> AlphaEnv -> Expr -> (Expr, AlphaEnv)+bindTargetExpr forceFresh =+ bindTargetExprWith (\name env -> if forceFresh then bindFreshLocal name env else bindLocal name env)+ mapAccumAlpha :: (AlphaEnv -> a -> (b, AlphaEnv)) -> AlphaEnv -> [a] -> ([b], AlphaEnv) mapAccumAlpha _ env [] = ([], env) mapAccumAlpha f env (x:xs) =@@ -347,14 +409,13 @@ (ys, env2) = mapAccumAlpha f env1 xs in (y : ys, env2) --- ------------------------------------------------------------------------------ Statement Alpha-Canonicalization--- ------------------------------------------------------------------------------- | Canonicalize a single 'Stmt' under the given 'AlphaEnv'.+-- | Statement-level alpha-canonicalization respecting language scoping rules.+-- Supports Rust @let@ sequential shadowing, Go @:=@ frame-local binding,+-- JS/TS @var@ hoisting vs @let@/@const@ block scope, and Python LEGB. canonicalizeStmtAlpha :: AlphaEnv -> Stmt -> (Stmt, AlphaEnv) canonicalizeStmtAlpha env stmt = let d0 = aeDepth env+ saved = captureBlockScope env in case stmt of StmtAssign targets val -> let (val', env1) = canonicalizeExprWithEnv env val@@ -368,7 +429,24 @@ StmtAnnAssign target ann mVal -> let (mVal', env1) = canonicalizeMaybeExpr env mVal- (target', env2) = bindTargetExpr False env1 target+ lang = aeLanguage env1+ (target', env2) = case (lang, ann) of+ ("rust", ExprId "let") ->+ -- Rust sequential let-shadowing: evaluate RHS under prior bindings, then allocate fresh slot+ bindTargetExprWith bindFreshLocal env1 target+ ("go", ExprId ":=") ->+ -- Go short var decl: reuse if in current frame, fresh if shadowing outer scope+ bindTargetExprWith bindInCurrentFrame env1 target+ (js, ExprId "var") | js == "javascript" || js == "typescript" ->+ -- JS var hoists to enclosing function scope (depth 1)+ let !dSaved = aeDepth env1+ !envFn = restoreDepth 1 env1+ !(t', envFn') = bindTargetExprWith bindInCurrentFrame envFn target+ in (t', restoreDepth dSaved envFn')+ (js, ExprId declKw) | (js == "javascript" || js == "typescript") && (declKw == "let" || declKw == "const") ->+ bindTargetExprWith bindInCurrentFrame env1 target+ _ ->+ bindTargetExpr False env1 target in (StmtAnnAssign target' ann mVal', env2) StmtReturn mExpr ->@@ -381,50 +459,58 @@ StmtIf cond thenB elseB -> let (cond', env1) = canonicalizeExprWithEnv env cond+ !savedAfterCond = captureBlockScope env1 (thenB', env2) = canonicalizeStmts (enterDepth env1) thenB- (elseB', env3) = canonicalizeStmts env2 elseB- in (StmtIf cond' thenB' elseB', restoreDepth d0 env3)+ !envForElse = restoreBlockScope (d0 + 1) savedAfterCond env2+ (elseB', env3) = canonicalizeStmts envForElse elseB+ in (StmtIf cond' thenB' elseB', restoreBlockScope d0 savedAfterCond env3) StmtWhile cond body elseB -> let (cond', env1) = canonicalizeExprWithEnv env cond+ !savedAfterCond = captureBlockScope env1 (body', env2) = canonicalizeStmts (enterDepth env1) body- (elseB', env3) = canonicalizeStmts env2 elseB- in (StmtWhile cond' body' elseB', restoreDepth d0 env3)+ !envForElse = restoreBlockScope (d0 + 1) savedAfterCond env2+ (elseB', env3) = canonicalizeStmts envForElse elseB+ in (StmtWhile cond' body' elseB', restoreBlockScope d0 savedAfterCond env3) StmtFor target iter body elseB -> let (iter', env1) = canonicalizeExprWithEnv env iter+ !savedBeforeLoop = captureBlockScope env1 envLoop0 = enterDepth env1 (target', envLoop1) = bindTargetExpr True envLoop0 target (body', envLoop2) = canonicalizeStmts envLoop1 body- (elseB', envLoop3) = canonicalizeStmts envLoop2 elseB- in (StmtFor target' iter' body' elseB', restoreDepth d0 envLoop3)+ !envForElse = restoreBlockScope (d0 + 1) savedBeforeLoop envLoop2+ (elseB', envLoop3) = canonicalizeStmts envForElse elseB+ in (StmtFor target' iter' body' elseB', restoreBlockScope d0 savedBeforeLoop envLoop3) StmtAsyncFor target iter body elseB -> let (iter', env1) = canonicalizeExprWithEnv env iter+ !savedBeforeLoop = captureBlockScope env1 envLoop0 = enterDepth env1 (target', envLoop1) = bindTargetExpr True envLoop0 target (body', envLoop2) = canonicalizeStmts envLoop1 body- (elseB', envLoop3) = canonicalizeStmts envLoop2 elseB- in (StmtAsyncFor target' iter' body' elseB', restoreDepth d0 envLoop3)+ !envForElse = restoreBlockScope (d0 + 1) savedBeforeLoop envLoop2+ (elseB', envLoop3) = canonicalizeStmts envForElse elseB+ in (StmtAsyncFor target' iter' body' elseB', restoreBlockScope d0 savedBeforeLoop envLoop3) StmtWith items body -> let envW0 = enterDepth env (items', envW1) = mapAccumAlpha canonicalizeWithItem envW0 items (body', envW2) = canonicalizeStmts envW1 body- in (StmtWith items' body', restoreDepth d0 envW2)+ in (StmtWith items' body', restoreBlockScope d0 saved envW2) StmtAsyncWith items body -> let envW0 = enterDepth env (items', envW1) = mapAccumAlpha canonicalizeWithItem envW0 items (body', envW2) = canonicalizeStmts envW1 body- in (StmtAsyncWith items' body', restoreDepth d0 envW2)+ in (StmtAsyncWith items' body', restoreBlockScope d0 saved envW2) StmtTry tryB handlers elseB finB -> let (tryB', env1) = canonicalizeStmts (enterDepth env) tryB (handlers', env2) = mapAccumAlpha canonicalizeHandler env1 handlers (elseB', env3) = canonicalizeStmts env2 elseB (finB', env4) = canonicalizeStmts env3 finB- in (StmtTry tryB' handlers' elseB' finB', restoreDepth d0 env4)+ in (StmtTry tryB' handlers' elseB' finB', restoreBlockScope d0 saved env4) StmtRaise mExc mCause -> let (mExc', env1) = canonicalizeMaybeExpr env mExc@@ -442,19 +528,21 @@ StmtMatch subject cases -> let (subject', env1) = canonicalizeExprWithEnv env subject+ !savedBeforeMatch = captureBlockScope env1 (cases', env2) = mapAccumAlpha canonicalizeMatchCase (enterDepth env1) cases- in (StmtMatch subject' cases', restoreDepth d0 env2)+ in (StmtMatch subject' cases', restoreBlockScope d0 savedBeforeMatch env2) StmtSwitch subject cases defStmts -> let (subject', env1) = canonicalizeExprWithEnv env subject+ !savedBeforeSwitch = captureBlockScope env1 envS0 = enterDepth env1 (cases', envS1) = mapAccumAlpha canonicalizeSwitchCase envS0 cases (defStmts', envS2) = canonicalizeStmts envS1 defStmts- in (StmtSwitch subject' cases' defStmts', restoreDepth d0 envS2)+ in (StmtSwitch subject' cases' defStmts', restoreBlockScope d0 savedBeforeSwitch envS2) StmtSelect clauses -> let (clauses', env1) = mapAccumAlpha canonicalizeSelectClause (enterDepth env) clauses- in (StmtSelect clauses', restoreDepth d0 env1)+ in (StmtSelect clauses', restoreBlockScope d0 saved env1) StmtChanSend ch val -> let (ch', env1) = canonicalizeExprWithEnv env ch@@ -471,7 +559,7 @@ StmtLoop body -> let (body', env1) = canonicalizeStmts (enterDepth env) body- in (StmtLoop body', restoreDepth d0 env1)+ in (StmtLoop body', restoreBlockScope d0 saved env1) other -> (other, env)
src/Canontra/Normalize/Normalize.hs view
@@ -1,14 +1,19 @@+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-} {- | Module : Canontra.Normalize.Normalize-Description : Polyglot AST normalization pass v3.+Description : Polyglot AST normalization pass v4. -Normalizer v3 strips away multi-scope docstrings, comments, redundant passes,+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.+and execution control flow. Provides 'CanonicalProgram' for single-pass+pipeline fusion across all fingerprint tiers. -} module Canontra.Normalize.Normalize- ( normalizeProgram+ ( CanonicalProgram (..)+ , toCanonicalProgram+ , normalizeProgram , normalizeModule , normalizeDeclaration , normalizeModuleDeclarations@@ -24,6 +29,7 @@ , stripLeadingDocstring ) where +import Control.DeepSeq (NFData) import Data.List (partition, sort, sortBy) import Data.Ord (comparing) import Data.Text (Text)@@ -35,21 +41,36 @@ import Canontra.IR.Expression import Canontra.IR.Program import Canontra.Normalize.Algebraic (normalizeAlgebraicExpr, normalizeAlgebraicModule)-import Canontra.Normalize.Alpha (canonicalizeAlphaModule)+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 normalizeModule modules+ let normModules = map (normalizeModuleForLang lang) modules in Program (sortBy (comparing modName) normModules) lang normalizeModule :: Module -> Module-normalizeModule (Module _ imps decls stmts) =+normalizeModule = normalizeModuleForLang ""++normalizeModuleForLang :: Text -> Module -> Module+normalizeModuleForLang lang (Module _ imps decls stmts) = let normImps = sort (map normalizeImport imps)- normDecls = normalizeModuleDeclarations decls+ normDecls = normalizeModuleDeclarationsCore decls strippedStmts = stripLeadingDocstring stmts- normStmts = cleanStmtSuite (map normalizeStmt strippedStmts)+ normStmts = cleanStmtSuite (map normalizeStmtCore strippedStmts) in normalizeAlgebraicModule- . canonicalizeAlphaModule+ . canonicalizeAlphaModuleForLang lang . normalizeBranchModule $ Module "" normImps normDecls normStmts @@ -78,10 +99,16 @@ -- | Normalize module declarations: pure declarations are canonically sorted; -- stateful or decorated declarations preserve source execution order. normalizeModuleDeclarations :: [Declaration] -> [Declaration]-normalizeModuleDeclarations decls =+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 normalizeDeclaration pureDecls)- normStateful = map normalizeDeclaration statefulDecls+ sortedPure = sortBy (comparing declIdentifier) (map normDecl pureDecls)+ normStateful = map normDecl statefulDecls in sortedPure ++ normStateful normalizeImport :: ImportDecl -> ImportDecl@@ -91,30 +118,38 @@ ImportFrom modName ImportAll -> ImportFrom modName ImportAll normalizeDeclaration :: Declaration -> Declaration-normalizeDeclaration decl = case decl of- DeclFunction fn -> DeclFunction (normalizeFunction fn)- DeclClass (Class name bases methods decs) ->- let classPreserve = preservesDocstrings decs- normMethods = map (normalizeClassFunction 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 normalizeFunction methods- in DeclStruct (Struct name normFields normMethods vis)- DeclInterface (Interface name methods bases) ->- let normMethods = map normalizeFunction methods- in DeclInterface (Interface name normMethods (sort bases))- DeclReceiver rc fn ->- DeclReceiver rc (normalizeFunction fn)- DeclTrait (Trait name methods supers) ->- let normMethods = map normalizeFunction methods- in DeclTrait (Trait name normMethods (sort supers))- DeclImpl (Impl mTr tgt methods) ->- let normMethods = map normalizeFunction 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)+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 =@@ -130,16 +165,16 @@ any (\d -> d `elem` ["@preserve_docstring", "@reflect", "@doc", "preserve_docstring", "reflect", "doc"]) decs normalizeFunction :: Function -> Function-normalizeFunction = normalizeClassFunction False+normalizeFunction = normalizeClassFunctionWith normalizeStmt False -normalizeClassFunction :: Bool -> Function -> Function-normalizeClassFunction classPreserve (Function name params retType decs body isAsync) =+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 normalizeStmt strippedBody)+ normBody = cleanStmtSuiteWithPreserve preserve (map normSt strippedBody) in Function name normParams normRetType normDecs normBody isAsync normalizeParam :: Parameter -> Parameter@@ -147,117 +182,125 @@ Parameter name kind (fmap T.strip defVal) (fmap T.strip mType) normalizeStmt :: Stmt -> Stmt-normalizeStmt stmt = case stmt of+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 normalizeExpr targets) (normalizeExpr expr)+ StmtAssign (map normE targets) (normE expr) StmtAnnAssign target ty maybeVal ->- StmtAnnAssign (normalizeExpr target) (normalizeExpr ty) (fmap normalizeExpr maybeVal)+ StmtAnnAssign (normE target) (normE ty) (fmap normE maybeVal) StmtAugAssign target op expr ->- StmtAugAssign (normalizeExpr target) op (normalizeExpr expr)+ StmtAugAssign (normE target) op (normE expr) StmtExpr expr ->- StmtExpr (normalizeExpr expr)+ StmtExpr (normE expr) StmtReturn maybeExpr ->- StmtReturn (fmap normalizeExpr maybeExpr)+ StmtReturn (fmap normE maybeExpr) StmtIf cond body elseSuite ->- StmtIf (normalizeExpr cond) (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring body))) (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring elseSuite)))+ StmtIf (normE cond) (cleanStmtSuite (map normSt (stripLeadingDocstring body))) (cleanStmtSuite (map normSt (stripLeadingDocstring elseSuite))) StmtWhile cond body elseSuite ->- StmtWhile (normalizeExpr cond) (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring body))) (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring elseSuite)))+ StmtWhile (normE cond) (cleanStmtSuite (map normSt (stripLeadingDocstring body))) (cleanStmtSuite (map normSt (stripLeadingDocstring elseSuite))) StmtFor target iter body elseSuite ->- StmtFor (normalizeExpr target) (normalizeExpr iter) (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring body))) (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring elseSuite)))+ StmtFor (normE target) (normE iter) (cleanStmtSuite (map normSt (stripLeadingDocstring body))) (cleanStmtSuite (map normSt (stripLeadingDocstring elseSuite))) StmtAsyncFor target iter body elseSuite ->- StmtAsyncFor (normalizeExpr target) (normalizeExpr iter) (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring body))) (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring 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 normalizeExpr clause, alias, cleanStmtSuite (map normalizeStmt (stripLeadingDocstring hBody)))) handlers- in StmtTry (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring body))) normHandlers (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring elseSuite))) (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring finalSuite)))+ (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) -> (normalizeExpr e, fmap normalizeExpr a)) items) (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring body)))+ StmtWith (map (\(e, a) -> (normE e, fmap normE a)) items) (cleanStmtSuite (map normSt (stripLeadingDocstring body))) StmtAsyncWith items body ->- StmtAsyncWith (map (\(e, a) -> (normalizeExpr e, fmap normalizeExpr a)) items) (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring body)))+ StmtAsyncWith (map (\(e, a) -> (normE e, fmap normE a)) items) (cleanStmtSuite (map normSt (stripLeadingDocstring body))) StmtAssert expr maybeMsg ->- StmtAssert (normalizeExpr expr) (fmap normalizeExpr maybeMsg)+ StmtAssert (normE expr) (fmap normE maybeMsg) StmtRaise maybeExpr maybeCause ->- StmtRaise (fmap normalizeExpr maybeExpr) (fmap normalizeExpr maybeCause)+ StmtRaise (fmap normE maybeExpr) (fmap normE maybeCause) StmtBreak -> StmtBreak StmtContinue -> StmtContinue StmtPass -> StmtPass- StmtDelete exprs -> StmtDelete (map normalizeExpr exprs)+ StmtDelete exprs -> StmtDelete (map normE exprs) StmtGlobal vars -> StmtGlobal (sort vars) StmtNonlocal vars -> StmtNonlocal (sort vars) StmtMatch expr cases ->- StmtMatch (normalizeExpr expr) (map normalizeMatchCase cases)+ StmtMatch (normE expr) (map normMatchCase cases) StmtGo expr ->- StmtGo (normalizeExpr expr)+ StmtGo (normE expr) StmtDefer expr ->- StmtDefer (normalizeExpr expr)+ StmtDefer (normE expr) StmtChanSend ch val ->- StmtChanSend (normalizeExpr ch) (normalizeExpr val)+ StmtChanSend (normE ch) (normE val) StmtSelect cases ->- StmtSelect (map (\(sc, b) -> (normalizeSelectCase sc, cleanStmtSuite (map normalizeStmt (stripLeadingDocstring b)))) cases)+ StmtSelect (map (\(sc, b) -> (normSelectCase sc, cleanStmtSuite (map normSt (stripLeadingDocstring b)))) cases) StmtLoop body ->- StmtLoop (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring body)))+ StmtLoop (cleanStmtSuite (map normSt (stripLeadingDocstring body))) StmtSwitch expr cases defStmts ->- StmtSwitch (normalizeExpr expr)- (map (\(c, b) -> (normalizeExpr c, cleanStmtSuite (map normalizeStmt (stripLeadingDocstring b)))) cases)- (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring defStmts)))--normalizeSelectCase :: SelectCase -> SelectCase-normalizeSelectCase = \case- SelectSend ch val -> SelectSend (normalizeExpr ch) (normalizeExpr val)- SelectRecv mV ch -> SelectRecv mV (normalizeExpr ch)- SelectDefault -> SelectDefault--normalizeMatchCase :: MatchCase -> MatchCase-normalizeMatchCase (MatchCase pat guard body) =- MatchCase (normalizeExpr pat) (fmap normalizeExpr guard) (cleanStmtSuite (map normalizeStmt (stripLeadingDocstring body)))+ 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 expr = normalizeAlgebraicExpr $ case expr of+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 (normalizeExpr e1) (normalizeExpr e2)- ExprUnary op e -> ExprUnary op (normalizeExpr e)+ ExprBinary op e1 e2 -> ExprBinary op (normalizeExprCore e1) (normalizeExprCore e2)+ ExprUnary op e -> ExprUnary op (normalizeExprCore e) ExprCall target args kwArgs ->- let normArgs = map normalizeExpr args- normKwArgs = sortBy (comparing fst) (map (\(k, v) -> (k, normalizeExpr v)) kwArgs)- in ExprCall (normalizeExpr target) normArgs normKwArgs- ExprAttr target attr -> ExprAttr (normalizeExpr target) attr- ExprSubscript target idx -> ExprSubscript (normalizeExpr target) (normalizeExpr idx)- ExprSlice ms me mst -> ExprSlice (fmap normalizeExpr ms) (fmap normalizeExpr me) (fmap normalizeExpr mst)- ExprList items -> ExprList (map normalizeExpr items)- ExprTuple items -> ExprTuple (map normalizeExpr items)- ExprDict items -> ExprDict (map (\(k, v) -> (normalizeExpr k, normalizeExpr v)) items)- ExprSet items -> ExprSet (map normalizeExpr items)- ExprLambda params body -> ExprLambda (map normalizeParam params) (normalizeExpr body)- ExprTernary cond trueExpr falseExpr -> ExprTernary (normalizeExpr cond) (normalizeExpr trueExpr) (normalizeExpr falseExpr)- ExprListComp item comps -> ExprListComp (normalizeExpr item) (map normalizeComp comps)- ExprDictComp k v comps -> ExprDictComp (normalizeExpr k) (normalizeExpr v) (map normalizeComp comps)- ExprSetComp item comps -> ExprSetComp (normalizeExpr item) (map normalizeComp comps)- ExprGenerator item comps -> ExprGenerator (normalizeExpr item) (map normalizeComp comps)- ExprWalrus name val -> ExprWalrus name (normalizeExpr val)- ExprAwait e -> ExprAwait (normalizeExpr e)- ExprYield me -> ExprYield (fmap normalizeExpr me)- ExprYieldFrom e -> ExprYieldFrom (normalizeExpr e)- ExprFormattedString parts -> ExprFormattedString (map normalizeFStringPart parts)- ExprStarred e -> ExprStarred (normalizeExpr e)- ExprKwStarred e -> ExprKwStarred (normalizeExpr e)- ExprOptChain e prop -> ExprOptChain (normalizeExpr e) prop- ExprNullish e1 e2 -> ExprNullish (normalizeExpr e1) (normalizeExpr e2)- ExprChanRecv ch -> ExprChanRecv (normalizeExpr ch)- ExprTryOp e -> ExprTryOp (normalizeExpr e)- ExprMacroCall name args -> ExprMacroCall name (map normalizeExpr args)+ 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, normalizeExpr v)) attrs)- normChildren = map normalizeExpr children+ let normAttrs = sortBy (comparing fst) (map (\(k, v) -> (k, normalizeExprCore v)) attrs)+ normChildren = map normalizeExprCore children in ExprJSX tagElem normAttrs normChildren -normalizeFStringPart :: FStringPart -> FStringPart-normalizeFStringPart = \case+normalizeFStringPartCore :: FStringPart -> FStringPart+normalizeFStringPartCore = \case FStringText t -> FStringText t- FStringExpr e conv fmt -> FStringExpr (normalizeExpr e) conv fmt+ FStringExpr e conv fmt -> FStringExpr (normalizeExprCore e) conv fmt -normalizeComp :: CompFor -> CompFor-normalizeComp (CompFor target iter ifs) = CompFor (normalizeExpr target) (normalizeExpr iter) (map normalizeExpr ifs)+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]
src/Canontra/Normalize/Rules.hs view
@@ -2,13 +2,16 @@ Module : Canontra.Normalize.Rules Description : Version constants and AST normalization rewrite rules. -Contains core normalization definitions for canontra v0.0.4-alpha,-including docstring identification predicates and semantic transformation rules.+Contains core normalization definitions for canontra v0.4.0,+including docstring identification predicates, harness schema versions,+and semantic transformation rules. -} module Canontra.Normalize.Rules ( engineVersion , engineName , normalizationVersion+ , snapSchemaVersion+ , snapStability , isDocstring ) where @@ -17,13 +20,21 @@ import Canontra.IR.Expression engineVersion :: Text-engineVersion = "0.3.0"+engineVersion = "0.4.0" normalizationVersion :: Text-normalizationVersion = "0.3.0"+normalizationVersion = "0.4.0" engineName :: Text engineName = "canontra"++-- | Schema version emitted by the stateless @canontra snap@ AI harness subsystem.+snapSchemaVersion :: Text+snapSchemaVersion = "0.1-alpha"++-- | Stability tier identifier for @canontra snap@.+snapStability :: Text+snapStability = "alpha" isDocstring :: Stmt -> Bool isDocstring (StmtExpr (ExprLit (LitString _))) = True
src/Canontra/Parser/FastPython.hs view
@@ -20,6 +20,7 @@ ( parseFastPythonSource , parseFastPythonByteString , parseFastPythonToArena+ , tokenizeFastPythonBS -- * Legacy v0.0.7 Register Indentation Stack (Backwards-Compatible) , IndentStack (..) , emptyIndentStack@@ -36,20 +37,33 @@ , hybridIndentToList -- * Lexical Column Collation , advanceColumn+ , advanceColumnW8 ) where import Control.DeepSeq (NFData) import Data.Bits ((.&.), (.|.), complement, shiftL, shiftR) import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Lazy as BL+import qualified Data.ByteString.Unsafe as BSU+import Data.Char (digitToInt)+import Data.Set (Set)+import qualified Data.Set as Set import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Data.Text.Read as TR import qualified Data.Vector.Unboxed as U import Data.Word (Word64, Word8) import GHC.Generics (Generic) -import Canontra.Canonical.FastScan (fastCanonicalizeBS, fastCanonicalizeText)+import Canontra.Canonical.FastScan (ScanResult (..))+import Canontra.Canonical.SIMDScan (scanSourceSIMD)+import Canontra.Canonical.Unicode (canonicalizeText) import Canontra.IR.Arena (LinearAST, programToLinearAST)+import Canontra.IR.Expression (Expr (..), FStringPart (..)) import Canontra.IR.Program (Program (..))-import Canontra.Parser.Python (parsePythonSource)+import Canontra.Parser.Python (LocatedToken (..), PyToken (..), parsePythonTokens) import Canontra.Types (ParseError (..)) -- ============================================================================@@ -200,21 +214,529 @@ advanceColumn !col '\t' = ((col `div` 8) + 1) * 8 advanceColumn !col _ = col + 1 +-- | Advance visual column for raw byte streams according to PEP 8 modulo-8 tab stops.+{-# INLINE advanceColumnW8 #-}+advanceColumnW8 :: Int -> Word8 -> Int+advanceColumnW8 !col 0x09 = ((col `quot` 8) + 1) * 8+advanceColumnW8 !col _ = col + 1+ -- ============================================================================+-- ByteString-Native SIMD + HybridIndentStack Python Lexer+-- ============================================================================++{-# INLINE sliceText #-}+sliceText :: BS.ByteString -> Int -> Int -> Text+sliceText bs start n = TE.decodeUtf8Lenient (BS.take n (BS.drop start bs))++{-# INLINE isSpaceNoNLW8 #-}+isSpaceNoNLW8 :: Word8 -> Bool+isSpaceNoNLW8 w = w == 0x20 || w == 0x09++{-# INLINE isDigitW8 #-}+isDigitW8 :: Word8 -> Bool+isDigitW8 w = w >= 0x30 && w <= 0x39++{-# INLINE isHexW8 #-}+isHexW8 :: Word8 -> Bool+isHexW8 w =+ isDigitW8 w || (w >= 0x61 && w <= 0x66) || (w >= 0x41 && w <= 0x46)++{-# INLINE isOctW8 #-}+isOctW8 :: Word8 -> Bool+isOctW8 w = w >= 0x30 && w <= 0x37++{-# INLINE isIdentStartW8 #-}+isIdentStartW8 :: Word8 -> Bool+isIdentStartW8 w =+ (w >= 0x61 && w <= 0x7A)+ || (w >= 0x41 && w <= 0x5A)+ || w == 0x5F+ || w >= 0x80++{-# INLINE isIdentContW8 #-}+isIdentContW8 :: Word8 -> Bool+isIdentContW8 w = isIdentStartW8 w || isDigitW8 w++{-# INLINE isSinglePunctW8 #-}+isSinglePunctW8 :: Word8 -> Bool+isSinglePunctW8 w = case w of+ 0x3A -> True -- :+ 0x2C -> True -- ,+ 0x3B -> True -- ;+ 0x2E -> True -- .+ 0x7E -> True -- ~+ 0x40 -> True -- @+ 0x60 -> True -- `+ 0x2B -> True -- ++ 0x2D -> True -- -+ 0x2A -> True -- *+ 0x2F -> True -- /+ 0x25 -> True -- %+ 0x5E -> True -- ^+ 0x26 -> True -- &+ 0x7C -> True -- |+ 0x3C -> True -- <+ 0x3E -> True -- >+ 0x3D -> True -- =+ 0x21 -> True -- !+ _ -> False++pyKeywordSet :: Set Text+pyKeywordSet = Set.fromList+ [ "False", "None", "True", "and", "as", "assert", "async", "await"+ , "break", "class", "continue", "def", "del", "elif", "else", "except"+ , "finally", "for", "from", "global", "if", "import", "in", "is"+ , "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try"+ , "while", "with", "yield"+ ]++data FastLexCtx = FLCtxExpr !Int | FLCtxQuote !BS.ByteString !Bool++-- | Tokenize raw Python UTF-8/ASCII ByteString directly into '[LocatedToken]' using+-- 256-bit SIMD classification, 'memchr' newline finding, zero-copy slices, and 'HybridIndentStack'.+tokenizeFastPythonBS :: BS.ByteString -> Either (Int, Int, String) [LocatedToken]+tokenizeFastPythonBS rawBytes =+ let !initStack = pushHybridIndent 0 emptyHybridIndentStack+ in case processOffset 0 1 initStack 0 True 0 [] of+ Left err -> Left err+ Right revToks -> Right (reverse revToks)+ where+ !bs = case scanSourceSIMD rawBytes of+ PureAsciiUnix -> rawBytes+ ContainsCRLF -> BS.filter (/= 0x0D) rawBytes+ RequiresUnicodeNFC -> TE.encodeUtf8 (canonicalizeText (TE.decodeUtf8Lenient rawBytes))+ !len = BS.length bs++ {-# INLINE at #-}+ at !i = BSU.unsafeIndex bs i++ processOffset :: Int -> Int -> HybridIndentStack -> Int -> Bool -> Int -> [LocatedToken] -> Either (Int, Int, String) [LocatedToken]+ processOffset !i !lNum !stack !pDepth !atLineStart !colStart !acc+ | i >= len =+ let !depth = hybridIndentDepth stack+ !dedents = replicate (max 0 (depth - 1)) (LocatedToken TokDedent 1 1)+ in Right (LocatedToken TokEOF 1 1 : dedents ++ acc)+ | atLineStart =+ let !(nonSpaceIdx, indentW) = scanLeadingIndent i colStart+ in if nonSpaceIdx >= len+ then processOffset len lNum stack pDepth False 0 acc+ else+ let !w = at nonSpaceIdx+ in if w == 0x0A+ then processOffset (nonSpaceIdx + 1) (lNum + 1) stack pDepth True 0 acc+ else if w == 0x23 -- '#' comment line+ then+ let !nextNL = findNewline nonSpaceIdx+ in processOffset nextNL (lNum + 1) stack pDepth True 0 acc+ else if isBlankLineContinuation nonSpaceIdx+ then+ let !nextNL = findNewline nonSpaceIdx+ in processOffset nextNL (lNum + 1) stack pDepth True 0 acc+ else+ let !(newStack, indentRev) =+ if pDepth == 0+ then handleHybridIndent lNum (fromIntegral (min 255 indentW)) stack+ else (stack, [])+ !acc0 = indentRev ++ acc+ in lexLineTokens nonSpaceIdx lNum (indentW + 1) newStack pDepth acc0 False+ | otherwise =+ lexLineTokens i lNum (colStart + 1) stack pDepth acc False++ scanLeadingIndent !k !wCol+ | k >= len = (k, wCol)+ | otherwise =+ let !b = at k+ in if b == 0x20 || b == 0x09+ then scanLeadingIndent (k + 1) (advanceColumnW8 wCol b)+ else (k, wCol)++ isBlankLineContinuation !k = k < len && at k == 0x5C && isOnlySpacesBeforeNL (k + 1)++ isOnlySpacesBeforeNL !k+ | k >= len = True+ | at k == 0x0A = True+ | isSpaceNoNLW8 (at k) = isOnlySpacesBeforeNL (k + 1)+ | otherwise = False++ findNewline !k =+ case BS.elemIndex 0x0A (BS.drop k bs) of+ Just off -> k + off + 1+ Nothing -> len++ handleHybridIndent !lNum !curW !st =+ let !top = currentHybridIndent st+ in if curW > top+ then (pushHybridIndent curW st, [LocatedToken TokIndent lNum 1])+ else if curW < top+ then popLoop curW st []+ else (st, [])+ where+ popLoop !target !curSt !revDedents+ | currentHybridIndent curSt > target =+ case popHybridIndent curSt of+ Just (_, st') -> popLoop target st' (LocatedToken TokDedent lNum 1 : revDedents)+ Nothing -> (curSt, revDedents)+ | otherwise = (curSt, revDedents)++ lexLineTokens !i !lNum !col !stack !pDepth !acc !hadTokens+ | i >= len =+ let !acc' = if pDepth == 0 && hadTokens+ then LocatedToken TokNewline lNum col : acc+ else acc+ in processOffset len lNum stack pDepth False 0 acc'+ | otherwise =+ let !w = at i+ in case w of+ 0x0A -> -- '\n'+ let !acc' = if pDepth == 0 && hadTokens+ then LocatedToken TokNewline lNum col : acc+ else acc+ in processOffset (i + 1) (lNum + 1) stack pDepth True 0 acc'+ 0x20 -> lexLineTokens (i + 1) lNum (col + 1) stack pDepth acc hadTokens+ 0x09 -> lexLineTokens (i + 1) lNum (advanceColumnW8 col 0x09) stack pDepth acc hadTokens+ 0x23 -> -- '#' comment+ let !nextPos = findNewline (i + 1)+ !acc' = if pDepth == 0 && hadTokens+ then LocatedToken TokNewline lNum col : acc+ else acc+ in processOffset nextPos (lNum + 1) stack pDepth True 0 acc'+ 0x5C -> -- '\\' explicit line continuation+ let !afterSpaces = skipSpacesNoNL (i + 1)+ in if afterSpaces < len && at afterSpaces == 0x0A+ then lexLineTokens (afterSpaces + 1) (lNum + 1) 1 stack pDepth acc hadTokens+ else lexLineTokens afterSpaces lNum (col + 1) stack pDepth acc hadTokens+ 0x28 -> emitSym "(" (i + 1) lNum (col + 1) stack (pDepth + 1) acc+ 0x5B -> emitSym "[" (i + 1) lNum (col + 1) stack (pDepth + 1) acc+ 0x7B -> emitSym "{" (i + 1) lNum (col + 1) stack (pDepth + 1) acc+ 0x29 -> emitSym ")" (i + 1) lNum (col + 1) stack (max 0 (pDepth - 1)) acc+ 0x5D -> emitSym "]" (i + 1) lNum (col + 1) stack (max 0 (pDepth - 1)) acc+ 0x7D -> emitSym "}" (i + 1) lNum (col + 1) stack (max 0 (pDepth - 1)) acc++ -- Quoted strings+ _ | w == 0x22 || w == 0x27 ->+ case scanPyStringBS w i lNum False of+ (tok, nextIdx, newLine, newCol) ->+ lexLineTokens nextIdx newLine newCol stack pDepth (LocatedToken tok lNum col : acc) True++ -- String prefixes: f/F/r/R/b/B (and 2-char combos rf/fr/rb/br)+ _ | isPrefixCharW8 w && i + 1 < len && (at (i + 1) == 0x22 || at (i + 1) == 0x27) ->+ let !q = at (i + 1)+ !isF = w == 0x66 || w == 0x46+ !isB = w == 0x62 || w == 0x42+ !isR = w == 0x72 || w == 0x52+ in if isF+ then case scanFStringBS q (i + 2) lNum of+ (tok, nextIdx, newLine, newCol) ->+ lexLineTokens nextIdx newLine newCol stack pDepth (LocatedToken tok lNum col : acc) True+ else case scanPyStringBS q (i + 1) lNum isR of+ (TokStr s, nextIdx, newLine, newCol) ->+ let !tok = if isB then TokBytes s else TokStr s+ in lexLineTokens nextIdx newLine newCol stack pDepth (LocatedToken tok lNum col : acc) True+ (tok, nextIdx, newLine, newCol) ->+ lexLineTokens nextIdx newLine newCol stack pDepth (LocatedToken tok lNum col : acc) True++ _ | isTwoCharPrefix i ->+ let !w1 = at i+ !w2 = at (i + 1)+ !q = at (i + 2)+ !isF = w1 == 0x66 || w1 == 0x46 || w2 == 0x66 || w2 == 0x46+ !isB = w1 == 0x62 || w1 == 0x42 || w2 == 0x62 || w2 == 0x42+ !isR = w1 == 0x72 || w1 == 0x52 || w2 == 0x72 || w2 == 0x52+ in if isF+ then case scanFStringBS q (i + 3) lNum of+ (tok, nextIdx, newLine, newCol) ->+ lexLineTokens nextIdx newLine newCol stack pDepth (LocatedToken tok lNum col : acc) True+ else case scanPyStringBS q (i + 2) lNum isR of+ (TokStr s, nextIdx, newLine, newCol) ->+ let !tok = if isB then TokBytes s else TokStr s+ in lexLineTokens nextIdx newLine newCol stack pDepth (LocatedToken tok lNum col : acc) True+ (tok, nextIdx, newLine, newCol) ->+ lexLineTokens nextIdx newLine newCol stack pDepth (LocatedToken tok lNum col : acc) True++ _ | isDigitW8 w ->+ let !(numTok, nextIdx) = scanPyNumber i+ in lexLineTokens nextIdx lNum (col + (nextIdx - i)) stack pDepth (LocatedToken numTok lNum col : acc) True++ _ | isIdentStartW8 w ->+ let !end = scanWhile isIdentContW8 (i + 1)+ !ident = sliceText bs i (end - i)+ !tok = if Set.member ident pyKeywordSet then TokKw ident else TokIdent ident+ in lexLineTokens end lNum (col + (end - i)) stack pDepth (LocatedToken tok lNum col : acc) True++ _ ->+ case matchMultiCharSym i of+ Just (sym, symLen) ->+ emitSym sym (i + symLen) lNum (col + symLen) stack pDepth acc+ Nothing+ | isSinglePunctW8 w ->+ emitSym (sliceText bs i 1) (i + 1) lNum (col + 1) stack pDepth acc+ | otherwise ->+ Left (lNum, col, "Unexpected byte in Python source: " ++ show w)++ emitSym !sym !nextIdx !lNum !nextCol !st !pd !acc =+ lexLineTokens nextIdx lNum nextCol st pd (LocatedToken (TokSymbol sym) lNum (nextCol - T.length sym) : acc) True++ skipSpacesNoNL !k+ | k < len && isSpaceNoNLW8 (at k) = skipSpacesNoNL (k + 1)+ | otherwise = k++ scanWhile p !k+ | k < len && p (at k) = scanWhile p (k + 1)+ | otherwise = k++ isPrefixCharW8 w =+ w == 0x66 || w == 0x46 || w == 0x72 || w == 0x52 || w == 0x62 || w == 0x42++ isTwoCharPrefix !i+ | i + 2 >= len = False+ | otherwise =+ let !w1 = at i+ !w2 = at (i + 1)+ !w3 = at (i + 2)+ !combo =+ ((w1 == 0x72 || w1 == 0x52) && (w2 == 0x66 || w2 == 0x46 || w2 == 0x62 || w2 == 0x42))+ || ((w1 == 0x66 || w1 == 0x46 || w1 == 0x62 || w1 == 0x42) && (w2 == 0x72 || w2 == 0x52))+ in combo && (w3 == 0x22 || w3 == 0x27)++ matchMultiCharSym !i+ | i + 2 < len =+ let !w0 = at i+ !w1 = at (i + 1)+ !w2 = at (i + 2)+ in case (w0, w1, w2) of+ (0x2F, 0x2F, 0x3D) -> Just ("//=", 3)+ (0x2A, 0x2A, 0x3D) -> Just ("**=", 3)+ (0x3C, 0x3C, 0x3D) -> Just ("<<=", 3)+ (0x3E, 0x3E, 0x3D) -> Just (">>=", 3)+ (0x2E, 0x2E, 0x2E) -> Just ("...", 3)+ _ -> matchTwoCharSym i+ | i + 1 < len = matchTwoCharSym i+ | otherwise = Nothing++ matchTwoCharSym !i+ | i + 1 >= len = Nothing+ | otherwise =+ case (at i, at (i + 1)) of+ (0x2D, 0x3E) -> Just ("->", 2)+ (0x3A, 0x3D) -> Just (":=", 2)+ (0x3D, 0x3D) -> Just ("==", 2)+ (0x21, 0x3D) -> Just ("!=", 2)+ (0x3C, 0x3D) -> Just ("<=", 2)+ (0x3E, 0x3D) -> Just (">=", 2)+ (0x2B, 0x3D) -> Just ("+=", 2)+ (0x2D, 0x3D) -> Just ("-=", 2)+ (0x2A, 0x3D) -> Just ("*=", 2)+ (0x2F, 0x3D) -> Just ("/=", 2)+ (0x25, 0x3D) -> Just ("%=", 2)+ (0x26, 0x3D) -> Just ("&=", 2)+ (0x7C, 0x3D) -> Just ("|=", 2)+ (0x5E, 0x3D) -> Just ("^=", 2)+ (0x40, 0x3D) -> Just ("@=", 2)+ (0x2F, 0x2F) -> Just ("//", 2)+ (0x2A, 0x2A) -> Just ("**", 2)+ (0x3C, 0x3C) -> Just ("<<", 2)+ (0x3E, 0x3E) -> Just (">>", 2)+ _ -> Nothing++ scanPyStringBS !q !quoteIdx !curLine !isRaw =+ let !isTriple = quoteIdx + 2 < len && at (quoteIdx + 1) == q && at (quoteIdx + 2) == q+ in if isTriple+ then scanTripleStringBS q (quoteIdx + 3) curLine+ else scanSingleLineStringBS q (quoteIdx + 1) curLine isRaw++ scanTripleStringBS !q !start !curLine = goTQ start curLine 1+ where+ goTQ !k !ln !cl+ | k >= len = (TokStr (sliceText bs start (len - start)), len, ln, cl)+ | at k == q && k + 2 < len && at (k + 1) == q && at (k + 2) == q =+ (TokStr (sliceText bs start (k - start)), k + 3, ln, cl + 3)+ | at k == 0x5C && k + 1 < len =+ let !nlExtra = if at (k + 1) == 0x0A then 1 else 0+ !cl' = if nlExtra == 1 then 1 else cl + 2+ in goTQ (k + 2) (ln + nlExtra) cl'+ | at k == 0x0A = goTQ (k + 1) (ln + 1) 1+ | otherwise = goTQ (k + 1) ln (cl + 1)++ scanSingleLineStringBS !q !start !curLine !isRaw = fastLoop start+ where+ fastLoop !k+ | k >= len = (TokStr (sliceText bs start (len - start)), len, curLine, 1 + (len - start))+ | otherwise =+ let !b = at k+ in if b == q+ then (TokStr (sliceText bs start (k - start)), k + 1, curLine, 1 + (k + 1 - start))+ else if b == 0x0A+ then (TokStr (sliceText bs start (k - start)), k, curLine, 1 + (k - start))+ else if not isRaw && b == 0x5C+ then slowLoop k (BB.byteString (BS.take (k - start) (BS.drop start bs)))+ else fastLoop (k + 1)++ slowLoop !k !acc+ | k >= len =+ (TokStr (TE.decodeUtf8Lenient (BL.toStrict (BB.toLazyByteString acc))), len, curLine, 1)+ | otherwise =+ let !b = at k+ in if b == q+ then (TokStr (TE.decodeUtf8Lenient (BL.toStrict (BB.toLazyByteString acc))), k + 1, curLine, 1)+ else if b == 0x0A+ then (TokStr (TE.decodeUtf8Lenient (BL.toStrict (BB.toLazyByteString acc))), k, curLine, 1)+ else if b == 0x5C && k + 1 < len+ then let !nextB = at (k + 1)+ !escByte = case nextB of+ 0x6E -> 0x0A+ 0x74 -> 0x09+ 0x72 -> 0x0D+ other -> other+ in if nextB == 0x0A+ then slowLoop (k + 2) acc+ else slowLoop (k + 2) (acc <> BB.word8 escByte)+ else slowLoop (k + 1) (acc <> BB.word8 b)++ scanFStringBS !q !bodyStart !curLine =+ let !isTriple = bodyStart + 1 < len && at bodyStart == q && at (bodyStart + 1) == q+ !actualStart = if isTriple then bodyStart + 2 else bodyStart+ !qSlice = BS.replicate (if isTriple then 3 else 1) q+ in loopBody isTriple qSlice actualStart mempty [] curLine+ where+ flushText !builder !pAcc =+ let !txtBS = BL.toStrict (BB.toLazyByteString builder)+ in if BS.null txtBS then pAcc else FStringText (TE.decodeUtf8Lenient txtBS) : pAcc++ loopBody !isTriple !qSlice !k !txtB !pAcc !curL+ | k >= len =+ (TokFStr (reverse (flushText txtB pAcc)), len, curL, 1)+ | isTriple && BS.isPrefixOf qSlice (BS.drop k bs) =+ (TokFStr (reverse (flushText txtB pAcc)), k + 3, curL, 1)+ | not isTriple && at k == q =+ (TokFStr (reverse (flushText txtB pAcc)), k + 1, curL, 1)+ | k + 1 < len && at k == 0x7B && at (k + 1) == 0x7B = -- '{{'+ loopBody isTriple qSlice (k + 2) (txtB <> BB.word8 0x7B) pAcc curL+ | k + 1 < len && at k == 0x7D && at (k + 1) == 0x7D = -- '}}'+ loopBody isTriple qSlice (k + 2) (txtB <> BB.word8 0x7D) pAcc curL+ | at k == 0x7B = -- '{' interpolation expression+ let !pAcc' = flushText txtB pAcc+ !(exprBS, afterExpr, newL, isClosed) = scanFExpr [FLCtxExpr 1] (k + 1) (k + 1) curL+ !exprPart = FStringExpr (ExprId (TE.decodeUtf8Lenient exprBS)) Nothing Nothing+ in if not isClosed+ then (TokFStr (reverse (exprPart : pAcc')), len, newL, 1)+ else loopBody isTriple qSlice afterExpr mempty (exprPart : pAcc') newL+ | at k == 0x5C && k + 1 < len =+ let !nextL = if at (k + 1) == 0x0A then curL + 1 else curL+ in loopBody isTriple qSlice (k + 2) (txtB <> BB.word8 0x5C <> BB.word8 (at (k + 1))) pAcc nextL+ | at k == 0x0A =+ loopBody isTriple qSlice (k + 1) (txtB <> BB.word8 0x0A) pAcc (curL + 1)+ | otherwise =+ loopBody isTriple qSlice (k + 1) (txtB <> BB.word8 (at k)) pAcc curL++ scanFExpr [] !exprStart !k !ln =+ (BS.take (max 0 (k - 1 - exprStart)) (BS.drop exprStart bs), k, ln, True)+ scanFExpr _ _ !k !ln | k >= len =+ ("", len, ln, False)+ scanFExpr st@(top : restSt) !exprStart !k !ln = case top of+ FLCtxQuote !qBS !isNestedF ->+ if at k == 0x5C && k + 1 < len+ then scanFExpr st exprStart (k + 2) (if at (k + 1) == 0x0A then ln + 1 else ln)+ else if BS.isPrefixOf qBS (BS.drop k bs)+ then scanFExpr restSt exprStart (k + BS.length qBS) ln+ else if isNestedF && k + 1 < len && at k == 0x7B && at (k + 1) == 0x7B+ then scanFExpr st exprStart (k + 2) ln+ else if isNestedF && at k == 0x7B+ then scanFExpr (FLCtxExpr 1 : st) exprStart (k + 1) ln+ else scanFExpr st exprStart (k + 1) (if at k == 0x0A then ln + 1 else ln)+ FLCtxExpr !d ->+ case at k of+ 0x7B -> scanFExpr (FLCtxExpr (d + 1) : restSt) exprStart (k + 1) ln+ 0x7D ->+ if d == 1+ then if null restSt+ then (BS.take (k - exprStart) (BS.drop exprStart bs), k + 1, ln, True)+ else scanFExpr restSt exprStart (k + 1) ln+ else scanFExpr (FLCtxExpr (d - 1) : restSt) exprStart (k + 1) ln+ 0x23 ->+ let !nlIdx = findNewline (k + 1)+ in scanFExpr st exprStart nlIdx (ln + 1)+ 0x5C | k + 1 < len ->+ scanFExpr st exprStart (k + 2) (if at (k + 1) == 0x0A then ln + 1 else ln)+ _ | (at k == 0x66 || at k == 0x46) && k + 3 < len && (BS.isPrefixOf "\"\"\"" (BS.drop (k + 1) bs) || BS.isPrefixOf "'''" (BS.drop (k + 1) bs)) ->+ let !q3 = BS.take 3 (BS.drop (k + 1) bs)+ in scanFExpr (FLCtxQuote q3 True : st) exprStart (k + 4) ln+ _ | (at k == 0x66 || at k == 0x46) && k + 1 < len && (at (k + 1) == 0x22 || at (k + 1) == 0x27) ->+ let !q1 = BS.singleton (at (k + 1))+ in scanFExpr (FLCtxQuote q1 True : st) exprStart (k + 2) ln+ _ | isPrefixCharW8 (at k) && k + 3 < len && (BS.isPrefixOf "\"\"\"" (BS.drop (k + 1) bs) || BS.isPrefixOf "'''" (BS.drop (k + 1) bs)) ->+ let !q3 = BS.take 3 (BS.drop (k + 1) bs)+ in scanFExpr (FLCtxQuote q3 False : st) exprStart (k + 4) ln+ _ | isPrefixCharW8 (at k) && k + 1 < len && (at (k + 1) == 0x22 || at (k + 1) == 0x27) ->+ let !q1 = BS.singleton (at (k + 1))+ in scanFExpr (FLCtxQuote q1 False : st) exprStart (k + 2) ln+ _ | k + 2 < len && (BS.isPrefixOf "\"\"\"" (BS.drop k bs) || BS.isPrefixOf "'''" (BS.drop k bs)) ->+ let !q3 = BS.take 3 (BS.drop k bs)+ in scanFExpr (FLCtxQuote q3 False : st) exprStart (k + 3) ln+ 0x22 -> scanFExpr (FLCtxQuote "\"" False : st) exprStart (k + 1) ln+ 0x27 -> scanFExpr (FLCtxQuote "'" False : st) exprStart (k + 1) ln+ 0x0A -> scanFExpr st exprStart (k + 1) (ln + 1)+ _ -> scanFExpr st exprStart (k + 1) ln++ scanPyNumber !i+ | i + 1 < len && at i == 0x30 && (at (i + 1) == 0x78 || at (i + 1) == 0x58) =+ let !end = scanWhile (\b -> isHexW8 b || b == 0x5F) (i + 2)+ !val = foldDigits 16 (\b -> fromIntegral (digitToInt (toEnum (fromIntegral b)))) (i + 2) end 0+ in (TokNum val, end)+ | i + 1 < len && at i == 0x30 && (at (i + 1) == 0x6F || at (i + 1) == 0x4F) =+ let !end = scanWhile (\b -> isOctW8 b || b == 0x5F) (i + 2)+ !val = foldDigits 8 (\b -> fromIntegral (digitToInt (toEnum (fromIntegral b)))) (i + 2) end 0+ in (TokNum val, end)+ | i + 1 < len && at i == 0x30 && (at (i + 1) == 0x62 || at (i + 1) == 0x42) =+ let !end = scanWhile (\b -> b == 0x30 || b == 0x31 || b == 0x5F) (i + 2)+ !val = foldDigits 2 (\b -> if b == 0x31 then 1 else 0) (i + 2) end 0+ in (TokNum val, end)+ | otherwise =+ let !(end, hasFlt, hasUnd) = scanDecOrFloat i False False+ !rawSlice = BS.take (end - i) (BS.drop i bs)+ !cleanBS = if hasUnd then BS.filter (/= 0x5F) rawSlice else rawSlice+ !txt = TE.decodeUtf8Lenient cleanBS+ !tok = if hasFlt+ then case TR.double txt of+ Right (d, _) -> TokFloat d+ Left _ -> TokFloat 0.0+ else case TR.decimal txt of+ Right (n, _) -> TokNum n+ Left _ -> TokNum 0+ in (tok, end)++ foldDigits !base f !k !end !acc+ | k >= end = acc+ | at k == 0x5F = foldDigits base f (k + 1) end acc+ | otherwise = foldDigits base f (k + 1) end (acc * base + f (at k))++ scanDecOrFloat !k !hasFlt !hasUnd+ | k >= len = (k, hasFlt, hasUnd)+ | otherwise =+ let !b = at k+ in if isDigitW8 b+ then scanDecOrFloat (k + 1) hasFlt hasUnd+ else if b == 0x5F+ then scanDecOrFloat (k + 1) hasFlt True+ else if b == 0x2E || b == 0x65 || b == 0x45+ then scanDecOrFloat (k + 1) True hasUnd+ else (k, hasFlt, hasUnd)++-- ============================================================================ -- High-Throughput Parsing Ingestion -- ============================================================================ --- | Parse Python source text using the SWAR-accelerated direct pipeline.+-- | Parse Python source text using the ByteString SIMD + HybridIndentStack pipeline. parseFastPythonSource :: FilePath -> Text -> Either ParseError Program parseFastPythonSource filePath input =- let cleanInput = fastCanonicalizeText input- in parsePythonSource filePath cleanInput+ parseFastPythonByteString filePath (TE.encodeUtf8 input) --- | Parse raw Python UTF-8 / ASCII ByteString directly into a Program.+-- | Parse raw Python UTF-8 / ASCII ByteString directly into a Program+-- using 256-bit SIMD classification and HybridIndentStack. parseFastPythonByteString :: FilePath -> BS.ByteString -> Either ParseError Program parseFastPythonByteString filePath bs =- let cleanText = fastCanonicalizeBS bs- in parsePythonSource filePath cleanText+ case tokenizeFastPythonBS bs of+ Left (line, col, msg) -> Left (ParseError filePath line col (T.pack msg))+ Right tokens -> parsePythonTokens filePath tokens -- | Parse Python source directly into a Flat Linear Arena AST. parseFastPythonToArena :: FilePath -> Text -> Either ParseError LinearAST
src/Canontra/Parser/Go.hs view
@@ -16,15 +16,25 @@ -} module Canontra.Parser.Go ( parseGoSource+ , parseGoByteString ) where import Control.DeepSeq (NFData)-import Data.Char (isAlpha, isAlphaNum, isDigit, isSpace)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Lazy as BL+import qualified Data.ByteString.Unsafe as BSU+import Data.Set (Set)+import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T+import qualified Data.Text.Encoding as TE import qualified Data.Text.Read as TR+import Data.Word (Word8) import GHC.Generics (Generic) +import Canontra.Canonical.FastScan (ScanResult (..))+import Canontra.Canonical.SIMDScan (scanSourceSIMD) import Canontra.Canonical.Unicode (canonicalizeText) import Canontra.IR.Declaration import Canontra.IR.Dependency@@ -34,8 +44,17 @@ parseGoSource :: FilePath -> Text -> Either ParseError Program parseGoSource filePath input =- let cleanInput = canonicalizeText input- tokens = tokenizeGo cleanInput+ parseGoByteString filePath (TE.encodeUtf8 input)++-- | Parse raw Go UTF-8/ASCII ByteString directly using 256-bit SIMD pre-classification+-- and zero-copy byte-slice tokenization.+parseGoByteString :: FilePath -> BS.ByteString -> Either ParseError Program+parseGoByteString filePath rawBytes =+ let cleanBS = case scanSourceSIMD rawBytes of+ PureAsciiUnix -> rawBytes+ ContainsCRLF -> BS.filter (/= 0x0D) rawBytes+ RequiresUnicodeNFC -> TE.encodeUtf8 (canonicalizeText (TE.decodeUtf8Lenient rawBytes))+ tokens = tokenizeGoBS cleanBS in case parseGoTopLevel filePath tokens of Left err -> Left err Right (pkgName, decls, imps, stmts) ->@@ -53,79 +72,182 @@ deriving stock (Eq, Show, Generic) deriving anyclass (NFData) -tokenizeGo :: Text -> [GoToken]-tokenizeGo text = go text+{-# INLINE sliceText #-}+sliceText :: BS.ByteString -> Int -> Int -> Text+sliceText bs start len = TE.decodeUtf8Lenient (BS.take len (BS.drop start bs))++{-# INLINE isSpaceW8 #-}+isSpaceW8 :: Word8 -> Bool+isSpaceW8 w = w == 0x20 || w == 0x0A || w == 0x0D || w == 0x09 || w == 0x0C || w == 0x0B++{-# INLINE isDigitW8 #-}+isDigitW8 :: Word8 -> Bool+isDigitW8 w = w >= 0x30 && w <= 0x39++{-# INLINE isIdentStartW8 #-}+isIdentStartW8 :: Word8 -> Bool+isIdentStartW8 w =+ (w >= 0x61 && w <= 0x7A)+ || (w >= 0x41 && w <= 0x5A)+ || w == 0x5F+ || w >= 0x80++{-# INLINE isIdentContW8 #-}+isIdentContW8 :: Word8 -> Bool+isIdentContW8 w = isIdentStartW8 w || isDigitW8 w++{-# INLINE isSingleSymW8 #-}+isSingleSymW8 :: Word8 -> Bool+isSingleSymW8 w = case w of+ 0x7B -> True -- {+ 0x7D -> True -- }+ 0x28 -> True -- (+ 0x29 -> True -- )+ 0x5B -> True -- [+ 0x5D -> True -- ]+ 0x3B -> True -- ;+ 0x2C -> True -- ,+ 0x3F -> True -- ?+ 0x2E -> True -- .+ 0x7E -> True -- ~+ _ -> False++{-# INLINE isMultiSymW8 #-}+isMultiSymW8 :: Word8 -> Bool+isMultiSymW8 w = case w of+ 0x3D -> True -- =+ 0x2B -> True -- ++ 0x2D -> True -- -+ 0x2A -> True -- *+ 0x2F -> True -- /+ 0x25 -> True -- %+ 0x26 -> True -- &+ 0x7C -> True -- |+ 0x5E -> True -- ^+ 0x21 -> True -- !+ 0x3C -> True -- <+ 0x3E -> True -- >+ 0x3A -> True -- :+ _ -> False++tokenizeGoBS :: BS.ByteString -> [GoToken]+tokenizeGoBS !bs = go 0 where- go t | T.null t = []- go t =- let c = T.head t- cs = T.tail t- in case c of- _ | isSpace c -> go (T.dropWhile isSpace t)- '/' | T.isPrefixOf "/" cs ->- go (T.drop 1 (T.dropWhile (/= '\n') cs))- '/' | T.isPrefixOf "*" cs ->- skipBlockComment (T.drop 1 cs)- '"' ->- let (s, rest) = parseQuotedString '"' cs- in TokStr s : go rest- '`' ->- let (s, rest) = parseQuotedString '`' cs- in TokStr s : go rest- _ | isAlpha c || c == '_' ->- let (ident, rest) = T.span (\x -> isAlphaNum x || x == '_') t- in (if isGoKeyword ident then TokKw ident else TokIdent ident) : go rest- _ | isDigit c ->- let (numStr, rest) = T.span (\x -> isDigit x || x == '.' || x == 'e' || x == 'E') t- in if '.' `elem` T.unpack numStr- then case TR.double numStr of- Right (d, _) -> TokFloat d : go rest- Left _ -> TokFloat 0.0 : go rest- else case TR.decimal numStr of- Right (n, _) -> TokNum n : go rest- Left _ -> TokNum 0 : go rest- _ | c `elem` ("{}()[];,?:.~" :: String) ->- TokSymbol (T.singleton c) : go cs- _ | c `elem` ("=+-*/%&|^!<>:" :: String) ->- let (sym, rest) = T.span (`elem` ("=+-*/%&|^!<>:" :: String)) t- in TokSymbol sym : go rest- _ -> go cs+ !len = BS.length bs+ {-# INLINE at #-}+ at !i = BSU.unsafeIndex bs i - skipBlockComment t | T.null t = []- skipBlockComment t- | T.isPrefixOf "*/" t = go (T.drop 2 t)- | otherwise = skipBlockComment (T.tail t)+ go !i+ | i >= len = []+ | otherwise =+ let !w = at i+ in case w of+ _ | isSpaceW8 w -> go (skipSpaces (i + 1))+ 0x2F | i + 1 < len && at (i + 1) == 0x2F -> -- //+ go (skipLineComment (i + 2))+ 0x2F | i + 1 < len && at (i + 1) == 0x2A -> -- /*+ go (skipBlockComment (i + 2))+ 0x22 -> -- '"'+ let !(s, nextIdx) = scanEscapedString 0x22 (i + 1)+ in TokStr s : go nextIdx+ 0x60 -> -- '`' raw string in Go (no backslash escapes)+ let !(s, nextIdx) = scanRawBacktick (i + 1)+ in TokStr s : go nextIdx+ _ | isIdentStartW8 w ->+ let !end = scanWhile isIdentContW8 (i + 1)+ !ident = sliceText bs i (end - i)+ !tok = if isGoKeyword ident then TokKw ident else TokIdent ident+ in tok : go end+ _ | isDigitW8 w ->+ let !(end, hasDot) = scanNumber (i + 1) False+ !numText = sliceText bs i (end - i)+ !tok = if hasDot+ then case TR.double numText of+ Right (d, _) -> TokFloat d+ Left _ -> TokFloat 0.0+ else case TR.decimal numText of+ Right (n, _) -> TokNum n+ Left _ -> TokNum 0+ in tok : go end+ _ | isSingleSymW8 w ->+ TokSymbol (sliceText bs i 1) : go (i + 1)+ _ | isMultiSymW8 w ->+ let !end = scanWhile isMultiSymW8 (i + 1)+ in TokSymbol (sliceText bs i (end - i)) : go end+ _ -> go (i + 1) - parseQuotedString q t =- let (body, rest) = parseQuotedBody q t ""- in (body, rest)+ skipSpaces !k+ | k < len && isSpaceW8 (at k) = skipSpaces (k + 1)+ | otherwise = k - parseQuotedBody _ t acc | T.null t = (acc, "")- parseQuotedBody q t acc =- let c = T.head t- cs = T.tail t- in if c == q- then (acc, cs)- else if c == '\\' && not (T.null cs)- then let esc = case T.head cs of- 'n' -> '\n'- 't' -> '\t'- 'r' -> '\r'- '\\' -> '\\'- '\'' -> '\''- '"' -> '"'- '`' -> '`'- other -> other- in parseQuotedBody q (T.tail cs) (acc `T.snoc` esc)- else parseQuotedBody q cs (acc `T.snoc` c)+ skipLineComment !k+ | k < len && at k /= 0x0A = skipLineComment (k + 1)+ | k < len = k + 1+ | otherwise = len -isGoKeyword :: Text -> Bool-isGoKeyword kw = kw `elem`+ skipBlockComment !k+ | k + 1 < len && at k == 0x2A && at (k + 1) == 0x2F = k + 2+ | k < len = skipBlockComment (k + 1)+ | otherwise = len++ scanWhile p !k+ | k < len && p (at k) = scanWhile p (k + 1)+ | otherwise = k++ scanNumber !k !hasDot+ | k >= len = (k, hasDot)+ | otherwise =+ let !b = at k+ in if isDigitW8 b || b == 0x65 || b == 0x45 -- e or E+ then scanNumber (k + 1) hasDot+ else if b == 0x2E -- '.'+ then scanNumber (k + 1) True+ else (k, hasDot)++ scanRawBacktick !start = loop start+ where+ loop !k+ | k >= len = (sliceText bs start (len - start), len)+ | at k == 0x60 = (sliceText bs start (k - start), k + 1)+ | otherwise = loop (k + 1)++ scanEscapedString !q !start = fastLoop start+ where+ fastLoop !k+ | k >= len = (sliceText bs start (len - start), len)+ | otherwise =+ let !b = at k+ in if b == q+ then (sliceText bs start (k - start), k + 1)+ else if b == 0x5C -- '\\'+ then slowLoop k (BB.byteString (BS.take (k - start) (BS.drop start bs)))+ else fastLoop (k + 1)++ slowLoop !k !acc+ | k >= len = (TE.decodeUtf8Lenient (BL.toStrict (BB.toLazyByteString acc)), len)+ | otherwise =+ let !b = at k+ in if b == q+ then (TE.decodeUtf8Lenient (BL.toStrict (BB.toLazyByteString acc)), k + 1)+ else if b == 0x5C && k + 1 < len+ then let !escByte = case at (k + 1) of+ 0x6E -> 0x0A -- \n+ 0x74 -> 0x09 -- \t+ 0x72 -> 0x0D -- \r+ other -> other+ in slowLoop (k + 2) (acc <> BB.word8 escByte)+ else slowLoop (k + 1) (acc <> BB.word8 b)++goKeywordSet :: Set Text+goKeywordSet = Set.fromList [ "package", "import", "func", "type", "struct", "interface", "var", "const" , "return", "if", "else", "for", "range", "switch", "case", "default" , "go", "defer", "select", "chan", "map", "fallthrough", "break", "continue" ] +isGoKeyword :: Text -> Bool+isGoKeyword kw = Set.member kw goKeywordSet+ parseGoTopLevel :: FilePath -> [GoToken] -> Either ParseError (Text, [Declaration], [ImportDecl], [Stmt]) parseGoTopLevel _ tokens = let (pkg, afterPkg) = case tokens of@@ -434,6 +556,18 @@ parseGoBodyStmts (TokKw "switch" : rest) = let (switchStmt, afterSwitch) = parseGoSwitch rest in maybe [] pure switchStmt ++ parseGoBodyStmts afterSwitch+parseGoBodyStmts (TokIdent n1 : TokSymbol "," : TokIdent n2 : TokSymbol ":=" : rest) =+ let (expr, afterExpr) = parseGoSimpleExpr rest+ in StmtAnnAssign (ExprTuple [ExprId n1, ExprId n2]) (ExprId ":=") (Just expr) : parseGoBodyStmts afterExpr+parseGoBodyStmts (TokIdent n1 : TokSymbol "," : TokIdent n2 : TokSymbol "=" : rest) =+ let (expr, afterExpr) = parseGoSimpleExpr rest+ in StmtAssign [ExprId n1, ExprId n2] expr : parseGoBodyStmts afterExpr+parseGoBodyStmts (TokIdent name : TokSymbol ":=" : rest) =+ let (expr, afterExpr) = parseGoSimpleExpr rest+ in StmtAnnAssign (ExprId name) (ExprId ":=") (Just expr) : parseGoBodyStmts afterExpr+parseGoBodyStmts (TokIdent name : TokSymbol "=" : rest) =+ let (expr, afterExpr) = parseGoSimpleExpr rest+ in StmtAssign [ExprId name] expr : parseGoBodyStmts afterExpr parseGoBodyStmts (_:rest) = parseGoBodyStmts rest parseGoSwitch :: [GoToken] -> (Maybe Stmt, [GoToken])
src/Canontra/Parser/JS.hs view
@@ -18,17 +18,28 @@ -} module Canontra.Parser.JS ( parseJSSource+ , parseJSByteString , JSToken (..) , tokenizeJS+ , tokenizeJSByteString ) where import Control.DeepSeq (NFData)-import Data.Char (isAlpha, isAlphaNum, isDigit, isSpace)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Lazy as BL+import qualified Data.ByteString.Unsafe as BSU+import Data.Set (Set)+import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T+import qualified Data.Text.Encoding as TE import qualified Data.Text.Read as TR+import Data.Word (Word8) import GHC.Generics (Generic) +import Canontra.Canonical.FastScan (ScanResult (..))+import Canontra.Canonical.SIMDScan (scanSourceSIMD) import Canontra.Canonical.Unicode (canonicalizeText) import Canontra.IR.Declaration import Canontra.IR.Dependency@@ -38,14 +49,20 @@ parseJSSource :: FilePath -> Text -> Either ParseError Program parseJSSource filePath input =- let cleanInput = canonicalizeText input- tokens = tokenizeJS cleanInput+ parseJSByteString filePath (TE.encodeUtf8 input)++-- | Parse raw JS/TS UTF-8/ASCII ByteString directly using 256-bit SIMD pre-classification+-- and zero-copy byte-slice tokenization.+parseJSByteString :: FilePath -> BS.ByteString -> Either ParseError Program+parseJSByteString filePath rawBytes =+ let tokens = tokenizeJSByteString rawBytes in case parseTopLevel filePath tokens of Left err -> Left err Right (decls, imps, stmts) ->- let isTS = T.isSuffixOf ".ts" (T.pack filePath) || T.isSuffixOf ".tsx" (T.pack filePath)+ let fpText = T.pack filePath+ isTS = T.isSuffixOf ".ts" fpText || T.isSuffixOf ".tsx" fpText lang = if isTS then "typescript" else "javascript"- modul = Module (T.pack filePath) imps decls stmts+ modul = Module fpText imps decls stmts in Right (Program [modul] lang) data JSToken@@ -60,155 +77,301 @@ deriving anyclass (NFData) tokenizeJS :: Text -> [JSToken]-tokenizeJS text = go Nothing text+tokenizeJS = tokenizeJSByteString . TE.encodeUtf8++{-# INLINE sliceText #-}+sliceText :: BS.ByteString -> Int -> Int -> Text+sliceText bs start len = TE.decodeUtf8Lenient (BS.take len (BS.drop start bs))++{-# INLINE isSpaceW8 #-}+isSpaceW8 :: Word8 -> Bool+isSpaceW8 w = w == 0x20 || w == 0x0A || w == 0x0D || w == 0x09 || w == 0x0C || w == 0x0B++{-# INLINE isAlphaW8 #-}+isAlphaW8 :: Word8 -> Bool+isAlphaW8 w = (w >= 0x61 && w <= 0x7A) || (w >= 0x41 && w <= 0x5A)++{-# INLINE isDigitW8 #-}+isDigitW8 :: Word8 -> Bool+isDigitW8 w = w >= 0x30 && w <= 0x39++{-# INLINE isJSIdentStartW8 #-}+isJSIdentStartW8 :: Word8 -> Bool+isJSIdentStartW8 w = isAlphaW8 w || w == 0x5F || w == 0x24 || w >= 0x80 -- '_' or '$'++{-# INLINE isJSIdentContW8 #-}+isJSIdentContW8 :: Word8 -> Bool+isJSIdentContW8 w = isJSIdentStartW8 w || isDigitW8 w++{-# INLINE isJSSingleSymW8 #-}+isJSSingleSymW8 :: Word8 -> Bool+isJSSingleSymW8 w = case w of+ 0x7B -> True -- {+ 0x7D -> True -- }+ 0x28 -> True -- (+ 0x29 -> True -- )+ 0x5B -> True -- [+ 0x5D -> True -- ]+ 0x3B -> True -- ;+ 0x2C -> True -- ,+ 0x3F -> True -- ?+ 0x3A -> True -- :+ 0x2E -> True -- .+ 0x7E -> True -- ~+ _ -> False++{-# INLINE isJSMultiSymW8 #-}+isJSMultiSymW8 :: Word8 -> Bool+isJSMultiSymW8 w = case w of+ 0x3D -> True -- =+ 0x2B -> True -- ++ 0x2D -> True -- -+ 0x2A -> True -- *+ 0x25 -> True -- %+ 0x26 -> True -- &+ 0x7C -> True -- |+ 0x5E -> True -- ^+ 0x21 -> True -- !+ 0x3C -> True -- <+ 0x3E -> True -- >+ 0x40 -> True -- @+ _ -> False++{-# INLINE isRegexFlagW8 #-}+isRegexFlagW8 :: Word8 -> Bool+isRegexFlagW8 w = case w of+ 0x67 -> True -- g+ 0x69 -> True -- i+ 0x6D -> True -- m+ 0x73 -> True -- s+ 0x75 -> True -- u+ 0x79 -> True -- y+ 0x76 -> True -- v+ 0x64 -> True -- d+ _ -> False++{-# INLINE isRegexFollowerW8 #-}+isRegexFollowerW8 :: Word8 -> Bool+isRegexFollowerW8 w = case w of+ 0x2E -> True -- .+ 0x3B -> True -- ;+ 0x2C -> True -- ,+ 0x29 -> True -- )+ 0x5D -> True -- ]+ 0x7D -> True -- }+ 0x0A -> True -- \n+ _ -> False++-- | ByteString-native JS/TS/JSX tokenizer using 256-bit SIMD pre-classification+-- and zero-copy slice extraction.+tokenizeJSByteString :: BS.ByteString -> [JSToken]+tokenizeJSByteString rawBytes = go Nothing 0 where- go _ t | T.null t = []- go prevTok t =- let c = T.head t- cs = T.tail t- in case c of- _ | isSpace c ->- let (spaces, rest) = T.span isSpace t- in if shouldInsertASI prevTok spaces- then TokSymbol ";" : go (Just (TokSymbol ";")) rest- else go prevTok rest- '/' | T.isPrefixOf "/" cs ->- go prevTok (T.drop 1 (T.dropWhile (/= '\n') cs))- '/' | T.isPrefixOf "*" cs ->- skipBlockComment prevTok (T.drop 1 cs)- '/' ->- if isDivideOp prevTok cs- then- if T.isPrefixOf "=" cs- then TokSymbol "/=" : go (Just (TokSymbol "/=")) (T.drop 1 cs)- else TokSymbol "/" : go (Just (TokSymbol "/")) cs- else- case scanRegex cs of- Just (pattern, flags, rest) ->- let regexTok = TokStr ("/" <> pattern <> "/" <> flags)- in regexTok : go (Just regexTok) rest- Nothing ->- TokSymbol "/" : go (Just (TokSymbol "/")) cs- '"' ->- let (s, rest) = parseQuotedString '"' cs- tok = TokStr s- in tok : go (Just tok) rest- '\'' ->- let (s, rest) = parseQuotedString '\'' cs- tok = TokStr s- in tok : go (Just tok) rest- '`' ->- let (s, rest) = parseQuotedString '`' cs- tok = TokStr s- in tok : go (Just tok) rest- _ | isAlpha c || c == '_' || c == '$' ->- let (ident, rest) = T.span (\x -> isAlphaNum x || x == '_' || x == '$') t- tok = if isJSKeyword ident then TokKw ident else TokIdent ident- in tok : go (Just tok) rest- _ | isDigit c ->- let (numStr, rest) = T.span (\x -> isDigit x || x == '.' || x == 'e' || x == 'E') t- tok = if '.' `elem` T.unpack numStr- then case TR.double numStr of+ !bs = case scanSourceSIMD rawBytes of+ PureAsciiUnix -> rawBytes+ ContainsCRLF -> BS.filter (/= 0x0D) rawBytes+ RequiresUnicodeNFC -> TE.encodeUtf8 (canonicalizeText (TE.decodeUtf8Lenient rawBytes))+ !len = BS.length bs++ {-# INLINE at #-}+ at !i = BSU.unsafeIndex bs i++ go !prevTok !i+ | i >= len = []+ | otherwise =+ let !w = at i+ in case w of+ _ | isSpaceW8 w ->+ let !(end, hasNL) = skipSpacesTrackNL (i + 1) (w == 0x0A)+ in if hasNL && shouldInsertASI prevTok+ then TokSymbol ";" : go (Just (TokSymbol ";")) end+ else go prevTok end+ 0x2F | i + 1 < len && at (i + 1) == 0x2F -> -- //+ go prevTok (skipLineComment (i + 2))+ 0x2F | i + 1 < len && at (i + 1) == 0x2A -> -- /*+ go prevTok (skipBlockComment (i + 2))+ 0x2F -> -- '/' (division or regex literal)+ let !afterSlash = i + 1+ in if isDivideOp prevTok afterSlash+ then if afterSlash < len && at afterSlash == 0x3D+ then let !tok = TokSymbol "/="+ in tok : go (Just tok) (afterSlash + 1)+ else let !tok = TokSymbol "/"+ in tok : go (Just tok) afterSlash+ else case scanRegexBS afterSlash of+ Just (pattern, flags, nextIdx) ->+ let !regexTok = TokStr ("/" <> pattern <> "/" <> flags)+ in regexTok : go (Just regexTok) nextIdx+ Nothing ->+ let !tok = TokSymbol "/"+ in tok : go (Just tok) afterSlash+ 0x22 -> -- '"'+ let !(s, nextIdx) = scanEscapedString 0x22 (i + 1)+ !tok = TokStr s+ in tok : go (Just tok) nextIdx+ 0x27 -> -- '\''+ let !(s, nextIdx) = scanEscapedString 0x27 (i + 1)+ !tok = TokStr s+ in tok : go (Just tok) nextIdx+ 0x60 -> -- '`'+ let !(s, nextIdx) = scanEscapedString 0x60 (i + 1)+ !tok = TokStr s+ in tok : go (Just tok) nextIdx+ _ | isJSIdentStartW8 w ->+ let !end = scanWhile isJSIdentContW8 (i + 1)+ !ident = sliceText bs i (end - i)+ !tok = if isJSKeyword ident then TokKw ident else TokIdent ident+ in tok : go (Just tok) end+ _ | isDigitW8 w ->+ let !(end, hasDot) = scanNumber (i + 1) False+ !numText = sliceText bs i (end - i)+ !tok = if hasDot+ then case TR.double numText of Right (d, _) -> TokFloat d Left _ -> TokFloat 0.0- else case TR.decimal numStr of+ else case TR.decimal numText of Right (n, _) -> TokNum n Left _ -> TokNum 0- in tok : go (Just tok) rest- _ | c `elem` ("{}()[];,?:.~" :: String) ->- let tok = TokSymbol (T.singleton c)- in tok : go (Just tok) cs- _ | c `elem` ("=+-*%&|^!<>@" :: String) ->- let (sym, rest) = T.span (`elem` ("=+-*%&|^!<>@" :: String)) t- tok = TokSymbol sym- in tok : go (Just tok) rest- _ -> go prevTok cs+ in tok : go (Just tok) end+ _ | isJSSingleSymW8 w ->+ let !tok = TokSymbol (sliceText bs i 1)+ in tok : go (Just tok) (i + 1)+ _ | isJSMultiSymW8 w ->+ let !end = scanWhile isJSMultiSymW8 (i + 1)+ !tok = TokSymbol (sliceText bs i (end - i))+ in tok : go (Just tok) end+ _ -> go prevTok (i + 1) - skipBlockComment _ t | T.null t = []- skipBlockComment prevTok t- | T.isPrefixOf "*/" t = go prevTok (T.drop 2 t)- | otherwise = skipBlockComment prevTok (T.tail t)+ skipSpacesTrackNL !k !hasNL+ | k >= len = (k, hasNL)+ | otherwise =+ let !b = at k+ in if isSpaceW8 b+ then skipSpacesTrackNL (k + 1) (hasNL || b == 0x0A)+ else (k, hasNL) - shouldInsertASI (Just (TokKw kw)) spaces- | kw `elem` ["return", "throw", "break", "continue", "yield"] && '\n' `elem` T.unpack spaces = True- shouldInsertASI _ _ = False+ skipLineComment !k+ | k < len && at k /= 0x0A = skipLineComment (k + 1)+ | k < len = k + 1+ | otherwise = len + skipBlockComment !k+ | k + 1 < len && at k == 0x2A && at (k + 1) == 0x2F = k + 2+ | k < len = skipBlockComment (k + 1)+ | otherwise = len++ scanWhile p !k+ | k < len && p (at k) = scanWhile p (k + 1)+ | otherwise = k++ scanNumber !k !hasDot+ | k >= len = (k, hasDot)+ | otherwise =+ let !b = at k+ in if isDigitW8 b || b == 0x65 || b == 0x45+ then scanNumber (k + 1) hasDot+ else if b == 0x2E+ then scanNumber (k + 1) True+ else (k, hasDot)++ shouldInsertASI (Just (TokKw kw)) =+ kw == "return" || kw == "throw" || kw == "break" || kw == "continue" || kw == "yield"+ shouldInsertASI _ = False+ isDivideOp (Just (TokIdent _)) _ = True isDivideOp (Just (TokNum _)) _ = True isDivideOp (Just (TokFloat _)) _ = True isDivideOp (Just (TokStr _)) _ = True isDivideOp (Just (TokSymbol ")")) _ = True isDivideOp (Just (TokSymbol "]")) _ = True- isDivideOp (Just (TokSymbol "}")) nextRest = not (looksLikeRegex nextRest)+ isDivideOp (Just (TokSymbol "}")) nextIdx = not (looksLikeRegexBS nextIdx) isDivideOp _ _ = False - looksLikeRegex t- | T.null t = False+ looksLikeRegexBS !startIdx+ | startIdx >= len = False | otherwise =- case scanRegex t of+ case scanRegexBounds startIdx of Nothing -> False- Just (pat, flags, rest) ->- not (T.null pat)- && case T.uncons pat of- Just (firstCh, _) -> firstCh /= ' ' && firstCh /= '\t' && firstCh /= '*' && firstCh /= '='- Nothing -> False- && (T.null flags || all (`elem` ("gimsuyvd" :: String)) (T.unpack flags))- && case T.uncons (T.dropWhile isSpace rest) of- Just (nextCh, _) -> nextCh `elem` (".;,)]}\n" :: String)- Nothing -> True+ Just (patLen, flagStart, flagEnd, restIdx) ->+ if patLen <= 0+ then False+ else+ let !firstB = at startIdx+ !flagsValid = allBytes isRegexFlagW8 flagStart flagEnd+ !nextNonSpace = scanWhile isSpaceW8 restIdx+ !validFollow = nextNonSpace >= len || isRegexFollowerW8 (at nextNonSpace)+ in firstB /= 0x20 && firstB /= 0x09 && firstB /= 0x2A && firstB /= 0x3D+ && flagsValid && validFollow - scanRegex t =- case scanPattern False False t "" of- Just (pat, afterSlash) ->- let (flags, rest) = T.span isAlpha afterSlash- in Just (pat, flags, rest)- Nothing -> Nothing+ allBytes p !a !b+ | a >= b = True+ | p (at a) = allBytes p (a + 1) b+ | otherwise = False++ scanRegexBS !startIdx = case scanRegexBounds startIdx of+ Nothing -> Nothing+ Just (patLen, flagStart, flagEnd, restIdx) ->+ let !pat = sliceText bs startIdx patLen+ !flags = sliceText bs flagStart (flagEnd - flagStart)+ in Just (pat, flags, restIdx)++ scanRegexBounds !startIdx = scanPat False False startIdx where- scanPattern _ _ txt _ | T.null txt = Nothing- scanPattern inCharClass escaped txt acc =- let ch = T.head txt- rst = T.tail txt- in if escaped- then scanPattern inCharClass False rst (acc `T.snoc` '\\' `T.snoc` ch)- else case ch of- '\\' -> scanPattern inCharClass True rst acc- '[' -> scanPattern True False rst (acc `T.snoc` ch)- ']' -> scanPattern False False rst (acc `T.snoc` ch)- '/' | not inCharClass -> Just (acc, rst)- '\n' -> Nothing- _ -> scanPattern inCharClass False rst (acc `T.snoc` ch)+ scanPat !inCC !esc !k+ | k >= len = Nothing+ | otherwise =+ let !b = at k+ in if esc+ then scanPat inCC False (k + 1)+ else case b of+ 0x5C -> scanPat inCC True (k + 1) -- '\\'+ 0x5B -> scanPat True False (k + 1) -- '['+ 0x5D -> scanPat False False (k + 1) -- ']'+ 0x2F | not inCC -> -- '/'+ let !flagStart = k + 1+ !flagEnd = scanWhile isAlphaW8 flagStart+ in Just (k - startIdx, flagStart, flagEnd, flagEnd)+ 0x0A -> Nothing+ _ -> scanPat inCC False (k + 1) - parseQuotedString q t =- let (body, rest) = parseQuotedBody q t ""- in (body, rest)+ scanEscapedString !q !start = fastLoop start+ where+ fastLoop !k+ | k >= len = (sliceText bs start (len - start), len)+ | otherwise =+ let !b = at k+ in if b == q+ then (sliceText bs start (k - start), k + 1)+ else if b == 0x5C+ then slowLoop k (BB.byteString (BS.take (k - start) (BS.drop start bs)))+ else fastLoop (k + 1) - parseQuotedBody _ t acc | T.null t = (acc, "")- parseQuotedBody q t acc =- let c = T.head t- cs = T.tail t- in if c == q- then (acc, cs)- else if c == '\\' && not (T.null cs)- then let esc = case T.head cs of- 'n' -> '\n'- 't' -> '\t'- 'r' -> '\r'- '\\' -> '\\'- '\'' -> '\''- '"' -> '"'- '`' -> '`'- other -> other- in parseQuotedBody q (T.tail cs) (acc `T.snoc` esc)- else parseQuotedBody q cs (acc `T.snoc` c)+ slowLoop !k !acc+ | k >= len = (TE.decodeUtf8Lenient (BL.toStrict (BB.toLazyByteString acc)), len)+ | otherwise =+ let !b = at k+ in if b == q+ then (TE.decodeUtf8Lenient (BL.toStrict (BB.toLazyByteString acc)), k + 1)+ else if b == 0x5C && k + 1 < len+ then let !escByte = case at (k + 1) of+ 0x6E -> 0x0A+ 0x74 -> 0x09+ 0x72 -> 0x0D+ other -> other+ in slowLoop (k + 2) (acc <> BB.word8 escByte)+ else slowLoop (k + 1) (acc <> BB.word8 b) -isJSKeyword :: Text -> Bool-isJSKeyword kw = kw `elem`+jsKeywordSet :: Set Text+jsKeywordSet = Set.fromList [ "function", "async", "class", "interface", "type", "enum", "const", "let", "var" , "import", "from", "export", "default", "return", "if", "else", "while", "for" , "of", "in", "switch", "case", "try", "catch", "finally", "throw", "break", "continue" , "new", "this", "super", "extends", "implements", "static", "await", "yield", "using" ] +isJSKeyword :: Text -> Bool+isJSKeyword kw = Set.member kw jsKeywordSet+ parseTopLevel :: FilePath -> [JSToken] -> Either ParseError ([Declaration], [ImportDecl], [Stmt]) parseTopLevel _ tokens = let (decls, imps, stmts) = extractDeclsAndStmts tokens@@ -223,6 +386,17 @@ (d, i, s) = extractDeclsAndStmts afterImp in (d, maybe [] pure impDecl ++ i, s) + -- export * from 'mod' / export { a, b as c } from 'mod' (barrel re-exports)+ TokKw "export" : TokSymbol "*" : TokKw "from" : TokStr modPath : rest ->+ let afterSemi = dropWhile (\tok -> tok == TokSymbol ";") rest+ (d, i, s) = extractDeclsAndStmts afterSemi+ in (d, ImportFrom modPath ImportAll : i, s)++ TokKw "export" : TokSymbol "{" : rest+ | Just (syms, modPath, afterExp) <- parseReExportClause rest ->+ let (d, i, s) = extractDeclsAndStmts afterExp+ in (d, ImportFrom modPath (ImportSymbols syms) : i, s)+ -- export ... TokKw "export" : rest -> extractDeclsAndStmts rest@@ -295,16 +469,60 @@ in (d, i, maybe [] pure stmt ++ s) parseImportItem :: [JSToken] -> (Maybe ImportDecl, [JSToken])+parseImportItem (TokStr modPath : rest) =+ (Just (ImportModule modPath Nothing), dropWhile (\tok -> tok == TokSymbol ";") rest) parseImportItem tokens =- let fromPart = dropWhile (\tok -> tok /= TokKw "from") tokens- in case fromPart of+ let (clauseToks, afterClause) = span (\tok -> tok /= TokKw "from" && tok /= TokSymbol ";") tokens+ in case afterClause of TokKw "from" : TokStr modPath : rest -> let afterSemi = dropWhile (\tok -> tok == TokSymbol ";") rest- in (Just (ImportModule modPath Nothing), afterSemi)+ in (Just (clauseToImport clauseToks modPath), afterSemi) _ -> let rest = dropWhile (\tok -> tok /= TokSymbol ";") tokens in (Nothing, if null rest then [] else tail rest)+ where+ clauseToImport toks modPath = case toks of+ [TokSymbol "*", TokIdent "as", TokIdent alias] ->+ ImportModule modPath (Just alias)+ [TokIdent defName] ->+ ImportModule modPath (Just defName)+ _ ->+ case span (\t -> t /= TokSymbol "{") toks of+ (prefix, TokSymbol "{" : inner) ->+ let (braceToks, _) = span (\t -> t /= TokSymbol "}") inner+ named = parseImportSpecifiers braceToks+ defPair = case prefix of+ (TokIdent defName : _) -> [("default", Just defName)]+ _ -> []+ allSyms = defPair ++ named+ in if null allSyms+ then ImportModule modPath Nothing+ else ImportFrom modPath (ImportSymbols allSyms)+ _ -> ImportModule modPath Nothing +parseReExportClause :: [JSToken] -> Maybe ([(Text, Maybe Text)], Text, [JSToken])+parseReExportClause toks =+ let (innerToks, afterBrace) = span (\t -> t /= TokSymbol "}") toks+ in case afterBrace of+ TokSymbol "}" : TokKw "from" : TokStr modPath : rest ->+ let syms = parseImportSpecifiers innerToks+ afterSemi = dropWhile (\t -> t == TokSymbol ";") rest+ in if null syms then Nothing else Just (syms, modPath, afterSemi)+ _ -> Nothing++parseImportSpecifiers :: [JSToken] -> [(Text, Maybe Text)]+parseImportSpecifiers [] = []+parseImportSpecifiers (TokIdent orig : TokIdent "as" : TokIdent alias : rest) =+ (orig, Just alias) : parseImportSpecifiers (dropWhile (\t -> t == TokSymbol ",") rest)+parseImportSpecifiers (TokIdent orig : TokKw "default" : rest) =+ (orig, Just "default") : parseImportSpecifiers (dropWhile (\t -> t == TokSymbol ",") rest)+parseImportSpecifiers (TokKw "default" : TokIdent "as" : TokIdent alias : rest) =+ ("default", Just alias) : parseImportSpecifiers (dropWhile (\t -> t == TokSymbol ",") rest)+parseImportSpecifiers (TokIdent orig : rest) =+ (orig, Nothing) : parseImportSpecifiers (dropWhile (\t -> t == TokSymbol ",") rest)+parseImportSpecifiers (_ : rest) =+ parseImportSpecifiers rest+ parseFunctionBody :: Text -> Bool -> [JSToken] -> (Function, [JSToken]) parseFunctionBody name isAsync tokens = let (params, afterParams) = parseParamList tokens@@ -447,6 +665,11 @@ afterSemi = dropWhile (\t -> t == TokSymbol ";") afterExpr remStmts = parseBodyStmts afterSemi in [StmtAsyncWith [(expr, Just (ExprId name))] remStmts]+parseBodyStmts (TokKw kw : TokIdent name : TokSymbol "=" : rest)+ | kw == "const" || kw == "let" || kw == "var" =+ let (expr, afterExpr) = parseSimpleExpr rest+ afterSemi = dropWhile (\t -> t == TokSymbol ";") afterExpr+ in StmtAnnAssign (ExprId name) (ExprId kw) (Just expr) : parseBodyStmts afterSemi parseBodyStmts (TokKw "return" : TokSymbol ";" : rest) = StmtReturn Nothing : parseBodyStmts rest parseBodyStmts (TokKw "return" : rest) =
src/Canontra/Parser/Polyglot.hs view
@@ -8,18 +8,22 @@ module Canontra.Parser.Polyglot ( parsePolyglotSource , parsePolyglotSourceWithLang+ , parsePolyglotByteString+ , parsePolyglotByteStringWithLang , detectLanguage ) where +import qualified Data.ByteString as BS import Data.Text (Text) import qualified Data.Text as T+import qualified Data.Text.Encoding as TE import System.FilePath (takeExtension) import Canontra.IR.Program (Program)-import Canontra.Parser.Go (parseGoSource)-import Canontra.Parser.JS (parseJSSource)-import Canontra.Parser.Python (parsePythonSource)-import Canontra.Parser.Rust (parseRustSource)+import Canontra.Parser.FastPython (parseFastPythonByteString, parseFastPythonSource)+import Canontra.Parser.Go (parseGoByteString, parseGoSource)+import Canontra.Parser.JS (parseJSByteString, parseJSSource)+import Canontra.Parser.Rust (parseRustByteString, parseRustSource) import Canontra.Types (LanguageTag (..), ParseError (..)) -- | Ingest and parse a polyglot source file by auto-detecting language from extension.@@ -31,12 +35,28 @@ -- | Parse source text using an explicitly declared language. parsePolyglotSourceWithLang :: LanguageTag -> FilePath -> Text -> Either ParseError Program parsePolyglotSourceWithLang lang filePath input = case lang of- LangPython -> parsePythonSource filePath input+ LangPython -> parseFastPythonSource filePath input LangJavaScript -> parseJSSource filePath input LangTypeScript -> parseJSSource filePath input LangGo -> parseGoSource filePath input LangRust -> parseRustSource filePath input- LangUnknown _ -> parsePythonSource filePath input+ LangUnknown _ -> parseFastPythonSource filePath input++-- | Parse raw source ByteString directly via SIMD-classified byte-slice parsers.+parsePolyglotByteString :: FilePath -> BS.ByteString -> Either ParseError Program+parsePolyglotByteString filePath rawBytes =+ let lang = detectLanguage filePath+ in parsePolyglotByteStringWithLang lang filePath rawBytes++-- | Parse raw source ByteString directly using an explicitly declared language.+parsePolyglotByteStringWithLang :: LanguageTag -> FilePath -> BS.ByteString -> Either ParseError Program+parsePolyglotByteStringWithLang lang filePath rawBytes = case lang of+ LangPython -> parseFastPythonByteString filePath rawBytes+ LangJavaScript -> parseJSByteString filePath rawBytes+ LangTypeScript -> parseJSByteString filePath rawBytes+ LangGo -> parseGoByteString filePath rawBytes+ LangRust -> parseRustByteString filePath rawBytes+ LangUnknown _ -> parseFastPythonByteString filePath (if BS.null rawBytes then TE.encodeUtf8 T.empty else rawBytes) -- | Detect the programming language from a file path extension. detectLanguage :: FilePath -> LanguageTag
src/Canontra/Parser/Python.hs view
@@ -18,12 +18,17 @@ -} module Canontra.Parser.Python ( parsePythonSource+ , parsePythonTokens , tokenizePython+ , PyToken (..)+ , LocatedToken (..) , advanceColumn ) where import Control.DeepSeq (NFData) import Data.Char (digitToInt, isAlpha, isAlphaNum, isDigit, isHexDigit, isOctDigit, isSpace)+import Data.Set (Set)+import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Read as TR@@ -36,6 +41,20 @@ import Canontra.IR.Program import Canontra.Types (ParseError (..)) +-- | Parse an already-tokenized Python token stream into a unified 'Program'.+parsePythonTokens :: FilePath -> [LocatedToken] -> Either ParseError Program+parsePythonTokens filePath tokens =+ case parsePythonTopLevel filePath tokens of+ Left err -> Left err+ Right (decls, imps, stmts) ->+ let modul = Module+ { modName = T.pack filePath+ , modImports = imps+ , modDeclarations = decls+ , modStatements = stmts+ }+ in Right (Program [modul] "python")+ -- | Main entry point: parses a Python source string into a 'Program'. parsePythonSource :: FilePath -> Text -> Either ParseError Program parsePythonSource filePath input =@@ -44,16 +63,7 @@ Left (line, col, msg) -> Left (ParseError filePath line col (T.pack msg)) Right tokens ->- case parsePythonTopLevel filePath tokens of- Left err -> Left err- Right (decls, imps, stmts) ->- let modul = Module- { modName = T.pack filePath- , modImports = imps- , modDeclarations = decls- , modStatements = stmts- }- in Right (Program [modul] "python")+ parsePythonTokens filePath tokens -- ============================================================================ -- Lexer Types & Token Definition@@ -438,14 +448,17 @@ Right (n, _) -> (TokNum n, T.drop len t, len) Left _ -> (TokNum 0, T.drop len t, len) -isPyKeyword :: Text -> Bool-isPyKeyword k = k `elem`+pyKeywordSet :: Set Text+pyKeywordSet = Set.fromList [ "False", "None", "True", "and", "as", "assert", "async", "await" , "break", "class", "continue", "def", "del", "elif", "else", "except" , "finally", "for", "from", "global", "if", "import", "in", "is" , "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try" , "while", "with", "yield" ]++isPyKeyword :: Text -> Bool+isPyKeyword k = Set.member k pyKeywordSet -- ============================================================================ -- Recursive Descent Parser
src/Canontra/Parser/Rust.hs view
@@ -16,15 +16,25 @@ -} module Canontra.Parser.Rust ( parseRustSource+ , parseRustByteString ) where import Control.DeepSeq (NFData)-import Data.Char (isAlpha, isAlphaNum, isDigit, isSpace)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Lazy as BL+import qualified Data.ByteString.Unsafe as BSU+import Data.Set (Set)+import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T+import qualified Data.Text.Encoding as TE import qualified Data.Text.Read as TR+import Data.Word (Word8) import GHC.Generics (Generic) +import Canontra.Canonical.FastScan (ScanResult (..))+import Canontra.Canonical.SIMDScan (scanSourceSIMD) import Canontra.Canonical.Unicode (canonicalizeText) import Canontra.IR.Declaration import Canontra.IR.Dependency@@ -34,8 +44,17 @@ parseRustSource :: FilePath -> Text -> Either ParseError Program parseRustSource filePath input =- let cleanInput = canonicalizeText input- tokens = tokenizeRust cleanInput+ parseRustByteString filePath (TE.encodeUtf8 input)++-- | Parse raw Rust UTF-8/ASCII ByteString directly using 256-bit SIMD pre-classification+-- and zero-copy byte-slice tokenization.+parseRustByteString :: FilePath -> BS.ByteString -> Either ParseError Program+parseRustByteString filePath rawBytes =+ let cleanBS = case scanSourceSIMD rawBytes of+ PureAsciiUnix -> rawBytes+ ContainsCRLF -> BS.filter (/= 0x0D) rawBytes+ RequiresUnicodeNFC -> TE.encodeUtf8 (canonicalizeText (TE.decodeUtf8Lenient rawBytes))+ tokens = tokenizeRustBS cleanBS in case parseRustTopLevel filePath tokens of Left err -> Left err Right (decls, imps, stmts) ->@@ -52,92 +71,185 @@ deriving stock (Eq, Show, Generic) deriving anyclass (NFData) -tokenizeRust :: Text -> [RustToken]-tokenizeRust text = go text+{-# INLINE sliceText #-}+sliceText :: BS.ByteString -> Int -> Int -> Text+sliceText bs start len = TE.decodeUtf8Lenient (BS.take len (BS.drop start bs))++{-# INLINE isSpaceW8 #-}+isSpaceW8 :: Word8 -> Bool+isSpaceW8 w = w == 0x20 || w == 0x0A || w == 0x0D || w == 0x09 || w == 0x0C || w == 0x0B++{-# INLINE isDigitW8 #-}+isDigitW8 :: Word8 -> Bool+isDigitW8 w = w >= 0x30 && w <= 0x39++{-# INLINE isIdentStartW8 #-}+isIdentStartW8 :: Word8 -> Bool+isIdentStartW8 w =+ (w >= 0x61 && w <= 0x7A)+ || (w >= 0x41 && w <= 0x5A)+ || w == 0x5F+ || w >= 0x80++{-# INLINE isIdentContW8 #-}+isIdentContW8 :: Word8 -> Bool+isIdentContW8 w = isIdentStartW8 w || isDigitW8 w++{-# INLINE isSingleSymW8 #-}+isSingleSymW8 :: Word8 -> Bool+isSingleSymW8 w = case w of+ 0x7B -> True -- {+ 0x7D -> True -- }+ 0x28 -> True -- (+ 0x29 -> True -- )+ 0x5B -> True -- [+ 0x5D -> True -- ]+ 0x3B -> True -- ;+ 0x2C -> True -- ,+ 0x3F -> True -- ?+ 0x2E -> True -- .+ 0x7E -> True -- ~+ _ -> False++{-# INLINE isMultiSymW8 #-}+isMultiSymW8 :: Word8 -> Bool+isMultiSymW8 w = case w of+ 0x3D -> True -- =+ 0x2B -> True -- ++ 0x2D -> True -- -+ 0x2A -> True -- *+ 0x2F -> True -- /+ 0x25 -> True -- %+ 0x26 -> True -- &+ 0x7C -> True -- |+ 0x5E -> True -- ^+ 0x21 -> True -- !+ 0x3C -> True -- <+ 0x3E -> True -- >+ 0x3A -> True -- :+ _ -> False++tokenizeRustBS :: BS.ByteString -> [RustToken]+tokenizeRustBS !bs = go 0 where- go t | T.null t = []- go t =- let c = T.head t- cs = T.tail t- in case c of- _ | isSpace c -> go (T.dropWhile isSpace t)- '/' | T.isPrefixOf "/" cs ->- go (T.drop 1 (T.dropWhile (/= '\n') cs))- '/' | T.isPrefixOf "*" cs ->- skipBlockComment (T.drop 1 cs)- '"' ->- let (s, rest) = parseQuotedString '"' cs- in TokStr s : go rest- '\'' ->- case T.uncons cs of- Just (x, xs) | (isAlpha x || x == '_') && not (T.isPrefixOf "'" xs) ->- let (lifetimeIdent, rest) = T.span (\ch -> isAlphaNum ch || ch == '_') cs- in TokIdent ("'" <> lifetimeIdent) : go rest- Just (x, xs) | T.isPrefixOf "'" xs ->- TokStr (T.singleton x) : go (T.drop 1 xs)- Just ('\\', xs) ->- case T.uncons xs of- Just (escChar, afterEsc) | T.isPrefixOf "'" afterEsc ->- TokStr (T.singleton escChar) : go (T.drop 1 afterEsc)- _ -> TokSymbol "'" : go cs- _ ->- TokSymbol "'" : go cs- _ | T.isPrefixOf "r#" t ->- let (ident, rest) = T.span (\x -> isAlphaNum x || x == '_') (T.drop 2 t)- in TokIdent ident : go rest- _ | isAlpha c || c == '_' ->- let (ident, rest) = T.span (\x -> isAlphaNum x || x == '_') t- in (if isRustKeyword ident then TokKw ident else TokIdent ident) : go rest- _ | isDigit c ->- let (numStr, rest) = T.span (\x -> isDigit x || x == '.' || x == 'e' || x == 'E') t- in if '.' `elem` T.unpack numStr- then case TR.double numStr of- Right (d, _) -> TokFloat d : go rest- Left _ -> TokFloat 0.0 : go rest- else case TR.decimal numStr of- Right (n, _) -> TokNum n : go rest- Left _ -> TokNum 0 : go rest- _ | c `elem` ("{}()[];,?:.~" :: String) ->- TokSymbol (T.singleton c) : go cs- _ | c `elem` ("=+-*/%&|^!<>:" :: String) ->- let (sym, rest) = T.span (`elem` ("=+-*/%&|^!<>:" :: String)) t- in TokSymbol sym : go rest- _ -> go cs+ !len = BS.length bs+ {-# INLINE at #-}+ at !i = BSU.unsafeIndex bs i - skipBlockComment t | T.null t = []- skipBlockComment t- | T.isPrefixOf "*/" t = go (T.drop 2 t)- | otherwise = skipBlockComment (T.tail t)+ go !i+ | i >= len = []+ | otherwise =+ let !w = at i+ in case w of+ _ | isSpaceW8 w -> go (skipSpaces (i + 1))+ 0x2F | i + 1 < len && at (i + 1) == 0x2F -> -- //+ go (skipLineComment (i + 2))+ 0x2F | i + 1 < len && at (i + 1) == 0x2A -> -- /*+ go (skipBlockComment (i + 2))+ 0x22 -> -- '"'+ let !(s, nextIdx) = scanEscapedString 0x22 (i + 1)+ in TokStr s : go nextIdx+ 0x27 -> -- '\'' (lifetime or char literal)+ if i + 3 < len && at (i + 1) == 0x5C && at (i + 3) == 0x27+ then TokStr (sliceText bs (i + 2) 1) : go (i + 4)+ else if i + 1 < len && isIdentStartW8 (at (i + 1)) && (i + 2 >= len || at (i + 2) /= 0x27)+ then+ let !end = scanWhile isIdentContW8 (i + 2)+ in TokIdent (sliceText bs i (end - i)) : go end+ else if i + 2 < len && at (i + 2) == 0x27+ then TokStr (sliceText bs (i + 1) 1) : go (i + 3)+ else TokSymbol "'" : go (i + 1)+ 0x72 | i + 1 < len && at (i + 1) == 0x23 -> -- r#ident+ let !end = scanWhile isIdentContW8 (i + 2)+ in TokIdent (sliceText bs (i + 2) (end - i - 2)) : go end+ _ | isIdentStartW8 w ->+ let !end = scanWhile isIdentContW8 (i + 1)+ !ident = sliceText bs i (end - i)+ !tok = if isRustKeyword ident then TokKw ident else TokIdent ident+ in tok : go end+ _ | isDigitW8 w ->+ let !(end, hasDot) = scanNumber (i + 1) False+ !numText = sliceText bs i (end - i)+ !tok = if hasDot+ then case TR.double numText of+ Right (d, _) -> TokFloat d+ Left _ -> TokFloat 0.0+ else case TR.decimal numText of+ Right (n, _) -> TokNum n+ Left _ -> TokNum 0+ in tok : go end+ _ | isSingleSymW8 w ->+ TokSymbol (sliceText bs i 1) : go (i + 1)+ _ | isMultiSymW8 w ->+ let !end = scanWhile isMultiSymW8 (i + 1)+ in TokSymbol (sliceText bs i (end - i)) : go end+ _ -> go (i + 1) - parseQuotedString q t =- let (body, rest) = parseQuotedBody q t ""- in (body, rest)+ skipSpaces !k+ | k < len && isSpaceW8 (at k) = skipSpaces (k + 1)+ | otherwise = k - parseQuotedBody _ t acc | T.null t = (acc, "")- parseQuotedBody q t acc =- let c = T.head t- cs = T.tail t- in if c == q- then (acc, cs)- else if c == '\\' && not (T.null cs)- then let esc = case T.head cs of- 'n' -> '\n'- 't' -> '\t'- 'r' -> '\r'- '\\' -> '\\'- '\'' -> '\''- '"' -> '"'- other -> other- in parseQuotedBody q (T.tail cs) (acc `T.snoc` esc)- else parseQuotedBody q cs (acc `T.snoc` c)+ skipLineComment !k+ | k < len && at k /= 0x0A = skipLineComment (k + 1)+ | k < len = k + 1+ | otherwise = len -isRustKeyword :: Text -> Bool-isRustKeyword kw = kw `elem`+ skipBlockComment !k+ | k + 1 < len && at k == 0x2A && at (k + 1) == 0x2F = k + 2+ | k < len = skipBlockComment (k + 1)+ | otherwise = len++ scanWhile p !k+ | k < len && p (at k) = scanWhile p (k + 1)+ | otherwise = k++ scanNumber !k !hasDot+ | k >= len = (k, hasDot)+ | otherwise =+ let !b = at k+ in if isDigitW8 b || b == 0x65 || b == 0x45+ then scanNumber (k + 1) hasDot+ else if b == 0x2E+ then scanNumber (k + 1) True+ else (k, hasDot)++ scanEscapedString !q !start = fastLoop start+ where+ fastLoop !k+ | k >= len = (sliceText bs start (len - start), len)+ | otherwise =+ let !b = at k+ in if b == q+ then (sliceText bs start (k - start), k + 1)+ else if b == 0x5C+ then slowLoop k (BB.byteString (BS.take (k - start) (BS.drop start bs)))+ else fastLoop (k + 1)++ slowLoop !k !acc+ | k >= len = (TE.decodeUtf8Lenient (BL.toStrict (BB.toLazyByteString acc)), len)+ | otherwise =+ let !b = at k+ in if b == q+ then (TE.decodeUtf8Lenient (BL.toStrict (BB.toLazyByteString acc)), k + 1)+ else if b == 0x5C && k + 1 < len+ then let !escByte = case at (k + 1) of+ 0x6E -> 0x0A+ 0x74 -> 0x09+ 0x72 -> 0x0D+ other -> other+ in slowLoop (k + 2) (acc <> BB.word8 escByte)+ else slowLoop (k + 1) (acc <> BB.word8 b)++rustKeywordSet :: Set Text+rustKeywordSet = Set.fromList [ "fn", "struct", "enum", "trait", "impl", "for", "type", "mod", "use", "pub", "crate" , "let", "mut", "const", "static", "if", "else", "match", "loop", "while", "return" , "async", "await", "self", "Self", "where", "break", "continue" ] +isRustKeyword :: Text -> Bool+isRustKeyword kw = Set.member kw rustKeywordSet+ parseRustTopLevel :: FilePath -> [RustToken] -> Either ParseError ([Declaration], [ImportDecl], [Stmt]) parseRustTopLevel _ tokens = let (decls, imps, stmts) = extractRustDeclsAndStmts tokens@@ -146,12 +258,12 @@ extractRustDeclsAndStmts :: [RustToken] -> ([Declaration], [ImportDecl], [Stmt]) extractRustDeclsAndStmts [] = ([], [], []) extractRustDeclsAndStmts tokens = case tokens of- -- use path::to::item;+ -- use path::to::item; (including pub use / braced use trees / ::*) TokKw "use" : rest ->- let (pathToks, afterSemi) = span (\tok -> tok /= TokSymbol ";") rest- path = T.concat [p | TokIdent p <- pathToks]- imp = ImportModule path Nothing- (d, i, s) = extractRustDeclsAndStmts (if null afterSemi then [] else tail afterSemi)+ let (useToks, afterSemi) = span (\tok -> tok /= TokSymbol ";") rest+ imp = parseRustUseTree useToks+ remToks = if null afterSemi then [] else tail afterSemi+ (d, i, s) = extractRustDeclsAndStmts remToks in (d, imp : i, s) -- pub ...@@ -293,7 +405,7 @@ Parameter "&mut self" ParamPositional Nothing Nothing : extractRustParams (dropWhile (\t -> t == TokSymbol ",") rest) extractRustParams (TokIdent pName : TokSymbol ":" : rest) = let (tyToks, afterTy) = span (\t -> t /= TokSymbol "," && t /= TokSymbol ")") rest- tyStr = if null tyToks then Nothing else Just (T.concat [tokenText t | t <- tyToks])+ tyStr = if null tyToks then Nothing else Just (T.strip (T.concat [typeTokenText t | t <- tyToks])) remToks = dropWhile (\t -> t == TokSymbol ",") afterTy in Parameter pName ParamPositional Nothing tyStr : extractRustParams remToks extractRustParams (TokIdent pName : rest) =@@ -303,7 +415,7 @@ parseRustReturnType :: [RustToken] -> (Maybe Text, [RustToken]) parseRustReturnType (TokSymbol "->" : rest) = let (tyToks, afterTy) = span (\t -> t /= TokSymbol "{" && t /= TokKw "where" && t /= TokSymbol ";") rest- tyStr = if null tyToks then Nothing else Just (T.concat [tokenText t | t <- tyToks])+ tyStr = if null tyToks then Nothing else Just (T.strip (T.concat [typeTokenText t | t <- tyToks])) in (tyStr, afterTy) parseRustReturnType tokens = (Nothing, tokens) @@ -312,11 +424,15 @@ parseRustFields (TokKw "pub" : rest) = parseRustFields rest parseRustFields (TokIdent fName : TokSymbol ":" : rest) = let (tyToks, afterTy) = span (\t -> t /= TokSymbol "," && t /= TokSymbol "}") rest- tyStr = if null tyToks then Nothing else Just (T.concat [tokenText t | t <- tyToks])+ tyStr = if null tyToks then Nothing else Just (T.strip (T.concat [typeTokenText t | t <- tyToks])) remToks = dropWhile (\t -> t == TokSymbol ",") afterTy in (fName, tyStr) : parseRustFields remToks parseRustFields (_:rest) = parseRustFields rest +typeTokenText :: RustToken -> Text+typeTokenText (TokKw "mut") = "mut "+typeTokenText t = tokenText t+ parseRustMethods :: [RustToken] -> [Function] parseRustMethods [] = [] parseRustMethods (TokKw "pub" : rest) = parseRustMethods rest@@ -374,15 +490,15 @@ in case afterType of TokSymbol "=" : exprToks -> let (expr, afterExpr) = parseRustSimpleExpr exprToks- in (Just (StmtAssign [ExprId name] expr), afterExpr)+ in (Just (StmtAnnAssign (ExprId name) (ExprId "let") (Just expr)), afterExpr) _ -> let nextToks = dropWhile (\t -> t == TokSymbol ";") afterType- in (Just (StmtAssign [ExprId name] (ExprId "()")), nextToks)+ in (Just (StmtAnnAssign (ExprId name) (ExprId "let") (Just (ExprId "()"))), nextToks) TokIdent name : TokSymbol "=" : exprToks -> let (expr, afterExpr) = parseRustSimpleExpr exprToks- in (Just (StmtAssign [ExprId name] expr), afterExpr)+ in (Just (StmtAnnAssign (ExprId name) (ExprId "let") (Just expr)), afterExpr) TokIdent name : TokSymbol ";" : afterSemi ->- (Just (StmtAssign [ExprId name] (ExprId "()")), afterSemi)+ (Just (StmtAnnAssign (ExprId name) (ExprId "let") (Just (ExprId "()"))), afterSemi) _ -> (Nothing, rest) parseRustSingleStmt (TokIdent name : TokSymbol "!" : rest) = let (macroExpr, afterMacro) = parseRustSimpleExpr (TokIdent name : TokSymbol "!" : rest)@@ -391,40 +507,39 @@ let (expr, afterExpr) = parseRustSimpleExpr rest in (Just (StmtAssign [ExprId name] expr), afterExpr) parseRustSingleStmt (TokIdent name : TokSymbol "(" : rest) =- let afterParen = dropWhile (\t -> t /= TokSymbol ")") rest- nextToks = dropWhile (\t -> t == TokSymbol ";") (if null afterParen then [] else tail afterParen)- in (Just (StmtExpr (ExprCall (ExprId name) [] [])), nextToks)+ let (expr, afterExpr) = parseRustSimpleExpr (TokIdent name : TokSymbol "(" : rest)+ in (Just (StmtExpr expr), afterExpr) parseRustSingleStmt (_:rest) = (Nothing, rest) parseRustSimpleExpr :: [RustToken] -> (Expr, [RustToken]) parseRustSimpleExpr (TokSymbol ";" : rest) = (ExprLit LitNone, rest)-parseRustSimpleExpr (TokIdent name : TokSymbol "!" : TokSymbol openB : rest)- | openB `elem` ["(", "[", "{"] =- let closeB = case openB of "(" -> ")"; "[" -> "]"; _ -> "}"- (bodyToks, afterClose) = extractBalancedDelim openB closeB rest- nextToks = dropWhile (\t -> t == TokSymbol ";") afterClose- macroArgs = if null bodyToks then [] else [ExprId (T.concat [tokenText t | t <- bodyToks])]- in (ExprMacroCall name macroArgs, nextToks)-parseRustSimpleExpr (TokIdent name : TokSymbol "(" : rest) =- let afterParen = dropWhile (\t -> t /= TokSymbol ")") rest- nextToks = dropWhile (\t -> t == TokSymbol ";") (if null afterParen then [] else tail afterParen)- in (ExprCall (ExprId name) [] [], nextToks)-parseRustSimpleExpr (TokNum n : rest) =- let nextToks = dropWhile (\t -> t == TokSymbol ";") rest- in (ExprLit (LitInt n), nextToks)-parseRustSimpleExpr (TokFloat f : rest) =- let nextToks = dropWhile (\t -> t == TokSymbol ";") rest- in (ExprLit (LitFloat f), nextToks)-parseRustSimpleExpr (TokStr s : rest) =- let nextToks = dropWhile (\t -> t == TokSymbol ";") rest- in (ExprLit (LitString s), nextToks)-parseRustSimpleExpr (TokIdent name : rest) =- let nextToks = dropWhile (\t -> t == TokSymbol ";") rest- in (ExprId name, nextToks) parseRustSimpleExpr tokens =- let after = dropWhile (\t -> t /= TokSymbol ";") tokens- in (ExprLit LitNone, if null after then [] else tail after)+ let (primary, afterPrimary) = parseRustPrimary tokens+ in applyPostfixOps primary afterPrimary+ where+ applyPostfixOps !expr (TokSymbol "?" : rest) =+ applyPostfixOps (ExprTryOp expr) rest+ applyPostfixOps !expr rest =+ (expr, dropWhile (\t -> t == TokSymbol ";") rest) + parseRustPrimary (TokIdent name : TokSymbol "!" : TokSymbol openB : rest)+ | openB `elem` ["(", "[", "{"] =+ let closeB = case openB of "(" -> ")"; "[" -> "]"; _ -> "}"+ (bodyToks, afterClose) = extractBalancedDelim openB closeB rest+ macroArgs = if null bodyToks then [] else [ExprId (T.concat [tokenText t | t <- bodyToks])]+ in (ExprMacroCall name macroArgs, afterClose)+ parseRustPrimary (TokIdent name : TokSymbol "(" : rest) =+ let afterParen = dropWhile (\t -> t /= TokSymbol ")") rest+ nextToks = if null afterParen then [] else tail afterParen+ in (ExprCall (ExprId name) [] [], nextToks)+ parseRustPrimary (TokNum n : rest) = (ExprLit (LitInt n), rest)+ parseRustPrimary (TokFloat f : rest) = (ExprLit (LitFloat f), rest)+ parseRustPrimary (TokStr s : rest) = (ExprLit (LitString s), rest)+ parseRustPrimary (TokIdent name : rest) = (ExprId name, rest)+ parseRustPrimary toks =+ let after = dropWhile (\t -> t /= TokSymbol ";") toks+ in (ExprLit LitNone, if null after then [] else tail after)+ extractBalancedDelim :: Text -> Text -> [RustToken] -> ([RustToken], [RustToken]) extractBalancedDelim openB closeB tokens = go (1 :: Int) [] tokens where@@ -445,3 +560,39 @@ tokenText (TokStr t) = "\"" <> t <> "\"" tokenText (TokNum n) = T.pack (show n) tokenText (TokFloat f) = T.pack (show f)++-- | Parse Rust @use@ path/tree into normalized 'ImportDecl' preserving module hierarchy,+-- braced symbol lists (@use a::b::{x, y as z}@), and wildcard re-exports (@use a::b::*@).+parseRustUseTree :: [RustToken] -> ImportDecl+parseRustUseTree toks =+ let (prefixToks, bracePart) = span (\t -> t /= TokSymbol "{") toks+ segNames = [p | t <- prefixToks, Just p <- [extractSeg t]]+ cleanSegs = filter (\s -> s /= "crate" && s /= "self" && s /= "super") segNames+ in case bracePart of+ TokSymbol "{" : inner ->+ let (bToks, _) = span (\t -> t /= TokSymbol "}") inner+ modPath = T.intercalate "." cleanSegs+ syms = parseRustUseBraced bToks+ in ImportFrom modPath (ImportSymbols syms)+ _ -> case reverse cleanSegs of+ ("*" : revParent) | not (null revParent) ->+ ImportFrom (T.intercalate "." (reverse revParent)) ImportAll+ (lastSeg : revParent) | not (null revParent) ->+ ImportFrom (T.intercalate "." (reverse revParent)) (ImportSymbols [(lastSeg, Nothing)])+ _ ->+ ImportModule (T.intercalate "." cleanSegs) Nothing+ where+ extractSeg (TokIdent p) = Just p+ extractSeg (TokKw "self") = Just "self"+ extractSeg (TokKw "crate") = Just "crate"+ extractSeg (TokKw "super") = Just "super"+ extractSeg (TokSymbol "*") = Just "*"+ extractSeg _ = Nothing++ parseRustUseBraced [] = []+ parseRustUseBraced (TokIdent orig : TokKw "as" : TokIdent alias : r) =+ (orig, Just alias) : parseRustUseBraced (dropWhile (\t -> t == TokSymbol ",") r)+ parseRustUseBraced (TokIdent orig : r) =+ (orig, Nothing) : parseRustUseBraced (dropWhile (\t -> t == TokSymbol ",") r)+ parseRustUseBraced (_ : r) =+ parseRustUseBraced r
src/Canontra/Repository/Parallel.hs view
@@ -5,14 +5,14 @@ {- | Module : Canontra.Repository.Parallel-Description : Chase-Lev lock-free work-stealing parallel repository processor.+Description : Mutable ring-buffer Chase-Lev work-stealing parallel repository processor. -Implements a dedicated Chase-Lev lock-free work-stealing scheduler for high-throughput-multi-core repository ingestion (>= 100,000 LOC/s) and sub-10ms incremental hot updates.-Each GHC capability runs a worker with a private Chase-Lev deque:-- Workers push and pop files locally from the bottom of their deque without locking.-- Idle capabilities steal batches of up to 16 tasks from the top of busy deques.-- Zero thread starvation and zero capability contention across 16+ core runners.+Implements a capability-aware work-stealing scheduler using mutable power-of-2+ring-buffer deques ('MV.IOVector') and a zero-contention pre-allocated result vector:+- O(1) pushBottom / popBottom / stealTop / stealBatchTop with zero whole-vector copies.+- O(1) worker deque lookup via boxed 'V.Vector'.+- Zero-contention parallel writes directly into disjoint slots of 'MV.IOVector b',+ preserving exact input stream order with zero final sort overhead. -} module Canontra.Repository.Parallel ( -- * Chase-Lev Deque & Work-Stealing Engine@@ -37,13 +37,13 @@ import Control.Concurrent (yield) import Control.Concurrent.Async (forConcurrently)+import Control.Concurrent.MVar (MVar, modifyMVar, modifyMVar_, newMVar, readMVar) import Control.Monad (forM_)+import Data.Bits ((.&.)) import qualified Data.ByteString as BS-import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)-import Data.List (sortBy)-import Data.Ord (comparing) import qualified Data.Text.Encoding as TE import qualified Data.Vector as V+import qualified Data.Vector.Mutable as MV import GHC.Conc (getNumCapabilities) import System.FilePath ((</>)) @@ -52,96 +52,113 @@ import Canontra.Types (FileEntry (..), ParseError) -- ============================================================================--- Chase-Lev Lock-Free Work-Stealing Deque+-- Chase-Lev Ring-Buffer Work-Stealing Deque -- ============================================================================ --- | Internal state of a Chase-Lev circular deque.+-- | Internal state of a mutable power-of-2 ring-buffer Chase-Lev deque. data DequeState a = DequeState { dsTop :: !Int , dsBottom :: !Int- , dsBuffer :: !(V.Vector (Maybe a))- } deriving stock (Show)+ , dsBuffer :: !(MV.IOVector (Maybe a))+ } +instance Show (DequeState a) where+ show (DequeState t b buf) =+ "DequeState {dsTop = " ++ show t ++ ", dsBottom = " ++ show b ++ ", dsCapacity = " ++ show (MV.length buf) ++ "}"+ -- | A Chase-Lev work-stealing deque bound to a worker capability. data ChaseLevDeque a = ChaseLevDeque { cldId :: !Int- , cldState :: !(IORef (DequeState a))+ , cldState :: !(MVar (DequeState a)) } --- | Allocate a new Chase-Lev deque with default initial circular buffer capacity.+-- | Allocate a new Chase-Lev deque with default initial circular buffer capacity (256 slots). newChaseLevDeque :: Int -> IO (ChaseLevDeque a) newChaseLevDeque workerId = do- ref <- newIORef (DequeState 0 0 (V.replicate 256 Nothing))+ buf <- MV.replicate 256 Nothing+ ref <- newMVar (DequeState 0 0 buf) pure $ ChaseLevDeque workerId ref --- | Push a task to the bottom of the deque (called exclusively by owner thread).+-- | Push a task to the bottom of the deque in amortized O(1) time (owner thread). pushBottom :: ChaseLevDeque a -> a -> IO ()-pushBottom (ChaseLevDeque _ ref) item =- atomicModifyIORef' ref $ \s@DequeState{..} ->- let !cap = V.length dsBuffer- in if dsBottom >= cap- then- let !newCap = cap * 2- !newBuf = V.generate newCap $ \i ->- if i < cap then dsBuffer V.! i else Nothing- !s' = s { dsBottom = dsBottom + 1- , dsBuffer = newBuf V.// [(dsBottom, Just item)]- }- in (s', ())- else- let !s' = s { dsBottom = dsBottom + 1- , dsBuffer = dsBuffer V.// [(dsBottom, Just item)]- }- in (s', ())+pushBottom (ChaseLevDeque _ mvar) item =+ modifyMVar_ mvar $ \s@DequeState{..} -> do+ let !cap = MV.length dsBuffer+ !size = dsBottom - dsTop+ !mask = cap - 1+ if size >= cap+ then do+ let !newCap = cap * 2+ newBuf <- MV.replicate newCap Nothing+ forM_ [0 .. size - 1] $ \k -> do+ val <- MV.unsafeRead dsBuffer ((dsTop + k) .&. mask)+ MV.unsafeWrite newBuf k val+ MV.unsafeWrite newBuf size (Just item)+ pure (DequeState 0 (size + 1) newBuf)+ else do+ MV.unsafeWrite dsBuffer (dsBottom .&. mask) (Just item)+ pure s { dsBottom = dsBottom + 1 } --- | Pop a task from the bottom of the deque in LIFO order (called by owner thread).+-- | Pop a task from the bottom of the deque in LIFO O(1) time (owner thread). popBottom :: ChaseLevDeque a -> IO (Maybe a)-popBottom (ChaseLevDeque _ ref) =- atomicModifyIORef' ref $ \s@DequeState{..} ->+popBottom (ChaseLevDeque _ mvar) =+ modifyMVar mvar $ \s@DequeState{..} -> if dsBottom <= dsTop- then (s { dsBottom = dsTop }, Nothing)- else+ then pure (s { dsBottom = dsTop }, Nothing)+ else do let !b = dsBottom - 1- !mItem = dsBuffer V.! b- !s' = s { dsBottom = b, dsBuffer = dsBuffer V.// [(b, Nothing)] }- in (s', mItem)+ !slot = b .&. (MV.length dsBuffer - 1)+ mItem <- MV.unsafeRead dsBuffer slot+ MV.unsafeWrite dsBuffer slot Nothing+ pure (s { dsBottom = b }, mItem) --- | Steal a single task from the top of the deque in FIFO order (called by thieves).+-- | Steal a single task from the top of the deque in FIFO O(1) time (thieves). stealTop :: ChaseLevDeque a -> IO (Maybe a)-stealTop (ChaseLevDeque _ ref) =- atomicModifyIORef' ref $ \s@DequeState{..} ->+stealTop (ChaseLevDeque _ mvar) =+ modifyMVar mvar $ \s@DequeState{..} -> if dsTop >= dsBottom- then (s, Nothing)- else- let !t = dsTop- !mItem = dsBuffer V.! t- !s' = s { dsTop = t + 1, dsBuffer = dsBuffer V.// [(t, Nothing)] }- in (s', mItem)+ then pure (s, Nothing)+ else do+ let !slot = dsTop .&. (MV.length dsBuffer - 1)+ mItem <- MV.unsafeRead dsBuffer slot+ MV.unsafeWrite dsBuffer slot Nothing+ pure (s { dsTop = dsTop + 1 }, mItem) -- | Steal a batch of up to @maxBatch@ tasks from the top of the deque in a single atomic step. stealBatchTop :: ChaseLevDeque a -> Int -> IO [a]-stealBatchTop (ChaseLevDeque _ ref) maxBatch =- atomicModifyIORef' ref $ \s@DequeState{..} ->+stealBatchTop (ChaseLevDeque _ mvar) maxBatch =+ modifyMVar mvar $ \s@DequeState{..} -> do let !available = dsBottom - dsTop- in if available <= 0- then (s, [])- else- let !batchSize = min maxBatch (max 1 (available `quot` 2))- !stolen = [item | i <- [dsTop .. dsTop + batchSize - 1], Just item <- [dsBuffer V.! i]]- !updates = [(i, Nothing) | i <- [dsTop .. dsTop + batchSize - 1]]- !s' = s { dsTop = dsTop + batchSize, dsBuffer = dsBuffer V.// updates }- in (s', stolen)+ if available <= 0 || maxBatch <= 0+ then pure (s, [])+ else do+ let !batchSize = min maxBatch (max 1 (available `quot` 2))+ !mask = MV.length dsBuffer - 1+ stolen <- collectSlice dsBuffer mask dsTop batchSize+ pure (s { dsTop = dsTop + batchSize }, stolen)+ where+ collectSlice !buf !mask !start !cnt = go 0 []+ where+ go !k acc+ | k >= cnt = pure (reverse acc)+ | otherwise = do+ let !slot = (start + k) .&. mask+ mVal <- MV.unsafeRead buf slot+ MV.unsafeWrite buf slot Nothing+ case mVal of+ Just v -> go (k + 1) (v : acc)+ Nothing -> go (k + 1) acc -- | Current number of active tasks in the deque. dequeSize :: ChaseLevDeque a -> IO Int-dequeSize (ChaseLevDeque _ ref) = do- s <- readIORef ref+dequeSize (ChaseLevDeque _ mvar) = do+ s <- readMVar mvar pure $ max 0 (dsBottom s - dsTop s) -- | Returns 'True' if the deque currently contains zero tasks. isDequeEmpty :: ChaseLevDeque a -> IO Bool-isDequeEmpty (ChaseLevDeque _ ref) = do- s <- readIORef ref+isDequeEmpty (ChaseLevDeque _ mvar) = do+ s <- readMVar mvar pure (dsBottom s <= dsTop s) -- ============================================================================@@ -150,33 +167,33 @@ -- | High-throughput capability-aware work-stealing parallel processor. -- Partitions work across private worker deques, dynamically balances execution via--- batch work-stealing, and ensures deterministic result ordering.+-- batch work-stealing, and writes results directly into disjoint slots of a pre-allocated+-- mutable vector for zero-contention deterministic output ordering. parProcessWorkStealing :: (a -> IO b) -> [a] -> IO [b] parProcessWorkStealing _ [] = pure [] parProcessWorkStealing f items = do numCaps <- getNumCapabilities let !numWorkers = max 1 numCaps- deques <- mapM newChaseLevDeque [0 .. numWorkers - 1]- let indexedItems = zip ([0..] :: [Int]) items+ !totalItems = length items+ deques <- V.generateM numWorkers newChaseLevDeque+ resultsVec <- MV.new totalItems - -- Distribute initial work across capability deques- forM_ indexedItems $ \(idx, item) -> do+ -- Distribute initial work across capability deques in O(N)+ forM_ (zip ([0..] :: [Int]) items) $ \(idx, item) -> do let !target = idx `rem` numWorkers- pushBottom (deques !! target) (idx, item)-- resultsRef <- newIORef ([] :: [(Int, b)])+ pushBottom (deques V.! target) (idx, item) let workerLoop !wId = do- let localDeque = deques !! wId- otherDeques = [deques !! j | j <- [0 .. numWorkers - 1], j /= wId]+ let !localDeque = deques V.! wId+ !otherDeques = [deques V.! j | j <- [0 .. numWorkers - 1], j /= wId] step localDeque otherDeques - step localDeque otherDeques = do+ step !localDeque otherDeques = do mTask <- popBottom localDeque case mTask of Just (idx, item) -> do !res <- f item- atomicModifyIORef' resultsRef (\acc -> ((idx, res) : acc, ()))+ MV.unsafeWrite resultsVec idx res step localDeque otherDeques Nothing -> do stolen <- trySteal otherDeques@@ -185,10 +202,10 @@ forM_ restTasks (pushBottom localDeque) let (idx, item) = firstTask !res <- f item- atomicModifyIORef' resultsRef (\acc -> ((idx, res) : acc, ()))+ MV.unsafeWrite resultsVec idx res step localDeque otherDeques [] -> do- allEmpty <- allM isDequeEmpty deques+ allEmpty <- allDequesEmpty 0 if allEmpty then pure () else do@@ -202,15 +219,15 @@ then trySteal ds else pure batch - allM _ [] = pure True- allM p (x:xs) = do- b <- p x- if not b then pure False else allM p xs+ allDequesEmpty !i+ | i >= numWorkers = pure True+ | otherwise = do+ empty <- isDequeEmpty (deques V.! i)+ if not empty then pure False else allDequesEmpty (i + 1) _ <- forConcurrently [0 .. numWorkers - 1] workerLoop- results <- readIORef resultsRef- -- Canonical sort ensures deterministic output ordering matching input stream- pure $ map snd (sortBy (comparing fst) results)+ frozen <- V.unsafeFreeze resultsVec+ pure (V.toList frozen) -- | Alias for 'parProcessWorkStealing'. parWorkStealing :: (a -> IO b) -> [a] -> IO [b]
src/Canontra/Repository/Repository.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE BangPatterns #-} {- | Module : Canontra.Repository.Repository Description : Deterministic polyglot repository traversal and aggregated Merkle fingerprinting.@@ -6,7 +7,7 @@ By sorting file paths and aggregating individual structural fingerprints into a canonical tree hash (F_R), canontra guarantees that filesystem traversal order never affects the resulting repository identity across Python, JS, TS, Go, and Rust.-Includes cross-platform POSIX path normalization and incremental caching.+Includes cross-platform POSIX path normalization and incremental CNTR\x07 slab caching. -} module Canontra.Repository.Repository ( fingerprintDirectory@@ -21,13 +22,15 @@ , normalizePathCanonical ) where +import Control.Applicative ((<|>)) import Control.Exception (IOException, try) import Control.Monad (forM) import qualified Data.ByteString as BS-import qualified Data.ByteString.Char8 as BSC+import qualified Data.ByteString.Builder as BB import Data.Char (toLower) import Data.Either (partitionEithers)-import Data.List (foldl', sort)+import Data.List (sort)+import qualified Data.Map.Strict as Map import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.Text.Encoding as TE@@ -35,17 +38,29 @@ import System.FilePath ((</>), makeRelative, takeDirectory, takeExtension) import System.IO (hPutStrLn, stderr) -import Canontra.Security.Path (canonicalizeSafePath, checkResourceBounds, isSymlinkLoop, maxRecursionDepth)-import Canontra.Cache.Inode (getFileMetadata)-import Canontra.Cache.MerkleCache (defaultCachePath, insertCache, lookupCache, readMerkleCache, writeMerkleCache)-import Canontra.Cache.SlabV6 (loadRepoGraphsSlab, saveRepoGraphsSlab)-import Canontra.Fingerprint.Bundle (computeBundle)+import Canontra.Analysis.WholeRepoGraph+ ( FileGraphSummary+ , buildWholeRepoCallGraphFromSummaries+ , buildWholeRepoDataFlowFromSummaries+ , extractFileGraphSummary+ , toCSRCallGraph+ , toCSRDataFlowGraph+ )+import Canontra.Cache.Common (MerkleCache (..), MerkleCacheEntry (..))+import Canontra.Cache.Inode (FileMetadata (..), getFileMetadata)+import Canontra.Cache.MerkleCache (defaultCachePath, readMerkleCache)+import Canontra.Cache.SlabV6 (saveRepoGraphsSlab)+import Canontra.Cache.SlabV7 (SlabV7Entry (..), readAnySlabCacheForV7, writeSlabV7File)+import Canontra.Canonical.Serialize (canonicalizeWholeRepoCallGraph, canonicalizeWholeRepoDataFlow)+import Canontra.Canonical.StreamingHash (hashBuilderDirect)+import Canontra.Fingerprint.Bundle (computeBundleAndProgram, computeWholeRepoBundleFromHashes) import Canontra.Fingerprint.Source (hashBytes) import Canontra.Fingerprint.WholeRepoCallGraph (computeFWCG) import Canontra.Fingerprint.WholeRepoDataFlow (computeFWDF) import Canontra.IR.Program (Program) import Canontra.Normalize.Rules (engineName, engineVersion) import Canontra.Repository.Parallel (parFingerprintWithPrograms, parMapChunks)+import Canontra.Security.Path (canonicalizeSafePath, checkResourceBounds, isSymlinkLoop, maxRecursionDepth) import Canontra.Types repoGraphsCachePath :: FilePath -> FilePath@@ -58,22 +73,6 @@ createDirectoryIfMissing True (takeDirectory p) writeFile p (T.unpack (unFingerprint fwcg) ++ "\n" ++ T.unpack (unFingerprint fwdf)) -loadRepoGraphs :: FilePath -> IO (Maybe (Fingerprint, Fingerprint))-loadRepoGraphs rootDir = do- mSlab <- loadRepoGraphsSlab rootDir- case mSlab of- Just (c, d, _, _) -> pure (Just (c, d))- Nothing -> do- let p = repoGraphsCachePath rootDir- exists <- doesFileExist p- if not exists- then pure Nothing- else do- content <- readFile p- case lines content of- (c:d:_) -> pure (Just (Fingerprint (T.pack c), Fingerprint (T.pack d)))- _ -> pure Nothing- -- | Universal cross-platform canonical path normalization (POSIX forward slashes + case folding). normalizePathCanonical :: FilePath -> FilePath normalizePathCanonical = map (\c -> if c == '\\' then '/' else toLower c)@@ -116,30 +115,36 @@ } pure (Right manifest) else do- actualCache <- readMerkleCache cachePath- results <- parMapChunks (processFileCachedConcurrent rootDir actualCache) sortedRelPaths- let rawEntries = map fst results- (failures, fileEntries) = partitionEithers rawEntries- newEntries = [item | (Right _, Just item) <- results]- newCache = foldl' (\c (p, m, b) -> insertCache p m b c) actualCache newEntries+ (cachedMap, mCachedRepo) <- loadCacheForV7 cachePath+ results <- parMapChunks (processFileV7Concurrent rootDir cachedMap) sortedRelPaths+ let (failures, successes) = partitionEithers results+ fileEntries = [fe | (fe, _, _, _) <- successes]+ v7Entries = [v7 | (_, v7, _, _) <- successes]+ summaries = [sm | (_, _, sm, _) <- successes]+ anyDirty = any (\(_, _, _, dirty) -> dirty) successes mapM_ logFailure failures if null fileEntries && not (null sortedRelPaths) then case failures of (e:_) -> pure (Left e) [] -> pure (Left (ParseError rootDir 0 0 "No files could be parsed")) else do- writeMerkleCache cachePath newCache- let repoFp = computeRepositoryFingerprint fileEntries- mSaved <- if null newEntries then loadRepoGraphs rootDir else pure Nothing- (fwcg, fwdf) <- case mSaved of- Just graphs -> pure graphs- Nothing -> do- resProgs <- parFingerprintWithPrograms rootDir sortedRelPaths- let (_, succs) = partitionEithers resProgs- progs = [(normalizePathCanonical (fePath fe), p) | (fe, p) <- succs]- c = computeFWCG progs- d = computeFWDF progs- saveRepoGraphs rootDir c d+ let !repoFp = computeRepositoryFingerprint fileEntries+ !currentKeySet = Set.fromList [normalizePathCanonical (fePath fe) | fe <- fileEntries]+ !sameFileSet = currentKeySet == Map.keysSet cachedMap+ (!fwcg, !fwdf) <- case (not anyDirty && sameFileSet, mCachedRepo) of+ (True, Just (wrb, _, _))+ | not (T.null (unFingerprint (wrbCallGraph wrb)))+ && not (T.null (unFingerprint (wrbDataFlow wrb))) ->+ pure (wrbCallGraph wrb, wrbDataFlow wrb)+ _ -> do+ let !wcg = buildWholeRepoCallGraphFromSummaries summaries+ !wdf = buildWholeRepoDataFlowFromSummaries summaries+ !c = hashBytes (canonicalizeWholeRepoCallGraph wcg)+ !d = hashBytes (canonicalizeWholeRepoDataFlow wdf)+ (!cgCSR, _) = toCSRCallGraph wcg+ (!dfCSR, _) = toCSRDataFlowGraph wdf+ !wrb = computeWholeRepoBundleFromHashes repoFp c d+ writeSlabV7File cachePath v7Entries (Just (wrb, cgCSR, dfCSR)) pure (c, d) let manifest = RepositoryManifest { rmEngine = engineName@@ -154,33 +159,54 @@ logFailure err = hPutStrLn stderr $ "[Canontra Parse Warning] " ++ peFile err ++ ":" ++ show (peLine err) ++ ":" ++ show (peColumn err) ++ ": " ++ T.unpack (peReason err) - processFileCachedConcurrent rDir cache relPath = do+ loadCacheForV7 cPath = do+ exists <- doesFileExist cPath+ if not exists+ then pure (Map.empty, Nothing)+ else do+ bs <- BS.readFile cPath+ case readAnySlabCacheForV7 bs of+ Just res -> pure res+ Nothing -> do+ MerkleCache legacyMap <- readMerkleCache cPath+ let upgraded = Map.mapWithKey+ (\p (MerkleCacheEntry sz mt b) -> SlabV7Entry (FileMetadata p sz mt) b Nothing)+ legacyMap+ pure (upgraded, Nothing)++ processFileV7Concurrent :: FilePath -> Map.Map FilePath SlabV7Entry -> FilePath -> IO (Either ParseError (FileEntry, SlabV7Entry, FileGraphSummary, Bool))+ processFileV7Concurrent rDir cachedMap relPath = do let fullPath = rDir </> relPath normPath = normalizePathCanonical relPath mMeta <- getFileMetadata fullPath case mMeta of- Nothing -> do+ Just meta+ | Just entry <- Map.lookup normPath cachedMap <|> Map.lookup relPath cachedMap+ , fmSize (sv7Meta entry) == fmSize meta+ , fmMtime (sv7Meta entry) == fmMtime meta+ , Just summary <- sv7Summary entry ->+ let !metaNorm = meta { fmPath = normPath }+ !entryNorm = entry { sv7Meta = metaNorm }+ in pure (Right (FileEntry relPath (sv7Bundle entry), entryNorm, summary, False))+ _ -> do rawBytes <- BS.readFile fullPath let textContent = TE.decodeUtf8Lenient rawBytes- case computeBundle relPath rawBytes textContent of- Left err -> pure (Left err, Nothing)- Right b -> pure (Right (FileEntry relPath b), Nothing)- Just meta -> case lookupCache normPath meta cache of- Just cachedBundle ->- pure (Right (FileEntry relPath cachedBundle), Nothing)- Nothing -> do- rawBytes <- BS.readFile fullPath- let textContent = TE.decodeUtf8Lenient rawBytes- case computeBundle relPath rawBytes textContent of- Left err -> pure (Left err, Nothing)- Right b -> pure (Right (FileEntry relPath b), Just (normPath, meta, b))+ case computeBundleAndProgram relPath rawBytes textContent of+ Left err -> pure (Left err)+ Right (b, prog) ->+ let !summary = extractFileGraphSummary normPath prog+ !meta = case mMeta of+ Just m -> m { fmPath = normPath }+ Nothing -> FileMetadata normPath 0 0+ !v7Entry = SlabV7Entry meta b (Just summary)+ in pure (Right (FileEntry relPath b, v7Entry, summary, True)) computeRepositoryFingerprint :: [FileEntry] -> Fingerprint computeRepositoryFingerprint entries =- let pairs = [(normalizePathCanonical (fePath e), unFingerprint (f1Structural (feFingerprints e))) | e <- entries]+ let pairs = [(normalizePathCanonical (fePath e), unFingerprint (f4Composite (feFingerprints e))) | e <- entries] sortedPairs = sort pairs- serialized = BSC.pack $ concatMap (\(p, f) -> p ++ ":" ++ T.unpack f ++ ";") sortedPairs- in hashBytes serialized+ builder = foldMap (\(p, f) -> BB.string8 p <> BB.char8 ':' <> BB.byteString (TE.encodeUtf8 f) <> BB.char8 ';') sortedPairs+ in hashBuilderDirect builder -- | Compute whole-repository bundle combining F_R, F_WCG, F_WDF, and F_W4. computeWholeRepoBundle :: [(FilePath, Program)] -> [FileEntry] -> WholeRepoBundle
technicalSpecs.md view
@@ -1,9 +1,9 @@ # Canontra Technical Specifications System Architecture, Compiler Pipeline, and Identity Engine-Version: v0.3.0.0 (Release v0.3.0)+Version: v0.4.0.0 (Release v0.4.0) Author: Jash Thakkar & SymtraceLabs Engineering Team-Status: Production Specification+Status: Production Specification (`canontra snap` Harness in Alpha) ## 1. Architectural Philosophy and Design Principles @@ -57,24 +57,24 @@ * F_R: Repository topology and module dependency DAG digest. * F_W4: Root Merkle digest over the entire repository. -## 3. The Five Pillars of Semantic Canonicalization (v0.3.0 Engine)+## 3. The Five Pillars of Semantic Canonicalization (v0.4.0 Engine) -Version 0.3.0 introduces five foundational canonicalization and analysis pillars that close semantic divergence gaps across all supported languages:+Version 0.4.0 hardens and fuses the five semantic canonicalization pillars introduced in v0.3.0 across a single-pass `CanonicalProgram` representation (`toCanonicalProgram`) while adding ByteString-native lexing, `CNTR\x07` summary caching, and `F_R` composite sensitivity: -### Pillar 1: Complete Alpha-Equivalence Normalization (Canontra.Normalize.Alpha)+### Pillar 1: Language-Specific Alpha-Equivalence Normalization (Canontra.Normalize.Alpha) -Local variable naming in private function scopes is an implementation detail. Canontra canonicalizes all bound local variable references into a deterministic, scope-aware de Bruijn coordinate: `@v<depth>.<ordinal>`.+Local variable naming in private function scopes is an implementation detail. Canontra canonicalizes all bound local variable references into a deterministic, scope-aware de Bruijn coordinate (`@v<depth>.<ordinal>`) via `canonicalizeAlphaModuleForLang`: -* Scope Hierarchy: Each nested lexical block (loops, conditionals, closures, comprehensions) increments scope depth.+* Scope Hierarchy: Each nested lexical block (loops, conditionals, closures, comprehensions) increments scope depth, while respecting Rust sequential `let` shadowing, Go `:=` block redeclaration rules, JavaScript `var` function hoisting, and Python LEGB + PEP 572 walrus scoping. * Ordinal Allocation: Local variable declarations within a scope are assigned ascending ordinal indices based on their textual declaration order. * Parameter and Shadow Isolation: Parameter bindings and shadowed variables are resolved deterministically against their nearest enclosing lexical scope. * Invariance Guarantee: Renaming any local variable across its definition and use sites produces a bit-identical AST and identical F1 digest. -### Pillar 2: Algebraic Normal Form and Operator Simplification (Canontra.Normalize.Algebraic)+### Pillar 2: Algebraic Normal Form and IEEE-754 / Trapping Guards (Canontra.Normalize.Algebraic) -Syntactic variations in expression phrasing frequently mask identical underlying computation. Canontra applies purity-guarded algebraic rewrites:+Syntactic variations in expression phrasing frequently mask identical underlying computation. Canontra applies purity-guarded algebraic rewrites protected by `isNonTrappingPureExpr` and `containsFloatOperand`: -* Commutative and Associative Sorting: Pure operands of commutative operators (`+`, `*`, `&&`, `||`, `==`, `!=`, `&`, `|`, `^`) are sorted lexicographically by normalized operand representation.+* Commutative and Associative Sorting: Pure non-trapping integer/bitwise operands of commutative operators (`+`, `*`, `&`, `|`, `^`, `==`, `!=`) are sorted lexicographically by normalized operand representation (`hashExprB`), while suppressing associative re-parenthesization when `containsFloatOperand` detects IEEE-754 floating-point operands or potentially trapping/short-circuiting expressions. * Relational Dual Inversion: Greater-than relational expressions are canonicalized to less-than relational forms by transposing operands: `b > a` normalizes to `a < b`, and `b >= a` normalizes to `a <= b`. * Double-Negation Elimination: Redundant boolean inversions are stripped: `not (not x)` simplifies to `x`. * Set and Dict Literal Ordering: Unordered collections containing pure elements or keys are sorted into canonical ascending sequence.@@ -83,27 +83,28 @@ Syntactically inverted conditional branches and guard clauses often generate disparate basic block layouts. Canontra canonicalizes the CFG topology: -* Dominator-Tree Canonicalization: Basic blocks are relabeled according to their depth and traversal index within the dominator tree.+* Dominator-Tree & Dominance Frontier Canonicalization: `computeDominators` and `computeDominanceFrontiers` construct canonical dominator hierarchies for basic blocks and SSA def-use normalization. * Reverse Post-Order (RPO) Indexing: Block IDs are reassigned based on a canonical RPO traversal from the function entry node. * Branch Inversion Normal Form: Branches testing inverted conditions with empty alternate suites (`if (!cond) A` versus `if (cond) ; else A`) are mapped to a uniform conditional structure. * Guard-Clause Lifting: Guard clauses featuring early returns (`if (!valid) return; doWork()`) are aligned with equivalent nested conditional topologies. -### Pillar 4: Deepened Structural Type Contract Lattice (Canontra.Analysis.TypeContract)+### Pillar 4: Hardened Structural Type Contract Lattice (Canontra.Analysis.TypeContract) Structural contracts determine whether interface changes break downstream consumers. Canontra formalizes type analysis into a structural subtyping lattice: -* Recursive ANF Type Flattening: Nested composite types, intersection types, and union types are flattened into canonical A-Normal Form.+* Exact ABI Scalar Widths, Mutability & Ordered Tuples: Preserves distinction between fixed-width ABI types (e.g., `i32` vs `u64`, `f32` vs `f64`), reference mutability (`Mutability`, e.g., `&T` vs `&mut T`), and positional tuple layouts (`(A, B)` vs `(B, A)`).+* Recursive ANF Type Flattening: Nested composite types, intersection types, and union types are flattened into canonical A-Normal Form (`makeUnion`, `makeIntersection`). * Structural Subtyping Evaluation: Determines width subtyping (excess fields permitted), depth subtyping (covariant returns, contravariant parameters), and union inclusion ($A \subseteq A \cup B$). * Generic Type Parameter Normalization: Generic parameters are normalized to ordinal alpha variables (`[T, U]` maps to `[α0, α1]`) across Python PEP 695, TypeScript generics, Go interfaces, and Rust traits. * Tuple Bound and Tilde Constraint Normalization: Structural constraints like Go `~int | ~float64` or Python `(int, float)` bounds are sorted and deduplicated. -### Pillar 5: CSR-Native PR Batch Impact Analysis (Canontra.Analysis.BatchImpact, Canontra.Analysis.Impact)+### Pillar 5: Whole-Repo Package Resolution & CSR Batch Impact Analysis (Canontra.Analysis.WholeRepoGraph, Canontra.Analysis.BatchImpact) -For continuous integration workflows, Canontra provides fast, multi-file change impact analysis directly over unboxed Compressed Sparse Row (CSR) call graphs:+For continuous integration workflows and monorepos, Canontra builds whole-repository graphs over unboxed Compressed Sparse Row (CSR) matrices: -* Batch Reachability Cones: Given a set of modified files in a Pull Request, Canontra maps changed symbols to CSR node indices and executes a multi-source bitset BFS reachability traversal.-* PR Base Diffing: The `canontra impact --pr-base <branch>` command inspects `git diff --name-only` against the PR base branch, runs incremental analysis, and outputs the affected downstream symbol blast radius.-* Machine-Readable Manifests: Emits structured JSON impact manifests detailing direct changes, transitively impacted symbols, and impacted test suites.+* Per-File Graph Summary Synthesis (`FileGraphSummary`): Each parsed module emits a compact binary `FileGraphSummary` cached in `CNTR\x07`, allowing `buildWholeRepoCallGraphFromSummaries` and `buildWholeRepoDataFlowFromSummaries` to synthesize repo graphs without retaining full ASTs for untouched files.+* Package Directory & Barrel Resolution: Merges Go package directory symbols, resolves TypeScript/JavaScript barrel re-exports, eliminates blind name-only false edges, and folds composite `F4` digests into the repository Merkle root `F_R`.+* Batch Reachability Cones: Given a set of modified files in a Pull Request, Canontra maps changed symbols to CSR node indices and executes a multi-source bitset BFS reachability traversal via `canontra impact --pr-base <branch>`. ## 4. End-to-End Compiler Pipeline Flow @@ -151,17 +152,17 @@ - Construct 9-tier FingerprintBundle | v-Phase 7: Radix-Directed Binary Caching (CNTR v6)+Phase 7: Radix-Directed Incremental Slab Caching (CNTR v7) - 4KB paged slab storage with IEEE 802.3 CRC-32C checksums- - 256-way L1 radix jump table for < 500 ns warm lookups- - Unboxed CSR graph persistence+ - Per-file FileGraphSummary binary payloads for warm graph synthesis+ - Transparent read-upgrade support for CNTR\x06 / CNTR\x05 - Resilient atomic file swapping with retry | v-Phase 8: Machine Interchange, Impact Analysis & Diagnostics+Phase 8: Machine Interchange, Impact Analysis & AI Harness Snaps - PR Batch Change Impact Analysis (CSR reachability)- - OASIS SARIF v2.1.0 diagnostics generation- - Graphviz DOT call graph export+ - Stateless AI harness sub-versioning (canontra snap, 0.1-alpha)+ - OASIS SARIF v2.1.0 diagnostics & Graphviz DOT export - Shell autocompletions and POSIX exit code reporting ``` @@ -225,26 +226,19 @@ The serialized canonical byte streams are hashed using NIST-standard SHA-256 via optimized primitives in `cryptohash-sha256`. The resulting 256-bit hashes are packaged into the `FingerprintBundle` structure. -### Phase 7: Radix-Directed Binary Slab Caching (CNTR v6)--Fingerprint manifests and Merkle DAG states are saved to a binary cache file (`.canontra/cache.bin`). The CNTR v6 (`CNTR\x06`) layout uses cache-line-aligned slab pages:+### Phase 7: Incremental Binary Slab Caching (`CNTR\x07`, `Canontra.Cache.SlabV7`) -* Magic Header (16 bytes): `CNTR\x06` magic identifier and cache version.-* 256-Way L1 Radix Jump Table (`0x0020 - 0x081F`, 2,048 bytes): Provides 1-cycle CPU fast-path indexing for warm file lookups.-* 64-Byte Cache Records: Fixed-width `CacheRecordV6` aligned to CPU cache lines, containing 64-bit device/file IDs, nanosecond modification timestamps, and all orthogonal cryptographic digests.-* Zero-Copy Memory-Mapped Retrieval: `lookupSlabBinaryBS` and `lookupSlabCacheWarm` execute in sub-microsecond latency (< 500 ns per file).-* Whole-Repository Binary CSR Graph Persistence: Saves compacted CSR call graphs and data-flow matrices (`saveRepoGraphsSlab`) with zero textual formatting overhead.-* Isolated 4KB Page Recovery: Every 4KB page maintains an independent IEEE 802.3 CRC-32C checksum (`salvageSlabCacheFile`). Damaged pages are isolated while valid entries remain instantly accessible.-* Atomic Write Swapping with Windows Resiliency: Staged cache writes are finalized via atomic rename with exponential backoff and jitter (`atomicSwapWithRetry`), eliminating Windows Defender and SearchIndexer file-locking conflicts.+Fingerprint manifests and per-file `FileGraphSummary` records are persisted to `.canontra/cache.bin`. The `CNTR\x07` layout stores 64-byte cache-line-aligned file metadata and all 9 cryptographic digests alongside compact binary call/data-flow summaries inside 4KB CRC-32C protected pages (with multi-page spanning for large modules and resilient recovery via `decodeSlabV7Resilient` / `readSlabV7FileResilient`). Writes use staged temporary files swapped via `atomicSwapWithRetry` / `atomicSwapWithRetry_` to eliminate Windows Defender and SearchIndexer sharing violations. -### Phase 8: Machine Interchange, Impact Analysis and Reporting+### Phase 8: Machine Interchange, Impact Analysis & Stateless AI Harness Sub-Versioning -The final phase exposes findings through standard formats:+The final phase exposes semantic findings and turn-level workspace checkpoints: * Pull Request Change Impact Analysis: Calculates blast radius, affected symbols, and downstream tests via `canontra impact --pr-base <branch>`.+* Stateless AI Harness Sub-Versioning (`canontra snap` — Alpha, `schema_version: "0.1-alpha"`): Implemented in `Canontra.Harness.Store`, `Canontra.Harness.SubVersion`, and `Canontra.Harness.Guard`, storing SHA-256 content-addressed `F0` objects, JSON manifests, `HEAD`, and `ledger.jsonl` under `.canontra/snaps/` with preflight path-containment and hash verification prior to `snap rewind`. See [HARNESS.md](HARNESS.md). * OASIS SARIF v2.1.0 JSON format for GitHub Code Scanning, SonarQube, and CI dashboards. * Graphviz DOT format for visualizing call graphs, CFGs, and DFGs.-* Strict POSIX exit codes (0 for identical, 1 for changed, 2 for CLI error, 3 for parse error, 4 for I/O or security violation).+* Strict POSIX exit codes (`0` for identical/pass, `1` for changed/guard fail, `2` for CLI error, `3` for parse error, `4` for I/O or security violation). ## 5. Formal Verification and Determinism Theorems
test/Canontra/MetamorphicSpec.hs view
@@ -1367,9 +1367,9 @@ -- ----------------------------------------------------------------------- describe "Gate 1: Scope-Aware Bound Lexical Alpha-Canonicalization" $ do - it "verifies engineVersion and normalizationVersion are bumped to 0.3.0" $ do- engineVersion `shouldBe` "0.3.0"- normalizationVersion `shouldBe` "0.3.0"+ it "verifies engineVersion and normalizationVersion are bumped to 0.4.0" $ do+ engineVersion `shouldBe` "0.4.0"+ normalizationVersion `shouldBe` "0.4.0" it "identifies canonical bound de Bruijn identifiers via isCanonicalBoundId" $ do isCanonicalBoundId "@v1.0" `shouldBe` True