-- | The driver: from files to an analysed program. It loads the given files, follows their -- dependencies (with clauses, parents, specifications) through the project's source -- directories and the predefined library, orders the units so that every specification -- comes before its users, and runs Sema on the units whose sources parsed cleanly. module Verada.Driver ( CheckOutcome (..) , FileNameRepair (..) , sourceFileNameRepairs , LibrarySession , Project (..) , SessionExtension (..) , SessionUnit (..) , addSessionSource , checkSources , checkSourcesWith , checkSourcesWithAplScope , checkSourcesWithAplOrigin , checkSourceSnapshot , checkSourceSnapshotWithAplScope , checkSourceSnapshotWithAplOrigin , extendSession , newLibrarySession , sessionSources , readProjectFile , parseProjectFile , ProofSettings (..) , Purpose (..) , readProofSettings , parseProofSettings , checkSourcesFor ) where import Verada.Diagnostics (Diagnostic (..), Label (..), Note (..), Phase (..), diagnostic, isError, label) import Verada.Diagnostics.Codes (DiagCode (..)) import Verada.Diagnostics.Excluded (Instead (..), excludedUnit, vibeInstead, varcInstead) import Verada.Frontends (parseFile) import Verada.Vibe.Token qualified as Vibe import Verada.Varc.Instances (isImplicitInstance) import Verada.Library.Predefined (predefinedFile) import Verada.Library.Unit (Dependency (..), dependenciesWith, dottedName, specFileName, unitFileName, unitFileNames, unitIdentity, unitNameSpan) import Verada.Result (Result (..)) import Verada.Sema (ParsedUnit (..), TypedAplOrigin, analyseWithAplScope, analyseWithAplOrigin) import Verada.Sema.Check.Expr (orderedMethods) import Verada.Source (FileId, SourceFile (..), SourceMap, Span (..), addSource, emptySourceMap, lookupSource, sourceFiles) import Verada.Syntax.AST.Decl qualified as AD import Verada.Syntax.AST.Expr qualified as AE import Verada.Syntax.AST.Stmt qualified as AS import Verada.Syntax.AST.Type qualified as AT import Verada.Syntax.AST.Unit (CompilationUnit (..), ContextItem (..), LibraryItem (..), Subunit (..), UnitBody (..), WithClause (..)) import Verada.Syntax.Apl.Runtime (aplRuntimeWith) import Verada.Syntax.Generic (everythingWith) import Verada.Syntax.Tasking (desugarTasking, taskingNode) import Verada.TAST.Ids (UnitId (..)) import Verada.TAST.Unit (Program, UnitKind (..)) import Verada.Translate (pruneUnusedVibeVectorsUnits) import Control.Applicative ((<|>)) import Control.Exception (IOException, displayException, try) import Control.Monad (filterM, foldM) import Data.ByteString (ByteString) import Data.Data (Data, cast, gmapQ, gmapT) import Data.ByteString qualified as ByteString import Data.List (find, isPrefixOf, nub, nubBy, unsnoc) import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe, mapMaybe) import Data.Set qualified as Set import Data.Text (Text) import Data.Text qualified as Text import Data.Text.Encoding (decodeUtf8Lenient) import System.Directory (canonicalizePath, doesFileExist) import System.FilePath (normalise, takeBaseName, takeDirectory, takeExtension, takeFileName, ()) import TOML (TOMLError, decodeWith, getFieldsOpt, renderTOMLError) data Project = Project { sourceDirs :: [FilePath] , cSources :: [FilePath] -- ^ C files compiled with the program and linked into it (or loaded by the JIT) } isVibePath :: FilePath -> Bool isVibePath p = takeExtension p `elem` [".vb", ".py"] -- | @verada.toml@: @[project] source-dirs = ["src"]@ and @c-sources = ["c/io.c"]@ (relative -- to the file's directory). readProjectFile :: FilePath -> IO (Either Diagnostic Project) readProjectFile path = try @IOException (ByteString.readFile path) >>= \case Left e -> pure (Left (projectFileError path (Text.pack (displayException e)))) Right bytes -> pure (parseProjectFile path bytes) -- | Parse already captured configuration bytes, so an agent operation does not silently -- reread a newer configuration while checking the requested source snapshot. parseProjectFile :: FilePath -> ByteString -> Either Diagnostic Project parseProjectFile path bytes = case (field "source-dirs", field "c-sources") of (Left err, _) -> Left (projectError (compactError (renderTOMLError err))) (_, Left err) -> Left (projectError (compactError (renderTOMLError err))) (Right dirs, Right cs) -> Right Project {sourceDirs = relative (fromMaybe ["."] dirs), cSources = relative (fromMaybe [] cs)} where field :: Text -> Either TOMLError (Maybe [Text]) field name = decodeWith (getFieldsOpt ["project", name]) (decodeUtf8Lenient bytes) relative = map ((takeDirectory path ) . Text.unpack) projectError = projectFileError path projectFileError :: FilePath -> Text -> Diagnostic projectFileError path why = (diagnostic InvalidProjectFile Driver ("cannot use project file `" <> Text.pack path <> "`")) { notes = [Note {text = why, span = Nothing}] , advice = Just "a project file looks like: [project] source-dirs = [\"src\"]" } -- | A project's proof settings (D76): `[proof] budget = "standard"` and -- `[proof.budget-overrides] "Unit.Subprogram" = "thorough"`, as written (the budgets' names -- are checked where they are used). data ProofSettings = ProofSettings { budget :: Maybe Text , overrides :: Map Text Text , certificates :: Maybe Bool -- ^ `[proof] certificates = true`: read and write `.verada/certs` (D92) , solverMemory :: Maybe Integer -- ^ `[proof] solver-memory`: each solver process's memory, in MB (D185) , queryCeiling :: Maybe Integer -- ^ `[proof] query-ceiling`: the largest query given a solver, in MB (D185) } readProofSettings :: FilePath -> IO (Either Diagnostic ProofSettings) readProofSettings path = try @IOException (ByteString.readFile path) >>= \case Left e -> pure (Left (proofFileError path (Text.pack (displayException e)))) Right bytes -> pure (parseProofSettings path bytes) parseProofSettings :: FilePath -> ByteString -> Either Diagnostic ProofSettings parseProofSettings path bytes = let source = decodeUtf8Lenient bytes size key = decodeWith (getFieldsOpt ["proof", key]) source in case (decodeWith (getFieldsOpt ["proof", "budget"]) source, decodeWith (getFieldsOpt ["proof", "budget-overrides"]) source, decodeWith (getFieldsOpt ["proof", "certificates"]) source, size "solver-memory", size "query-ceiling") of (Left err, _, _, _, _) -> Left (proofError (compactError (renderTOMLError err))) (_, Left err, _, _, _) -> Left (proofError (compactError (renderTOMLError err))) (_, _, Left err, _, _) -> Left (proofError (compactError (renderTOMLError err))) (_, _, _, Left err, _) -> Left (proofError (compactError (renderTOMLError err))) (_, _, _, _, Left err) -> Left (proofError (compactError (renderTOMLError err))) (Right b, Right os, Right c, Right m, Right q) | any (maybe False (<= 0)) [m, q] -> Left (proofError "`solver-memory` and `query-ceiling` are sizes in MB, above 0") | otherwise -> Right ProofSettings {budget = b, overrides = fromMaybe Map.empty os, certificates = c, solverMemory = m, queryCeiling = q} where proofError = proofFileError path proofFileError :: FilePath -> Text -> Diagnostic proofFileError path why = (diagnostic InvalidProjectFile Driver ("cannot use the proof settings of `" <> Text.pack path <> "`")) { notes = [Note {text = why, span = Nothing}] , advice = Just "proof settings look like: [proof] budget = \"standard\"" } -- | A TOML error on one line: its position and its message, without the source excerpt. compactError :: Text -> Text compactError t = Text.intercalate " " (filter keep (map Text.strip (Text.lines t))) where keep l = not (Text.null l) && not ("|" `Text.isInfixOf` l) data CheckOutcome = CheckOutcome { sources :: SourceMap , diagnostics :: [Diagnostic] , program :: Maybe Program } -- | The structured file operation behind B1007. Explicit library declarations -- keep their identity; only a filename-derived Vibe module may change identity. -- This is computed from the same loaded units as the warning, never its prose. data FileNameRepair = FileNameRepair { path :: FilePath , target :: FilePath , oldName :: Text , newName :: Text , implicitModule :: Bool } deriving stock (Eq, Show) sourceFileNameRepairs :: FilePath -> ByteString -> [FileNameRepair] sourceFileNameRepairs path bytes = nub (mapMaybe fileNameRepair (Map.elems loaded.units)) where loaded = loadBytes True LoadState {sourceMap = emptySourceMap, reports = [], units = Map.empty, attempted = Set.empty, overlay = Map.empty, purpose = ForCode} path bytes -- | A unit read from a file. data Loaded = Loaded { name :: Text , kind :: UnitKind , unit :: CompilationUnit , path :: FilePath , explicit :: Bool , broken :: Bool -- ^ its file had syntax errors , dependsOn :: [Dependency] -- ^ the unit's dependencies, worked out once (loading asks for them again at every step) , instantiates :: [Text] -- ^ the generics it instantiates or renames, by name, worked out once } -- | A loaded unit, its dependencies and the generics it names left to be worked out when -- first asked for. loadedUnit :: Text -> UnitKind -> CompilationUnit -> FilePath -> Bool -> Bool -> Loaded loadedUnit name kind unit = loadedWith (unitFacts unit) name kind unit loadedWith :: UnitFacts -> Text -> UnitKind -> CompilationUnit -> FilePath -> Bool -> Bool -> Loaded loadedWith facts name kind unit path explicit broken = Loaded {name, kind, unit, path, explicit, broken, dependsOn = dependenciesWith facts.attributes unit, instantiates = facts.generics} -- | What loading needs to know of a unit's text, found in one traversal of it. data UnitFacts = UnitFacts { generics :: [Text] -- ^ the generics it instantiates or renames, by name , attributes :: [Text] -- ^ the attributes it names, case-folded , tasking :: Bool -- ^ whether it has tasks, protected objects or delays , codeStrings :: [AE.CodeString] } unitFacts :: CompilationUnit -> UnitFacts unitFacts u = UnitFacts { generics = mapMaybe dottedName [e | FactGeneric e <- found] <> concat [implied k | FactForm k <- found] , attributes = [a | FactAttribute a <- found] , tasking = or [True | FactTasking <- found] , codeStrings = [c | FactCode c <- found] } where found = everythingWith fact u -- (and those Sema instantiates for a surface form: Vibe's `xs.sort()` is a vector's -- `Generic_Sort`) implied :: AE.SurfaceFormKind -> [Text] implied = \case AE.FormMethod m _ -> maybe [] pure (lookup (Text.toLower m.text) orderedMethods) _ -> [] data Fact = FactGeneric AE.Expr | FactForm AE.SurfaceFormKind | FactAttribute Text | FactTasking | FactCode AE.CodeString fact :: forall d. (Data d) => d -> [Fact] fact x | Just (i :: AD.Instantiation) <- cast x = [FactGeneric i.generic] | Just (r :: AD.GenericRenaming) <- cast x = [FactGeneric r.renamed] | Just (f :: AD.FormalPackage) <- cast x = [FactGeneric f.generic] | Just (k :: AE.SurfaceFormKind) <- cast x = [FactForm k] | Just (a :: AE.AttributeRef) <- cast x = [FactAttribute (Text.toCaseFold a.designator.text)] | Just (c :: AE.CodeString) <- cast x = [FactCode c] | taskingNode x = [FactTasking] | otherwise = [] type Key = (Text, UnitKind) keyOf :: Loaded -> Key keyOf l = (Text.toCaseFold l.name, l.kind) data LoadState = LoadState { sourceMap :: SourceMap , reports :: [Diagnostic] , units :: Map Key Loaded , attempted :: Set.Set Text , overlay :: Map FilePath ByteString -- ^ files' contents held in memory (an editor's unsaved buffers), read instead of disk , purpose :: Purpose } -- | What the loaded units are for. Code needs every body; legality, flow and proof need a -- predefined unit's body only where its specification does not say all that its callers -- see (a generic's body, which its instances are made from; a subprogram without a stated -- `Global`, whose effects flow analysis takes from its body). The predefined library's -- bodies are proved apart and trusted, so analysing them again for each program, most of a -- small program's check, is left out. data Purpose = ForCode | ForAnalysis deriving stock (Eq, Show) checkSources :: Project -> [FilePath] -> IO CheckOutcome checkSources project = checkSourcesWith project Map.empty -- | Check sources, reading the files held in memory instead of their saved contents. checkSourcesWith :: Project -> Map FilePath ByteString -> [FilePath] -> IO CheckOutcome checkSourcesWith project buffers files = checkSourcesWithAplScope project buffers files Nothing -- | Check sources for a purpose: 'ForAnalysis' leaves out the predefined bodies that -- analysis does not need (see 'Purpose'); the program then has no code for them. checkSourcesFor :: Purpose -> Project -> Map FilePath ByteString -> [FilePath] -> IO CheckOutcome checkSourcesFor purpose project buffers files = fst <$> checkSourcesWithInspectionFor purpose project buffers files Nothing Nothing -- | Scope discovery is opt-in and limited to one selected expression. Ordinary -- checks and serialized interfaces do not duplicate every lexical environment. checkSourcesWithAplScope :: Project -> Map FilePath ByteString -> [FilePath] -> Maybe (FilePath, Int) -> IO CheckOutcome checkSourcesWithAplScope project buffers files scopeAt = fst <$> checkSourcesWithInspection project buffers files scopeAt Nothing checkSourcesWithAplOrigin :: Project -> Map FilePath ByteString -> [FilePath] -> Maybe (FilePath, Int) -> (Int, Int) -> IO (CheckOutcome, Either Text [TypedAplOrigin]) checkSourcesWithAplOrigin project buffers files scopeAt selection = checkSourcesWithInspection project buffers files scopeAt (Just selection) checkSourcesWithInspection :: Project -> Map FilePath ByteString -> [FilePath] -> Maybe (FilePath, Int) -> Maybe (Int, Int) -> IO (CheckOutcome, Either Text [TypedAplOrigin]) checkSourcesWithInspection = checkSourcesWithInspectionFor ForCode checkSourcesWithInspectionFor :: Purpose -> Project -> Map FilePath ByteString -> [FilePath] -> Maybe (FilePath, Int) -> Maybe (Int, Int) -> IO (CheckOutcome, Either Text [TypedAplOrigin]) checkSourcesWithInspectionFor purpose project buffers files scopeAt originSelection = do explicitState <- foldM (loadPath True) LoadState {sourceMap = emptySourceMap, reports = [], units = Map.empty, attempted = Set.empty, overlay = buffers, purpose} files let dirs = nub (map takeDirectory files <> project.sourceDirs) -- (with the bodies beside the specs, a spec named on the command line's too: proving a -- spec proves its body) -- (and the generic bodies that the subunits' instances need) st0 <- withBodies dirs Set.empty =<< closure dirs explicitState st <- withGenericBodies dirs =<< withSubunits dirs =<< withGenericBodies dirs (pruneUnusedVibeVectors st0) pure (finishCheckWithInspection scopeAt originSelection st) -- | Recheck a complete source snapshot without consulting disk or discovering -- newer dependencies. The caller supplies the exact sources from a previous -- check, including any predefined units that were used. Missing dependencies -- remain errors instead of being filled from another revision. checkSourceSnapshot :: [(FilePath, ByteString)] -> CheckOutcome checkSourceSnapshot files = finishCheck (foldl (\st (path, bytes) -> loadBytes True st path bytes) initial files) where initial = LoadState {sourceMap = emptySourceMap, reports = [], units = Map.empty, attempted = Set.empty, overlay = Map.empty, purpose = ForCode} checkSourceSnapshotWithAplScope :: [(FilePath, ByteString)] -> (FilePath, Int) -> CheckOutcome checkSourceSnapshotWithAplScope files scopeAt = finishCheckWithAplScope (Just scopeAt) (foldl (\st (path, bytes) -> loadBytes True st path bytes) initial files) where initial = LoadState {sourceMap = emptySourceMap, reports = [], units = Map.empty, attempted = Set.empty, overlay = Map.empty, purpose = ForCode} checkSourceSnapshotWithAplOrigin :: [(FilePath, ByteString)] -> (FilePath, Int) -> (Int, Int) -> (CheckOutcome, Either Text [TypedAplOrigin]) checkSourceSnapshotWithAplOrigin files scopeAt selection = finishCheckWithInspection (Just scopeAt) (Just selection) (foldl (\st (path, bytes) -> loadBytes True st path bytes) initial files) where initial = LoadState {sourceMap = emptySourceMap, reports = [], units = Map.empty, attempted = Set.empty, overlay = Map.empty, purpose = ForCode} finishCheck :: LoadState -> CheckOutcome finishCheck = finishCheckWithAplScope Nothing finishCheckWithAplScope :: Maybe (FilePath, Int) -> LoadState -> CheckOutcome finishCheckWithAplScope scopeAt = fst . finishCheckWithInspection scopeAt Nothing finishCheckWithInspection :: Maybe (FilePath, Int) -> Maybe (Int, Int) -> LoadState -> (CheckOutcome, Either Text [TypedAplOrigin]) finishCheckWithInspection scopeAt originSelection st0 = let st = pruneUnusedVibeVectors st0 spliced = propagateVibeModes (spliceSubunits st.units) ordered = order spliced usable = cleanUnits spliced -- a body sees the context clause of its spec (RM 10.1.4), and a child unit the with -- clauses of its ancestors' specs (their scope includes the children, RM 10.1.2(5)) specContext l = ancestorWiths ordered.units l <> concat [s.unit.context | l.kind == UnitBody, s <- ordered.units, s.kind == UnitSpec, s.name == l.name] parsed = [ParsedUnit {unitId = UnitId i, name = l.name, kind = l.kind, unit = l.unit, inheritedContext = specContext l, session = [], python = isVibePath l.path, varc = takeExtension l.path == ".va", predefined = "/" `isPrefixOf` l.path} | (i, l) <- zip [0 ..] ordered.units, keyOf l `Set.member` usable] mismatches = concatMap fileNameMismatch (Map.elems st.units) selected = do (path, offset) <- scopeAt sf <- find (\f -> normalise f.path == normalise path) (sourceFiles st.sourceMap) pure (Span sf.fileId offset offset) (semantic, origins) = if null parsed then (Result {diagnostics = [], value = Nothing}, Right []) else case originSelection of Nothing -> (analyseWithAplScope selected parsed, Right []) Just selection -> analyseWithAplOrigin selected selection parsed in (CheckOutcome { sources = st.sourceMap , diagnostics = reverse st.reports <> mismatches <> ordered.cycles <> filter (not . pythonUnchanged st.sourceMap) semantic.diagnostics , program = semantic.value }, origins) -- | B8005 in a Vibe file: Vibe infers constness, so a local that never changes is already a -- constant there, and there is nothing to write (vibe-syntax LN21). pythonUnchanged :: SourceMap -> Diagnostic -> Bool pythonUnchanged sources d = d.code == NeverChanged && maybe False (\l -> maybe False (\sf -> isVibePath sf.path) (lookupSource sources l.span.file)) d.primary -- * REPL sessions -- | The library units a REPL session has loaded (append-only: a unit loaded once keeps its -- place, so that code compiled for it earlier stays valid). data LibrarySession = LibrarySession { state :: LoadState , loaded :: Set.Set Key , nextUnit :: Int } newLibrarySession :: LibrarySession newLibrarySession = LibrarySession {state = LoadState {sourceMap = emptySourceMap, reports = [], units = Map.empty, attempted = Set.empty, overlay = Map.empty, purpose = ForCode}, loaded = Set.empty, nextUnit = 0} sessionSources :: LibrarySession -> SourceMap sessionSources s = s.state.sourceMap -- | Add a source text that is not a file (a REPL input). addSessionSource :: FilePath -> ByteString -> LibrarySession -> (FileId, LibrarySession) addSessionSource path bytes s = let (fid, sources) = addSource path bytes s.state.sourceMap in (fid, s {state = s.state {sourceMap = sources}}) -- | A unit a REPL input contributes. data SessionUnit = SessionUnit { name :: Text , kind :: UnitKind , unit :: CompilationUnit , keep :: Bool -- ^ a library unit the input brings (an implicit instance): the session keeps it from -- then on, and it is returned with the units loaded for the input } -- | A session extended for new session units: the session, the diagnostics of loading what -- they depend on, and those units for Sema. data SessionExtension = SessionExtension { session :: LibrarySession , diagnostics :: [Diagnostic] , units :: [ParsedUnit] } -- | The library units new session units depend on and the session has not loaded yet (with -- the units those depend on, from the project's source directories and the predefined -- library), in dependency order, as units for Sema; and the diagnostics of loading them. -- The session units themselves are not returned: the caller places them. extendSession :: Project -> LibrarySession -> [SessionUnit] -> IO SessionExtension extendSession project s items = do let own = [loadedUnit i.name i.kind i.unit "" False False | i <- items, not i.keep] brought = [loadedUnit i.name i.kind i.unit "" True False | i <- items, i.keep] ownKeys = Set.fromList (map keyOf own) start = LoadState {sourceMap = s.state.sourceMap, reports = [], units = foldl (\m l -> Map.insert (keyOf l) l m) s.state.units (brought <> own), attempted = s.state.attempted, overlay = Map.empty, purpose = ForCode} st <- withSubunits project.sourceDirs =<< withGenericBodies project.sourceDirs =<< withBodies project.sourceDirs ownKeys =<< closure project.sourceDirs start let ordered = order (spliceSubunits st.units) usable = cleanUnits st.units fresh = [l | l <- ordered.units, not (Set.member (keyOf l) s.loaded), not (Set.member (keyOf l) ownKeys), Set.member (keyOf l) usable] specContext l = ancestorWiths ordered.units l <> concat [x.unit.context | l.kind == UnitBody, x <- ordered.units, x.kind == UnitSpec, x.name == l.name] parsed = [ParsedUnit {unitId = UnitId i, name = l.name, kind = l.kind, unit = l.unit, inheritedContext = specContext l, session = [], python = isVibePath l.path, varc = takeExtension l.path == ".va", predefined = "/" `isPrefixOf` l.path} | (i, l) <- zip [s.nextUnit ..] fresh] -- the session's own units are not kept here: a rejected input leaves nothing behind kept = LoadState {sourceMap = st.sourceMap, reports = [], units = foldl (flip Map.delete) st.units (Set.toList ownKeys), attempted = st.attempted, overlay = st.overlay, purpose = st.purpose} pure SessionExtension { session = s {state = kept, loaded = foldl (flip Set.insert) s.loaded (map keyOf fresh), nextUnit = s.nextUnit + length fresh} , diagnostics = reverse st.reports , units = parsed } -- | The plain with clauses of the specs of a unit's ancestors (`P` and `P.Q` for `P.Q.R`). ancestorWiths :: [Loaded] -> Loaded -> [ContextItem] ancestorWiths units l = [ c | a <- ancestorNames l.name , s <- units , s.kind == UnitSpec , Text.toCaseFold s.name == Text.toCaseFold a , c@(ContextWith w) <- s.unit.context , not w.private ] where ancestorNames n = let parts = Text.splitOn "." n in [Text.intercalate "." (take k parts) | k <- [1 .. length parts - 1]] -- | Load the bodies of generic units (their instances need them), from the source -- directories or the predefined library, and what those bodies depend on. withGenericBodies :: [FilePath] -> LoadState -> IO LoadState withGenericBodies dirs st = case wanted of [] -> pure st l : _ -> do let marker = "generic body:" <> Text.toCaseFold l.name st' = st {attempted = Set.insert marker st.attempted} file = unitFileName l.name UnitBody onDisk <- filterM doesFileExist [dir f | dir <- dirs <> [takeDirectory l.path], f <- unitFileNames l.name UnitBody] next <- case (onDisk, predefinedFile file) of (p : _, _) -> closure dirs =<< loadPath False st' p ([], Just bytes) -> closure dirs (loadBytes False st' ("/" <> file) bytes) ([], Nothing) -> pure st' withGenericBodies dirs next where wanted = [ l | l <- Map.elems st.units , l.kind == UnitSpec , isGenericUnit l.unit -- (for analysis, a predefined generic's body only where its instances need it) , st.purpose == ForCode || not ("/" `isPrefixOf` l.path) || genericNeedsBody instantiated l.unit , not (Map.member (Text.toCaseFold l.name, UnitBody) st.units) , not (Set.member ("generic body:" <> Text.toCaseFold l.name) st.attempted) ] instantiated = instantiatedNames st isGenericUnit :: CompilationUnit -> Bool isGenericUnit u = case u.body of LibraryUnit LibraryItem {item = AD.Decl {node = AD.DGeneric _}} -> True LibraryUnit LibraryItem {item = AD.Decl {node = AD.DPackage p}} -> or [True | AD.Decl {node = AD.DGeneric _} <- p.visible] _ -> False -- * Subunits -- | Load the subunits the loaded units' stubs need (GNAT's file names, from the source -- directories), and theirs, until there are no more. withSubunits :: [FilePath] -> LoadState -> IO LoadState withSubunits dirs st = case wanted of [] -> pure st n : _ -> do let st' = st {attempted = Set.insert ("separate:" <> Text.toCaseFold n) st.attempted} onDisk <- filterM doesFileExist [dir f | dir <- dirs, f <- unitFileNames n UnitSubunit] -- (with what the subunit's own context clause names) next <- case onDisk of p : _ -> closure dirs =<< loadPath False st' p [] -> pure st' {reports = missingSubunit n : st'.reports} withSubunits dirs next where wanted = [ n | l <- Map.elems st.units , n <- stubNames l , not (Map.member (Text.toCaseFold n, UnitSubunit) st.units) , not (Set.member ("separate:" <> Text.toCaseFold n) st.attempted) ] missingSubunit n = (diagnostic UnknownUnit Driver ("no subunit `" <> n <> "` was found")) { notes = [Note {text = "looked for `" <> Text.pack (unitFileName n UnitSubunit) <> "` in the source directories", span = Nothing}] , advice = Just "a `separate` body goes in its own file, named after its parent unit and itself" } -- | The full names of the subunits a unit's stubs need: a stub in a body nested in the unit -- is named after that body too (`separate (Main.Inner)`, RM 10.1.3(8)). stubNames :: Loaded -> [Text] stubNames l = concatMap (stubsIn l.name True) (unitDeclarations l.unit) where stubsIn prefix top d = case d.node of AD.DBodyStub s -> [prefix <> "." <> n | Just n <- [stubName s]] AD.DSubprogramBody b -> concatMap (stubsIn (nestedPrefix prefix top b.spec.name) False) b.declarations AD.DPackageBody b -> concatMap (stubsIn (nestedPrefix prefix top b.name) False) b.declarations _ -> [] -- | The expanded name of a body nested in the unit named @prefix@ (the unit's own body when -- it is the top one). nestedPrefix :: Text -> Bool -> AE.Expr -> Text nestedPrefix prefix top n | top = prefix | otherwise = maybe prefix (\x -> prefix <> "." <> x) (dottedName n) stubName :: AD.BodyStub -> Maybe Text stubName s = case s.target of AD.StubSubprogram spec -> dottedName spec.name AD.StubPackage e -> dottedName e AD.StubTask i -> Just i.text AD.StubProtected i -> Just i.text unitDeclarations :: CompilationUnit -> [AD.Decl] unitDeclarations u = case u.body of LibraryUnit li -> [li.item] SubunitBody s -> [s.item] -- | Every body with its stubs replaced by the subunits' bodies, which take the place of the -- stubs (so they see what the stubs see); the subunits' context clauses join their -- parents'. The subunits are no longer units of their own. spliceSubunits :: Map Key Loaded -> Map Key Loaded spliceSubunits units -- (with no subunits, every unit is as it was loaded) | not (any (\l -> l.kind == UnitSubunit) units) = units | otherwise = Map.map splice (Map.filter (\l -> l.kind /= UnitSubunit) units) where splice l = let (decls, extra) = spliceIn l.name True (unitDeclarations l.unit) body = case (l.unit.body, decls) of (LibraryUnit li, d : _) -> LibraryUnit LibraryItem {private = li.private, item = d} (other, _) -> other in loadedUnit l.name l.kind CompilationUnit {span = l.unit.span, context = l.unit.context <> extra, body} l.path l.explicit l.broken spliceIn prefix top decls = let results = map (spliceDecl prefix top) decls in (map fst results, concatMap snd results) spliceDecl prefix top d = case d.node of AD.DBodyStub s | Just n <- stubName s , Just sub <- Map.lookup (Text.toCaseFold (prefix <> "." <> n), UnitSubunit) units , SubunitBody su <- sub.unit.body -> let (inner, extra) = spliceIn sub.name True [su.item] in case inner of i : _ -> (i, sub.unit.context <> extra) [] -> (d, []) AD.DSubprogramBody b -> let (ds, extra) = spliceIn (nestedPrefix prefix top b.spec.name) False b.declarations in (AD.Decl {span = d.span, node = AD.DSubprogramBody AD.SubprogramBody {spec = b.spec, aspects = b.aspects, declarations = ds, statements = b.statements, handlers = b.handlers, endName = b.endName}}, extra) AD.DPackageBody b -> let (ds, extra) = spliceIn (nestedPrefix prefix top b.name) False b.declarations in (AD.Decl {span = d.span, node = AD.DPackageBody AD.PackageBody {name = b.name, aspects = b.aspects, declarations = ds, statements = b.statements, handlers = b.handlers, endName = b.endName}}, extra) _ -> (d, []) -- | Load the bodies of the loaded specifications (the session runs their code), and what -- the bodies depend on, until there are no more. withBodies :: [FilePath] -> Set.Set Key -> LoadState -> IO LoadState withBodies dirs own st = case wanted of [] -> pure st l : _ -> do let marker = "body:" <> Text.toCaseFold l.name st' = st {attempted = Set.insert marker st.attempted} onDisk <- filterM doesFileExist [dir f | dir <- dirs, f <- unitFileNames l.name UnitBody] next <- case onDisk of p : _ -> closure dirs =<< loadPath False st' p [] -> pure st' withBodies dirs own next where wanted = [ l | l <- Map.elems st.units , l.kind == UnitSpec , not (Set.member (keyOf l) own) , not (Map.member (Text.toCaseFold l.name, UnitBody) st.units) , not (Set.member ("body:" <> Text.toCaseFold l.name) st.attempted) ] -- | Read and parse one file, adding its units. loadPath :: Bool -> LoadState -> FilePath -> IO LoadState loadPath explicit st0 given = do -- (named as written without `./` segments: `main.vadb`, not `././main.vadb`) let path = normalise given -- a file is read once (a Varc file holds a spec and a body, looked for separately), by -- whichever path names it: `main.va` on the command line is `./main.va` in the project canonical <- either (const path) id <$> try @IOException (canonicalizePath path) let marker = "file:" <> Text.pack canonical st = st0 {attempted = Set.insert marker st0.attempted} if Set.member marker st0.attempted || any (\sf -> sf.path == path) (sourceFiles st0.sourceMap) then pure st0 else loadNew st path where loadNew st path = maybe (try @IOException (ByteString.readFile path)) (pure . Right) (Map.lookup given st.overlay <|> Map.lookup path st.overlay) >>= \case Left e -> pure st { reports = (diagnostic CannotReadFile Driver ("cannot read `" <> Text.pack path <> "`")) { notes = [Note {text = Text.pack (displayException e), span = Nothing}] } : st.reports } Right bytes -> pure (loadBytes explicit st path bytes) loadBytes :: Bool -> LoadState -> FilePath -> ByteString -> LoadState loadBytes explicit st path bytes = st { sourceMap = sources' , reports = notUnits <> reverse parsed.diagnostics <> st.reports -- (a unit from a file named on the command line is never replaced by one found by -- search: `main.vadb` beside a `main.va` that also holds `Main`) , units = foldl (\m l -> Map.insertWith (\new old -> if old.explicit && not new.explicit then old else new) (keyOf l) l m) st.units loaded } where (fid, sources') = addSource path bytes st.sourceMap parsed = maybe Result {diagnostics = [], value = Nothing} parseFile (lookupSource sources' fid) broken = any isError parsed.diagnostics -- (a declaration that is not a library item, `G : exception;` alone in a file: RM -- 10.1.1(3); it was dropped, and the units naming it saw nothing of it, D257) notUnits = [ (diagnostic WrongKindOfEntity Semantic "a library unit is a package, a subprogram, a generic unit, an instance or a renaming of one; this declaration is none of them") { primary = Just (label li.item.span "not a library unit") , advice = Just "declare it in a package, and name the package in a with clause" } | raw <- fromMaybe [] parsed.value , LibraryUnit li <- [raw.body] , notLibraryItem li.item.node ] notLibraryItem = \case AD.DObject _ -> True AD.DNumber _ -> True AD.DType _ -> True AD.DSubtype _ -> True AD.DObjectRenaming _ -> True AD.DException _ -> True _ -> False loaded = [ loadedWith facts name kind u path explicit broken | raw <- fromMaybe [] parsed.value , let rawFacts = unitFacts raw -- (a unit with tasking is made of other declarations, which are its facts) desugared = if rawFacts.tasking then desugarTasking raw else raw facts = if rawFacts.tasking then unitFacts desugared else rawFacts u = aplRuntimeWith rawFacts.codeStrings desugared , Just (name, kind) <- [unitIdentity u] ] -- | Load specifications until every dependency is present or known to be missing. closure :: [FilePath] -> LoadState -> IO LoadState closure dirs st = do let wanted = [ d | l <- Map.elems st.units , d <- l.dependsOn , not (Map.member (Text.toCaseFold d.name, UnitSpec) st.units) , not (Set.member (Text.toCaseFold d.name) st.attempted) ] case wanted of [] -> pure st d : _ -> do let st' = st {attempted = Set.insert (Text.toCaseFold d.name) st.attempted} file = specFileName d.name onDisk <- filterM doesFileExist [dir f | dir <- dirs, f <- unitFileNames d.name UnitSpec] next <- case (onDisk, predefinedFile file) of -- a spec found on disk, with its body beside it when it has one (unless loaded) (p : _, _) -> do withSpec <- loadPath False st' p bodies <- filterM doesFileExist [takeDirectory p f | f <- unitFileNames d.name UnitBody] case bodies of b : _ | not (Map.member (Text.toCaseFold d.name, UnitBody) withSpec.units) -> loadPath False withSpec b _ -> pure withSpec -- a predefined spec, with its body when it has one ([], Just bytes) -> do let withSpec = loadBytes False st' ("/" <> file) bytes bodyFile = unitFileName d.name UnitBody pure case predefinedFile bodyFile of Just body | st.purpose == ForCode || any (specNeedsBody . (.unit)) (specsNamed d.name withSpec) -> loadBytes False withSpec ("/" <> bodyFile) body _ -> withSpec -- (a library subprogram may have no specification: its body declares it, RM -- 10.1.4(4), found in its body's file) ([], Nothing) | d.required -> do let bodyOnly x = neededKey x.units d.name /= (Text.toCaseFold d.name, UnitSpec) bodies <- filterM doesFileExist [dir f | dir <- dirs, f <- unitFileNames d.name UnitBody] withBody <- case bodies of b : _ | not (bodyOnly st') -> loadPath False st' b _ -> pure st' -- (at each with clause that names it, RM 10.1.2(4)) let naming = nubBy (\a b -> a.span == b.span) [x | l <- Map.elems st.units, x <- l.dependsOn, x.required, Text.toCaseFold x.name == Text.toCaseFold d.name] pure if bodyOnly withBody then withBody else withBody {reports = map (missing withBody.sourceMap) (if null naming then [d] else naming) <> withBody.reports} | otherwise -> pure st' closure dirs next where -- (a language-defined unit of a construct Verada leaves out: what Verada has instead) missing sources d | Just (what, r) <- excludedUnit d.name = (diagnostic ExcludedConstruct Driver ("`" <> d.name <> "` (" <> what <> ") is not in Verada")) { primary = (\s -> label s "not in Verada") <$> d.span , notes = [Note {text = r.why, span = Nothing}] , advice = Just case takeExtension . (.path) <$> (lookupSource sources . (.file) =<< d.span) of Just ".vb" -> vibeInstead r Just ".py" -> vibeInstead r Just ".va" -> varcInstead r _ -> r.instead } missing _ d = (diagnostic UnknownUnit Driver ("no library unit `" <> d.name <> "` was found")) { primary = (\s -> label s ("looked for " <> alternatives ["`" <> Text.pack f <> "`" | f <- unitFileNames d.name UnitSpec])) <$> d.span , notes = [Note {text = "searched " <> Text.intercalate ", " (map (\x -> "`" <> Text.pack x <> "`") dirs) <> " and the predefined library", span = Nothing}] , advice = Just "check the name, or add the directory that contains the unit to `source-dirs` in verada.toml" } -- | The specifications loaded under a name. specsNamed :: Text -> LoadState -> [Loaded] specsNamed n st = [l | Just l <- [Map.lookup (Text.toCaseFold n, UnitSpec) st.units]] -- | Whether a predefined specification leaves to its body something its callers' analysis -- needs: a subprogram without a stated `Global` (its effects are its body's), a task or a -- protected object. (A generic's body is 'withGenericBodies'' to load.) specNeedsBody :: CompilationUnit -> Bool specNeedsBody u = any needsBody (unitDeclarations u) -- | Whether a declaration leaves something its users' analysis needs to a body (see -- 'specNeedsBody'); a generic declared in it is looked at apart. needsBody :: AD.Decl -> Bool needsBody d = case d.node of AD.DSubprogram s -> s.form == AD.PlainSpec && not (any (\a -> named "Global" a || named "Import" a) s.aspects) AD.DPackage p -> any needsBody (p.visible <> fromMaybe [] p.private) AD.DTask _ -> True AD.DProtected _ -> True AD.DEntry _ -> True _ -> False where named n a = Text.toCaseFold a.mark.text == Text.toCaseFold n -- | Whether a predefined generic's instances need its body for analysis: the instances of -- the predefined library's generics are trusted as it is (their checks are its own, proved -- apart), so only for what their specification does not say (see 'needsBody'), and a -- generic subprogram's always (its instance is made from its body). For a -- package that declares generics (`Ada.Text_IO`'s `Integer_IO`), only when one of those the -- body is needed for is instantiated. genericNeedsBody :: Set.Set Text -> CompilationUnit -> Bool genericNeedsBody instantiated u = case u.body of LibraryUnit LibraryItem {item = AD.Decl {node = AD.DGeneric g}} -> genericUnitNeeds g LibraryUnit LibraryItem {item = AD.Decl {node = AD.DPackage p}} -> any (\(n, needed) -> needed && Set.member n instantiated) (concatMap inside (p.visible <> fromMaybe [] p.private)) _ -> False where inside d = case d.node of AD.DGeneric g -> [(Text.toCaseFold (simpleName n), genericUnitNeeds g) | Just n <- [genericName g.unit]] AD.DPackage p -> concatMap inside (p.visible <> fromMaybe [] p.private) _ -> [] -- (a generic subprogram is instantiated from its body: Sema makes the instance's body) genericUnitNeeds g = case g.unit.node of AD.DSubprogram _ -> True _ -> needsWithin g.unit -- (inside a generic package, a generic subprogram's instances need the body too, when -- there are any: `Generic_Sort` of a vector) needsWithin d = case d.node of AD.DGeneric g -> maybe True (\n -> Set.member (Text.toCaseFold (simpleName n)) instantiated) (genericName g.unit) && genericUnitNeeds g AD.DPackage p -> any needsWithin (p.visible <> fromMaybe [] p.private) _ -> needsBody d genericName d = case d.node of AD.DPackage p -> dottedName p.name AD.DSubprogram s -> dottedName s.spec.name _ -> Nothing -- | The generics the loaded units instantiate or rename, by simple name, case-folded. instantiatedNames :: LoadState -> Set.Set Text instantiatedNames st = Set.fromList [Text.toCaseFold (simpleName n) | l <- Map.elems st.units, n <- l.instantiates] simpleName :: Text -> Text simpleName = snd . Text.breakOnEnd "." data Ordered = Ordered { units :: [Loaded] , cycles :: [Diagnostic] } -- | Dependency order (depth-first), reporting cycles among specifications (B1006). order :: Map Key Loaded -> Ordered order units = let (_, done, cyc) = foldl visit (Set.empty, [], []) (Map.keys units) in Ordered {units = reverse done, cycles = reverse cyc} where visit = go [] go path (seen, done, cyc) k | k `elem` path = (seen, done, cycleReport (reverse (k : path)) : cyc) | Set.member k seen = (seen, done, cyc) | otherwise = case Map.lookup k units of Nothing -> (seen, done, cyc) Just l -> -- (a `limited with` needs only the named unit's syntax, its limited view: it may -- close a cycle, and the unit may come later, RM 10.1.1(12.1)) let specs = [needed | d <- l.dependsOn, not d.limited, let needed = neededKey units d.name, needed /= k] -- an instance needs the generic's body too genericBodies = [(n, UnitBody) | (n, _) <- specs, isGeneric (n, UnitSpec), Map.member (n, UnitBody) units, (n, UnitBody) /= k] deps = specs <> genericBodies (seen', done', cyc') = foldl (go (k : path)) (seen, done, cyc) deps in if Set.member k seen' then (seen', done', cyc') else (Set.insert k seen', l : done', cyc') -- a generic unit, or a package with generics in it: their bodies are its body's isGeneric key = case Map.lookup key units of Just Loaded {unit = CompilationUnit {body = LibraryUnit LibraryItem {item = AD.Decl {node = AD.DGeneric _}}}} -> True Just Loaded {unit = CompilationUnit {body = LibraryUnit LibraryItem {item = AD.Decl {node = AD.DPackage p}}}} -> or [True | AD.Decl {node = AD.DGeneric _} <- p.visible] _ -> False cycleReport ks = let names = [maybe n (.name) (Map.lookup (n, kd) units) | (n, kd) <- ks] first = case ks of k : _ -> Map.lookup k units [] -> Nothing second = case ks of _ : (n, _) : _ -> Just n _ -> Nothing -- the with clause in the first unit that leads into the cycle withSpan l = case [s | d <- l.dependsOn, Just (Text.toCaseFold d.name) == second, Just s <- [d.span]] of s : _ -> s [] -> fromMaybe l.unit.span (unitNameSpan l.unit) in (diagnostic CircularDependency Driver ("these units depend on each other: " <> Text.intercalate " -> " names)) { primary = (\l -> label (withSpan l) "this context clause closes the cycle") <$> first , notes = [Note {text = "Ada RM 10.1.1: the specifications named in with clauses must not form a cycle; name one of them in a `limited with`, which needs only its types, or move the shared declarations to a third package", span = Nothing}] } -- | Units that can be analysed: parsed without errors, as are all the specs they depend on. cleanUnits :: Map Key Loaded -> Set.Set Key cleanUnits units = Set.fromList [k | k <- Map.keys units, clean Set.empty k] where clean visiting k | Set.member k visiting = True | otherwise = case Map.lookup k units of Nothing -> True Just l -> not l.broken && all (clean (Set.insert k visiting)) [neededKey units d.name | d <- l.dependsOn, d.required] -- | The unit a with clause of this name needs analysed first: its specification, or the body -- of a library subprogram that has none (the body is its declaration too, RM 10.1.4(4)), -- whatever the names of the units that name it (B1003 for those that sorted before it). neededKey :: Map Key Loaded -> Text -> Key neededKey units n | not (Map.member spec units) , Just Loaded {unit = CompilationUnit {body = LibraryUnit LibraryItem {item = AD.Decl {node = AD.DSubprogramBody _}}}} <- Map.lookup body units = body | otherwise = spec where spec = (Text.toCaseFold n, UnitSpec) body = (Text.toCaseFold n, UnitBody) -- | B1007: an explicitly given file whose unit others could not find under its name. fileNameMismatch :: Loaded -> [Diagnostic] fileNameMismatch l | not l.explicit || isImplicitInstance l.unit || genericClass || vibeProgram = [] | vibeModule = vibeModuleFileNameMismatch l | takeFileName l.path `elem` unitFileNames l.name l.kind = [] | otherwise = [ (diagnostic UnitFileMismatch Driver ("`" <> Text.pack (takeFileName l.path) <> "` contains `" <> l.name <> "`, which other units look for in `" <> Text.pack expected <> "`")) { primary = Just (label (fromMaybe l.unit.span (unitNameSpan l.unit)) "this unit") , advice = Just ("rename the file to `" <> Text.pack expected <> "`") } ] where -- Vibe's package name is implicit in the filename, not a declaration in the -- source. A main subprogram still has an explicit name and uses the usual check. vibeModule = implicitVibeModule l -- (a Vibe generic class, `M_Generic_Box`, is a unit of its module's file `m.vb`) genericClass = case Text.breakOn "_Generic_" l.name of (m, c) -> not (Text.null c) && isVibePath l.path && Text.toLower (Text.pack (takeBaseName l.path)) == Text.toLower m -- (and the program of a Vibe module that declares types beside its `main`, `m_Program`) vibeProgram = isVibePath l.path && Text.toLower l.name == Text.toLower (Text.pack (takeBaseName l.path)) <> "_program" -- the file name in the file's own syntax (a Varc unit in a `.va` file) expected = expectedUnitFilename l implicitVibeModule :: Loaded -> Bool implicitVibeModule l = isVibePath l.path && l.name == Text.pack (takeBaseName l.path) && case l.unit.body of LibraryUnit LibraryItem {item = AD.Decl {node = AD.DPackage _}} -> True LibraryUnit LibraryItem {item = AD.Decl {node = AD.DPackageBody _}} -> True _ -> False expectedUnitFilename :: Loaded -> FilePath expectedUnitFilename l = case [n | n <- unitFileNames l.name l.kind, takeExtension n == takeExtension l.path] of n : _ -> n [] -> unitFileName l.name l.kind fileNameRepair :: Loaded -> Maybe FileNameRepair fileNameRepair l | l.broken || null (fileNameMismatch l) = Nothing | otherwise = Just FileNameRepair { path = l.path, target = normalise (takeDirectory l.path expected), oldName = l.name , newName = if implicit then Text.pack (takeBaseName expected) else l.name , implicitModule = implicit } where implicit = implicitVibeModule l expected = if implicit then Text.unpack (vibeModuleFilename (Text.pack (takeBaseName l.path))) <> takeExtension l.path else expectedUnitFilename l -- | A Vibe module needs an importable filename, as well as the lower-case spelling -- used by library lookup. Merely lowercasing `Untitled-2.vb` leaves an unimportable -- module name; do not suggest that incomplete repair. Report once for the package's -- spec, at the start of the file, without pretending a source declaration supplied it. vibeModuleFileNameMismatch :: Loaded -> [Diagnostic] vibeModuleFileNameMismatch l | l.kind /= UnitSpec || (importable stem && stem == Text.toLower stem) = [] | otherwise = [ (diagnostic UnitFileMismatch Driver message) { primary = Just (label (l.unit.span {end = l.unit.span.start}) "the module name comes from the file name") , notes = [Note {text = "Vibe takes a module's name from its filename. Use lowercase letters, digits and underscores, starting with a letter or underscore; a keyword cannot name a module.", span = Nothing}] , advice = Just ("rename the file to `" <> suggested <> Text.pack (takeExtension l.path) <> "` and update any imports of this module") } ] where stem = Text.pack (takeBaseName l.path) named = "`" <> Text.pack (takeFileName l.path) <> "` gives this Vibe module the name `" <> stem <> "`" message | not (importable stem) = named <> ", which cannot be used in an import" | not (importable (Text.toLower stem)) = named <> ", whose lowercase spelling `" <> Text.toLower stem <> "` is a reserved Vibe keyword" | otherwise = named <> ", but module lookup uses the lowercase filename `" <> Text.toLower stem <> Text.pack (takeExtension l.path) <> "`" -- These are exactly the ASCII identifier characters accepted by the Vibe -- lexer; unlike Vada, Vibe also permits leading and repeated underscores. first c = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' rest c = first c || (c >= '0' && c <= '9') importable name = case Text.uncons name of Just (c, cs) -> first c && Text.all rest cs && Vibe.keywordFromText name == Nothing Nothing -> False suggested = vibeModuleFilename stem vibeModuleFilename :: Text -> Text vibeModuleFilename stem = if Vibe.keywordFromText prefixed == Nothing then prefixed else prefixed <> "_module" where first c = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' rest c = first c || (c >= '0' && c <= '9') sanitized = Text.map (\c -> if rest c then c else '_') (Text.toLower stem) prefixed = case Text.uncons sanitized of Nothing -> "module" Just (c, _) | not (first c) -> "module_" <> sanitized _ | Text.all (== '_') sanitized -> "module" _ -> sanitized -- | @a@, @a or b@, @a, b or c@. alternatives :: [Text] -> Text alternatives xs = case unsnoc xs of Just (before@(_ : _), final) -> Text.intercalate ", " before <> " or " <> final _ -> Text.concat xs -- * Vibe cross-module passes (unused Vectors pruning & writable-mode propagation) -- | Vibe's desugarer emits a `Vectors_` instantiation of -- `Verada.Containers.Unbounded.Vectors` beside every plain `@dataclass` so that another -- module's `list[Class]` names the same type. Once the full set of units is loaded, drop any -- such instantiation that no unit references so unused container bodies are never expanded, -- lowered, proved or emitted. pruneUnusedVibeVectors :: LoadState -> LoadState pruneUnusedVibeVectors st | not (any (\l -> isVibePath l.path) (Map.elems st.units)) = st | otherwise = let items = Map.toList st.units pruned = pruneUnusedVibeVectorsUnits [(isVibePath l.path, l.unit) | (_, l) <- items] units' = Map.fromList [(k, if u' == l.unit then l else loadedUnit l.name l.kind u' l.path l.explicit l.broken) | ((k, l), u') <- zip items pruned] in LoadState {sourceMap = st.sourceMap, reports = st.reports, units = units', attempted = st.attempted, overlay = st.overlay, purpose = st.purpose} -- | Extend Vibe's inferred writable (`in out`) parameter mode across module boundaries. -- Single-file desugaring marks a parameter writable when the module mutates it directly or -- passes it to another procedure of the same module that mutates it. Once all units are -- loaded, propagate writable modes through calls to imported procedures to a fixed point. propagateVibeModes :: Map Key Loaded -> Map Key Loaded propagateVibeModes units0 | not (any (\l -> isVibePath l.path) (Map.elems units0)) = units0 | otherwise = go units0 where go units = let sigs = collectProcs units usedPkgs = collectUses units updates = collectUpgrades units sigs usedPkgs in if Map.null updates then units else go (Map.map (applyUpgrades updates) units) -- ((unitKey, procKey, arity) -> [[(paramKey, isWritable)]]) collectProcs :: Map Key Loaded -> Map (Text, Text, Int) [[(Text, Bool)]] collectProcs units = Map.fromListWith (<>) [ ((Text.toCaseFold l.name, Text.toCaseFold pName, length formals), [formals]) | l <- Map.elems units , spec <- allProcSpecs l.unit.body , Just pName <- [dottedName spec.name] , let formals = flattenFormals spec.profile.parameters ] allProcSpecs :: (Data a) => a -> [AD.SubprogramSpec] allProcSpecs x = here <> concat (gmapQ allProcSpecs x) where here = case cast x of Just AD.Decl {node = AD.DSubprogram s} | s.spec.kind == AD.ProcedureKind -> [s.spec] Just AD.Decl {node = AD.DSubprogramBody b} | b.spec.kind == AD.ProcedureKind -> [b.spec] _ -> [] flattenFormals :: [AT.Parameter] -> [(Text, Bool)] flattenFormals ps = [ (Text.toCaseFold ident.text, p.mode == AT.ModeInOut || p.mode == AT.ModeOut) | p <- ps , ident <- p.names ] collectUses :: Map Key Loaded -> Map Text [Text] collectUses units = Map.fromListWith (<>) [ (Text.toCaseFold l.name, map Text.toCaseFold (mapMaybe dottedName u.names)) | l <- Map.elems units , ContextUse u <- l.unit.context , u.kind == AD.UsePackage ] -- Map (unitKey, procKey, arity) -> Set paramKey to promote to ModeInOut collectUpgrades :: Map Key Loaded -> Map (Text, Text, Int) [[(Text, Bool)]] -> Map Text [Text] -> Map (Text, Text, Int) (Set.Set Text) collectUpgrades units sigs usedPkgs = Map.filter (not . Set.null) $ Map.fromListWith Set.union [ ((uKey, Text.toCaseFold pName, length formals), promoted) | l <- Map.elems units , isVibePath l.path , let uKey = Text.toCaseFold l.name uses = nub (uKey : Map.findWithDefault [] uKey usedPkgs) , b <- allProcBodies l.unit.body , b.spec.kind == AD.ProcedureKind , Just pName <- [dottedName b.spec.name] , let formals = flattenFormals b.spec.profile.parameters readOnly = Set.fromList [k | (k, w) <- formals, not w] views = collectViews (Set.fromList (map fst formals)) b.declarations called = mutatedByCalls sigs uses views b.declarations b.statements promoted = Set.intersection readOnly called , not (Set.null promoted) ] allProcBodies :: (Data a) => a -> [AD.SubprogramBody] allProcBodies x = here <> concat (gmapQ allProcBodies x) where here = case cast x of Just b@AD.SubprogramBody {} -> [b] _ -> [] collectViews :: Set.Set Text -> [AD.Decl] -> Map Text Text collectViews params decls = fixViews (Map.fromList [(p, p) | p <- Set.toList params]) where renamings = [(Text.toCaseFold r.name.text, r.renamed) | AD.Decl {node = AD.DObjectRenaming r} <- decls] fixViews m = let m' = foldl (\acc (n, e) -> maybe acc (\root -> Map.insert n root acc) (rootOf acc e)) m renamings in if m' == m then m else fixViews m' rootOf :: Map Text Text -> AE.Expr -> Maybe Text rootOf views e = case e.node of AE.ENameRef i -> Map.lookup (Text.toCaseFold i.text) views AE.ESelected s -> rootOf views s.prefix AE.EApply a -> rootOf views a.prefix AE.EDereference inner -> rootOf views inner AE.EParen inner -> rootOf views inner _ -> Nothing mutatedByCalls :: Map (Text, Text, Int) [[(Text, Bool)]] -> [Text] -> Map Text Text -> [AD.Decl] -> [AS.Stmt] -> Set.Set Text mutatedByCalls sigs uses views decls stmts = Set.fromList (concatMap walkAny decls <> concatMap walkAny stmts) where walkAny :: (Data a) => a -> [Text] walkAny x | Just (_ :: AD.SubprogramBody) <- cast x = [] | Just e <- (cast x :: Maybe AE.Expr) = checkCall e <> concat (gmapQ walkAny e) | otherwise = concat (gmapQ walkAny x) checkCall :: AE.Expr -> [Text] checkCall e = case e.node of AE.EApply a -> let cands = resolveCallee a.prefix (length a.arguments) in if null cands then [] else [ root | (idx, arg) <- zip [0 :: Int ..] a.arguments , all (\fs -> formalWritable fs idx arg.formal) cands , AE.ArgExpr val <- [arg.value] , Just root <- [rootOf views val] ] _ -> [] resolveCallee :: AE.Expr -> Int -> [[(Text, Bool)]] resolveCallee callee nArgs = case callee.node of AE.ESelected sel | AE.SelectIdentifier fn <- sel.selector , Just modName <- dottedName sel.prefix -> lookupCandidates (Text.toCaseFold modName) (Text.toCaseFold fn.text) nArgs AE.ENameRef fn -> let fnKey = Text.toCaseFold fn.text in case [cs | u <- uses, let cs = lookupCandidates u fnKey nArgs, not (null cs)] of cs : _ -> cs [] -> [] _ -> [] lookupCandidates :: Text -> Text -> Int -> [[(Text, Bool)]] lookupCandidates uKey fnKey nArgs = concat [ fs | ((u, fn, arity), fs) <- Map.toList sigs , u == uKey , fn == fnKey , arity >= nArgs ] formalWritable :: [(Text, Bool)] -> Int -> Maybe AE.Identifier -> Bool formalWritable fs idx mFormal = case mFormal of Just fid -> maybe False snd (find (\(k, _) -> k == Text.toCaseFold fid.text) fs) Nothing -> case drop idx fs of (_, w) : _ -> w [] -> False applyUpgrades :: Map (Text, Text, Int) (Set.Set Text) -> Loaded -> Loaded applyUpgrades updates l | not (isVibePath l.path) = l | otherwise = let uKey = Text.toCaseFold l.name body' = rewriteSpecs uKey l.unit.body u' = CompilationUnit {span = l.unit.span, context = l.unit.context, body = body'} in if body' == l.unit.body then l else Loaded {name = l.name, kind = l.kind, unit = u', path = l.path, explicit = l.explicit, broken = l.broken, dependsOn = l.dependsOn, instantiates = l.instantiates} where rewriteSpecs :: (Data a) => Text -> a -> a rewriteSpecs uKey x = case cast x of Just spec -> fromMaybe x (cast (upgradeSpec uKey (spec :: AD.SubprogramSpec))) Nothing -> gmapT (rewriteSpecs uKey) x upgradeSpec :: Text -> AD.SubprogramSpec -> AD.SubprogramSpec upgradeSpec uKey spec | spec.kind /= AD.ProcedureKind = spec | Just pName <- dottedName spec.name , let arity = length (flattenFormals spec.profile.parameters) , Just toPromote <- Map.lookup (uKey, Text.toCaseFold pName, arity) updates = spec {AD.profile = spec.profile {AT.parameters = map (upgradeParam toPromote) spec.profile.parameters}} | otherwise = spec upgradeParam :: Set.Set Text -> AT.Parameter -> AT.Parameter upgradeParam toPromote p | p.mode `elem` [AT.ModeDefault, AT.ModeIn] , any (\i -> Set.member (Text.toCaseFold i.text) toPromote) p.names = p {AT.mode = AT.ModeInOut} | otherwise = p