module Unison.Codebase.Editor.HandleInput.Load
  ( handleLoad,
    loadUnisonFile,
    EvalMode (..),
    evalUnisonFile,
    parseAndTypecheckUnisonFile,
    pulledInDefinitions,
    pulledInStarts,
    PulledIn (..),
    insertAboveFold,
    pulledInHeader,
  )
where

import Control.Lens ((.=), (?=))
import Control.Monad.Reader (ask)
import Control.Monad.State.Strict qualified as State
import Data.IORef (newIORef, readIORef, writeIORef)
import Data.Map.Merge.Strict qualified as Map
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Set.NonEmpty (NESet)
import Data.Set.NonEmpty qualified as Set.NonEmpty
import Data.Text qualified as Text
import System.Directory qualified as Directory
import System.Environment (withArgs)
import U.Codebase.Sqlite.Operations qualified as Operations
import U.Codebase.Sqlite.Project qualified as Sqlite
import U.Codebase.Sqlite.ProjectBranch qualified as Sqlite
import U.Codebase.Sqlite.Queries qualified as Queries
import Unison.ABT qualified as ABT
import Unison.Builtin qualified as Builtin
import Unison.Cli.Monad (Cli)
import Unison.Cli.Monad qualified as Cli
import Unison.Cli.MonadUtils qualified as Cli
import Unison.Cli.TypeCheck (computeTypecheckingEnvironment)
import Unison.Cli.UniqueTypeGuidLookup qualified as Cli
import Unison.Codebase (Codebase)
import Unison.Codebase qualified as Codebase
import Unison.Codebase.Branch qualified as Branch
import Unison.Codebase.Branch.Names qualified as Branch
import Unison.Codebase.Editor.HandleInput.EditNamespace (getNamesForEdit)
import Unison.Codebase.Editor.HandleInput.RuntimeUtils (EvalMode (..), modeProfSpec)
import Unison.Codebase.Editor.HandleInput.RuntimeUtils qualified as RuntimeUtils
import Unison.Codebase.Editor.HandleInput.ShowDefinition (renderToFile)
import Unison.Codebase.Editor.Input (RelativeToFold (AboveFold))
import Unison.Codebase.Editor.Output qualified as Output
import Unison.Codebase.Editor.SlurpResult (TermSlurp (..), TypeSlurp (..))
import Unison.Codebase.Execute qualified as Codebase
import Unison.Codebase.ProjectPath (ProjectPathG (..))
import Unison.Codebase.Runtime qualified as Runtime
import Unison.Codebase.Runtime.Profile (ProfileSpec (NoProf))
import Unison.ConstructorReference (ConstructorReference, GConstructorReference (..))
import Unison.DataDeclaration (DeclOrBuiltin)
import Unison.DataDeclaration qualified as DataDeclaration
import Unison.FileParsers qualified as FileParsers
import Unison.Merge (GUpdated (..))
import Unison.Name (Name)
import Unison.Names (Names (..))
import Unison.Names qualified as Names
import Unison.OrBuiltin (OrBuiltin (..))
import Unison.Parser.Ann (Ann)
import Unison.Parser.Ann qualified as Ann
import Unison.Parsers qualified as Parsers
import Unison.Prelude
import Unison.PrettyPrintEnv qualified as PPE
import Unison.PrettyPrintEnv.Names qualified as PPE
import Unison.PrettyPrintEnvDecl qualified as PPED
import Unison.Reference (TermReference, TypeReference)
import Unison.Reference qualified as Reference
import Unison.Referent (Referent)
import Unison.Referent qualified as Referent
import Unison.Result qualified as Result
import Unison.Runtime (Error)
import Unison.Sqlite qualified as Sqlite
import Unison.Symbol (Symbol)
import Unison.Syntax.Name qualified as Name
import Unison.Syntax.Parser qualified as Parser
import Unison.Term (Term)
import Unison.Term qualified as Term
import Unison.Type (Type)
import Unison.Typechecker.Context qualified as Context
import Unison.Typechecker.TypeError qualified as TypeError
import Unison.Typed (Typed (..))
import Unison.UnisonFile (TypecheckedUnisonFile)
import Unison.UnisonFile qualified as UF
import Unison.UnisonFile.Names qualified as UF
import Unison.UnisonFile.Names qualified as UFN
import Unison.Util.Defns (Defns (..))
import Unison.Util.Relation (Relation)
import Unison.Util.Relation qualified as Relation
import Unison.Util.Timing qualified as Timing
import Unison.Var qualified as Var
import Unison.WatchKind (WatchKind)
import Unison.WatchKind qualified as WatchKind

handleLoad :: Maybe FilePath -> Cli ()
handleLoad :: Maybe FilePath -> Cli ()
handleLoad Maybe FilePath
maybePath = do
  latestFile <- Cli (Maybe (FilePath, Bool))
Cli.getLatestFile
  path <- (maybePath <|> fst <$> latestFile) & onNothing (Cli.returnEarly Output.NoUnisonFile)
  Cli.Env {loadSource} <- ask
  contents <-
    liftIO (loadSource (Text.pack path)) >>= \case
      LoadSourceResult
Cli.InvalidSourceNameError -> Output -> Cli Text
forall a. Output -> Cli a
Cli.returnEarly (Output -> Cli Text) -> Output -> Cli Text
forall a b. (a -> b) -> a -> b
$ FilePath -> Output
Output.InvalidSourceName FilePath
path
      LoadSourceResult
Cli.LoadError -> Output -> Cli Text
forall a. Output -> Cli a
Cli.returnEarly (Output -> Cli Text) -> Output -> Cli Text
forall a b. (a -> b) -> a -> b
$ FilePath -> Output
Output.SourceLoadFailed FilePath
path
      Cli.LoadSuccess Text
contents -> Text -> Cli Text
forall a. a -> Cli a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Text
contents
  loadUnisonFile (Text.pack path) contents

loadUnisonFile :: Text -> Text -> Cli ()
loadUnisonFile :: Text -> Text -> Cli ()
loadUnisonFile Text
sourceName Text
text = do
  env <- Cli Env
forall r (m :: * -> *). MonadReader r m => m r
ask

  Cli.respond $ Output.LoadingFile sourceName
  oldBranch0 <- Cli.getCurrentBranch0
  let oldNames = Branch0 IO -> Names
forall (m :: * -> *). Branch0 m -> Names
Branch.toNames Branch0 IO
oldBranch0
  unisonFile <- parseAndTypecheckUnisonFile oldNames sourceName text
  let unisonFileNames = TypecheckedUnisonFile Symbol Ann -> Names
forall v a. Var v => TypecheckedUnisonFile v a -> Names
UF.typecheckedToNames TypecheckedUnisonFile Symbol Ann
unisonFile
  let newNames = TypecheckedUnisonFile Symbol Ann -> Names -> Names
forall v a. Var v => TypecheckedUnisonFile v a -> Names -> Names
UF.addNamesFromTypeCheckedUnisonFile TypecheckedUnisonFile Symbol Ann
unisonFile Names
oldNames
  let newPpe = PrettyPrintEnvDecl -> PrettyPrintEnv
PPED.suffixifiedPPE (Namer -> Suffixifier -> PrettyPrintEnvDecl
PPED.makePPED (Int -> Names -> Namer
PPE.hqNamer Int
10 Names
newNames) (Names -> Suffixifier
PPE.suffixifyByHash Names
newNames))
  pp <- Cli.getCurrentProjectPath

  -- If we're on an update, upgrade, or merge branch, we have special logic to render changes relative to the parent
  -- branch (in a merge branch, that's the branch we're merging into). This is because, on these branches, dependents
  -- have been pulled out of the underlying namespace and put into the scratch file (so that we can support deleting
  -- things). Without this special logic, all of these things would be classified as new definitions.

  maybeSpecialBranchParentCausalHash <-
    if pp.branch.isUpdate || pp.branch.isUpgrade || pp.branch.isMerge
      then case pp.branch.parentBranchId of
        Maybe ProjectBranchId
Nothing -> Maybe CausalHash -> Cli (Maybe CausalHash)
forall a. a -> Cli a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe CausalHash
forall a. Maybe a
Nothing
        Just ProjectBranchId
parentBranchId ->
          CausalHash -> Maybe CausalHash
forall a. a -> Maybe a
Just (CausalHash -> Maybe CausalHash)
-> Cli CausalHash -> Cli (Maybe CausalHash)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Transaction CausalHash -> Cli CausalHash
forall a. Transaction a -> Cli a
Cli.runTransaction (HasCallStack =>
ProjectId -> ProjectBranchId -> Transaction CausalHash
ProjectId -> ProjectBranchId -> Transaction CausalHash
Queries.expectProjectBranchHeadHash ProjectPath
pp.project.projectId ProjectBranchId
parentBranchId)
      else pure Nothing

  (oldPpe, slurpEntries, existingTerms) <-
    case maybeSpecialBranchParentCausalHash of
      Maybe CausalHash
Nothing -> do
        slurpEntries <-
          Transaction (Defns (Map Name TermSlurp) (Map Name TypeSlurp))
-> Cli (Defns (Map Name TermSlurp) (Map Name TypeSlurp))
forall a. Transaction a -> Cli a
Cli.runTransaction do
            terms <-
              Codebase IO Symbol Ann
-> TypecheckedUnisonFile Symbol Ann
-> Bool
-> Map Name (Set Referent)
-> Map Name (Set Referent)
-> Transaction (Map Name TermSlurp)
forall (m :: * -> *).
Codebase m Symbol Ann
-> TypecheckedUnisonFile Symbol Ann
-> Bool
-> Map Name (Set Referent)
-> Map Name (Set Referent)
-> Transaction (Map Name TermSlurp)
slurpTerms
                Env
env.codebase
                TypecheckedUnisonFile Symbol Ann
unisonFile
                Bool
False
                (Relation Name Referent -> Map Name (Set Referent)
forall a b. Relation a b -> Map a (Set b)
Relation.domain Names
oldNames.terms)
                (Relation Name Referent -> Map Name (Set Referent)
forall a b. Relation a b -> Map a (Set b)
Relation.domain Names
unisonFileNames.terms)
            types <-
              slurpTypes
                env.codebase
                unisonFile
                False
                (Relation.domain oldNames.types)
                (Relation.domain unisonFileNames.types)
            pure Defns {terms, types}

        pure
          ( PPED.suffixifiedPPE (PPED.makePPED (PPE.hqNamer 10 oldNames) (PPE.suffixifyByHash oldNames)),
            slurpEntries,
            oldNames.terms
          )
      Just CausalHash
specialBranchParentCausalHash -> do
        specialBranchParent <- IO (Branch IO) -> Cli (Branch IO)
forall a. IO a -> Cli a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Codebase IO Symbol Ann -> CausalHash -> IO (Branch IO)
forall (m :: * -> *) v a.
Monad m =>
Codebase m v a -> CausalHash -> m (Branch m)
Codebase.expectBranchForHash Env
env.codebase CausalHash
specialBranchParentCausalHash)
        let specialBranchParent0 = Branch IO -> Branch0 IO
forall (m :: * -> *). Branch m -> Branch0 m
Branch.head Branch IO
specialBranchParent
        let specialBranchParentNames = Branch0 IO -> Names
forall (m :: * -> *). Branch0 m -> Names
Branch.toNames Branch0 IO
specialBranchParent0
        let specialBranchParentLocalNames = Branch0 IO -> Names
forall (m :: * -> *). Branch0 m -> Names
Branch.toNames (Branch0 IO -> Branch0 IO
forall (m :: * -> *). Branch0 m -> Branch0 m
Branch.deleteLibdeps Branch0 IO
specialBranchParent0)
        let specialBranchLocalNames =
              Names -> Names -> Names
Names.shadowing Names
unisonFileNames (Branch0 IO -> Names
forall (m :: * -> *). Branch0 m -> Names
Branch.toNames (Branch0 IO -> Branch0 IO
forall (m :: * -> *). Branch0 m -> Branch0 m
Branch.deleteLibdeps Branch0 IO
oldBranch0))

        slurpEntries <-
          Cli.runTransaction do
            terms <-
              slurpTerms
                env.codebase
                unisonFile
                True
                (Relation.domain specialBranchParentLocalNames.terms)
                (Relation.domain specialBranchLocalNames.terms)
            types <-
              slurpTypes
                env.codebase
                unisonFile
                False
                (Relation.domain specialBranchParentLocalNames.types)
                (Relation.domain specialBranchLocalNames.types)
            pure Defns {terms, types}

        pure
          ( PPED.suffixifiedPPE $
              PPED.makePPED
                (PPE.hqNamer 10 specialBranchParentNames)
                (PPE.suffixifyByHash specialBranchParentNames),
            slurpEntries,
            specialBranchParentNames.terms
          )

  let aliases :: Map Referent (NESet Name)
      aliases =
        Relation Name Referent
-> Map Name TermSlurp -> Map Referent (NESet Name)
getTermAliases Relation Name Referent
existingTerms Defns (Map Name TermSlurp) (Map Name TypeSlurp)
slurpEntries.terms

  Cli.respond (Output.Typechecked oldPpe newPpe slurpEntries aliases pp.branch.isMerge)

  when (not . null $ UF.watchComponents unisonFile) do
    Timing.time "evaluating watches" do
      evalUnisonFile (Permissive NoProf) newPpe unisonFile [] >>= \case
        Right ([(Symbol, Term Symbol ())]
bindings, Map
  Symbol (Ann, FilePath, Id, Term Symbol (), Term Symbol (), Bool)
e) -> do
          Bool -> Cli () -> Cli ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not (Map
  Symbol (Ann, FilePath, Id, Term Symbol (), Term Symbol (), Bool)
-> Bool
forall a. Map Symbol a -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null Map
  Symbol (Ann, FilePath, Id, Term Symbol (), Term Symbol (), Bool)
e)) do
            let f :: (a, b, c, d, c, d) -> (a, b, c, d)
f (a
ann, b
kind, c
_hash, d
_uneval, c
eval, d
isHit) = (a
ann, b
kind, c
eval, d
isHit)
            Output -> Cli ()
Cli.respond (Output -> Cli ()) -> Output -> Cli ()
forall a b. (a -> b) -> a -> b
$ Text
-> PrettyPrintEnv
-> [(Symbol, Term Symbol ())]
-> Map Symbol (Ann, FilePath, Term Symbol (), Bool)
-> Output
Output.Evaluated Text
text PrettyPrintEnv
newPpe [(Symbol, Term Symbol ())]
bindings (((Ann, FilePath, Id, Term Symbol (), Term Symbol (), Bool)
 -> (Ann, FilePath, Term Symbol (), Bool))
-> Map
     Symbol (Ann, FilePath, Id, Term Symbol (), Term Symbol (), Bool)
-> Map Symbol (Ann, FilePath, Term Symbol (), Bool)
forall a b k. (a -> b) -> Map k a -> Map k b
Map.map (Ann, FilePath, Id, Term Symbol (), Term Symbol (), Bool)
-> (Ann, FilePath, Term Symbol (), Bool)
forall {a} {b} {c} {d} {c} {d}. (a, b, c, d, c, d) -> (a, b, c, d)
f Map
  Symbol (Ann, FilePath, Id, Term Symbol (), Term Symbol (), Bool)
e)
        Left Error
err -> Output -> Cli ()
Cli.respond ((Pretty ColorText -> Pretty ColorText) -> Error -> Output
Output.EvaluationFailure Pretty ColorText -> Pretty ColorText
forall a. a -> a
id Error
err)

  #latestTypecheckedFile .= Just (Right unisonFile)

slurpTerms ::
  Codebase m Symbol Ann ->
  TypecheckedUnisonFile Symbol Ann ->
  Bool ->
  Map Name (Set Referent) ->
  Map Name (Set Referent) ->
  Sqlite.Transaction (Map Name TermSlurp)
slurpTerms :: forall (m :: * -> *).
Codebase m Symbol Ann
-> TypecheckedUnisonFile Symbol Ann
-> Bool
-> Map Name (Set Referent)
-> Map Name (Set Referent)
-> Transaction (Map Name TermSlurp)
slurpTerms Codebase m Symbol Ann
codebase TypecheckedUnisonFile Symbol Ann
unisonFile Bool
isUpdate =
  WhenMissing Transaction Name (Set Referent) TermSlurp
-> WhenMissing Transaction Name (Set Referent) TermSlurp
-> WhenMatched
     Transaction Name (Set Referent) (Set Referent) TermSlurp
-> Map Name (Set Referent)
-> Map Name (Set Referent)
-> Transaction (Map Name TermSlurp)
forall (f :: * -> *) k a c b.
(Applicative f, Ord k) =>
WhenMissing f k a c
-> WhenMissing f k b c
-> WhenMatched f k a b c
-> Map k a
-> Map k b
-> f (Map k c)
Map.mergeA
    ( if Bool
isUpdate
        then (Name -> Set Referent -> Transaction (Maybe TermSlurp))
-> WhenMissing Transaction Name (Set Referent) TermSlurp
forall (f :: * -> *) k x y.
Applicative f =>
(k -> x -> f (Maybe y)) -> WhenMissing f k x y
Map.traverseMaybeMissing \Name
_ Set Referent
refs ->
          case Set Referent -> Referent
forall a. Set a -> a
Set.findMin Set Referent
refs of
            Referent.Ref TermReference
ref -> do
              ty <- Codebase m Symbol Ann
-> TermReference -> Transaction (Type Symbol Ann)
forall a (m :: * -> *).
BuiltinAnnotation a =>
Codebase m Symbol a -> TermReference -> Transaction (Type Symbol a)
Codebase.expectTypeOfTerm Codebase m Symbol Ann
codebase TermReference
ref
              pure (Just (TermSlurp'Delete (Typed ref ty)))
            Referent.Con ConstructorReference
_ ConstructorType
_ -> Maybe TermSlurp -> Transaction (Maybe TermSlurp)
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe TermSlurp
forall a. Maybe a
Nothing
        else WhenMissing Transaction Name (Set Referent) TermSlurp
forall (f :: * -> *) k x y. Applicative f => WhenMissing f k x y
Map.dropMissing
    )
    ( (Name -> Set Referent -> Transaction (Maybe TermSlurp))
-> WhenMissing Transaction Name (Set Referent) TermSlurp
forall (f :: * -> *) k x y.
Applicative f =>
(k -> x -> f (Maybe y)) -> WhenMissing f k x y
Map.traverseMaybeMissing \Name
name Set Referent
refs ->
        case Set Referent -> Referent
forall a. Set a -> a
Set.findMin Set Referent
refs of
          Referent.Ref TermReference
ref -> do
            ty <- Name -> TermReference -> Transaction (Type Symbol Ann)
getNewRefType Name
name TermReference
ref
            pure (Just (TermSlurp'Add (Typed ref ty)))
          Referent.Con ConstructorReference
_ ConstructorType
_ -> Maybe TermSlurp -> Transaction (Maybe TermSlurp)
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe TermSlurp
forall a. Maybe a
Nothing
    )
    ( (Name
 -> Set Referent -> Set Referent -> Transaction (Maybe TermSlurp))
-> WhenMatched
     Transaction Name (Set Referent) (Set Referent) TermSlurp
forall (f :: * -> *) k x y z.
Applicative f =>
(k -> x -> y -> f (Maybe z)) -> WhenMatched f k x y z
Map.zipWithMaybeAMatched \Name
name Set Referent
oldRefs Set Referent
newRefs ->
        let oldRef :: Referent
oldRef = Set Referent -> Referent
forall a. Set a -> a
Set.findMin Set Referent
oldRefs
            newRef :: Referent
newRef = Set Referent -> Referent
forall a. Set a -> a
Set.findMin Set Referent
newRefs
         in case (Referent
oldRef, Referent
newRef) of
              (Referent.Ref TermReference
oldRef1, Referent.Ref TermReference
newRef1) ->
                if TermReference
oldRef1 TermReference -> TermReference -> Bool
forall a. Eq a => a -> a -> Bool
== TermReference
newRef1
                  then
                    Maybe TermSlurp -> Transaction (Maybe TermSlurp)
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
                      if Bool
isUpdate Bool -> Bool -> Bool
|| Symbol
-> Map
     Symbol (Ann, Id, Maybe FilePath, Term Symbol Ann, Type Symbol Ann)
-> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member (Name -> Symbol
forall v. Var v => Name -> v
Name.toVar Name
name) (TypecheckedUnisonFile Symbol Ann
-> Map
     Symbol (Ann, Id, Maybe FilePath, Term Symbol Ann, Type Symbol Ann)
forall v a.
TypecheckedUnisonFile v a
-> Map v (a, Id, Maybe FilePath, Term v a, Type v a)
UF.hashTermsId TypecheckedUnisonFile Symbol Ann
unisonFile)
                        then TermSlurp -> Maybe TermSlurp
forall a. a -> Maybe a
Just TermSlurp
TermSlurp'Unchanged
                        else Maybe TermSlurp
forall a. Maybe a
Nothing
                  else do
                    oldType <- Codebase m Symbol Ann
-> TermReference -> Transaction (Type Symbol Ann)
forall a (m :: * -> *).
BuiltinAnnotation a =>
Codebase m Symbol a -> TermReference -> Transaction (Type Symbol a)
Codebase.expectTypeOfTerm Codebase m Symbol Ann
codebase TermReference
oldRef1
                    newType <- getNewRefType name newRef1
                    pure (Just (TermSlurp'Update (Updated (Typed oldRef oldType) (Typed newRef newType))))
              (Referent.Con ConstructorReference
oldRef1 ConstructorType
_, Referent.Ref TermReference
newRef1) -> do
                oldType <- Codebase m Symbol Ann
-> ConstructorReference -> Transaction (Type Symbol Ann)
forall v (m :: * -> *) a.
Ord v =>
Codebase m v a -> ConstructorReference -> Transaction (Type v a)
Codebase.expectTypeOfConstructor Codebase m Symbol Ann
codebase ConstructorReference
oldRef1
                newType <- getNewRefType name newRef1
                pure (Just (TermSlurp'Update (Updated (Typed oldRef oldType) (Typed newRef newType))))
              (Referent.Ref TermReference
oldRef1, Referent.Con ConstructorReference
newRef1 ConstructorType
_) -> do
                oldType <- Codebase m Symbol Ann
-> TermReference -> Transaction (Type Symbol Ann)
forall a (m :: * -> *).
BuiltinAnnotation a =>
Codebase m Symbol a -> TermReference -> Transaction (Type Symbol a)
Codebase.expectTypeOfTerm Codebase m Symbol Ann
codebase TermReference
oldRef1
                newType <- getNewConType name newRef1
                pure (Just (TermSlurp'Update (Updated (Typed oldRef oldType) (Typed newRef newType))))
              (Referent.Con ConstructorReference
_ ConstructorType
_, Referent.Con ConstructorReference
_ ConstructorType
_) ->
                Maybe TermSlurp -> Transaction (Maybe TermSlurp)
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe TermSlurp
forall a. Maybe a
Nothing
    )
  where
    getNewConType :: Name -> ConstructorReference -> Sqlite.Transaction (Type Symbol Ann)
    getNewConType :: Name -> ConstructorReference -> Transaction (Type Symbol Ann)
getNewConType Name
name ConstructorReference
ref =
      case Symbol
-> Map Symbol (ConstructorReferenceId, Decl Symbol Ann)
-> Maybe (ConstructorReferenceId, Decl Symbol Ann)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup (Name -> Symbol
forall v. Var v => Name -> v
Name.toVar Name
name) (TypecheckedUnisonFile Symbol Ann
-> Map Symbol (ConstructorReferenceId, Decl Symbol Ann)
forall v a.
(Ord v, Show v) =>
TypecheckedUnisonFile v a
-> Map v (ConstructorReferenceId, Decl v a)
UF.constructorsId TypecheckedUnisonFile Symbol Ann
unisonFile) of
        Just (ConstructorReference Id
_ ConstructorId
conId, Decl Symbol Ann
decl) ->
          Type Symbol Ann -> Transaction (Type Symbol Ann)
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (DataDeclaration Symbol Ann -> ConstructorId -> Type Symbol Ann
forall a v.
(Show a, Show v) =>
DataDeclaration v a -> ConstructorId -> Type v a
DataDeclaration.expectTypeOfConstructor (Decl Symbol Ann -> DataDeclaration Symbol Ann
forall v a. Decl v a -> DataDeclaration v a
DataDeclaration.asDataDecl Decl Symbol Ann
decl) ConstructorId
conId)
        Maybe (ConstructorReferenceId, Decl Symbol Ann)
Nothing -> Codebase m Symbol Ann
-> ConstructorReference -> Transaction (Type Symbol Ann)
forall v (m :: * -> *) a.
Ord v =>
Codebase m v a -> ConstructorReference -> Transaction (Type v a)
Codebase.expectTypeOfConstructor Codebase m Symbol Ann
codebase ConstructorReference
ref

    getNewRefType :: Name -> TermReference -> Sqlite.Transaction (Type Symbol Ann)
    getNewRefType :: Name -> TermReference -> Transaction (Type Symbol Ann)
getNewRefType Name
name TermReference
ref =
      case Symbol
-> Map
     Symbol (Ann, Id, Maybe FilePath, Term Symbol Ann, Type Symbol Ann)
-> Maybe
     (Ann, Id, Maybe FilePath, Term Symbol Ann, Type Symbol Ann)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup (Name -> Symbol
forall v. Var v => Name -> v
Name.toVar Name
name) (TypecheckedUnisonFile Symbol Ann
-> Map
     Symbol (Ann, Id, Maybe FilePath, Term Symbol Ann, Type Symbol Ann)
forall v a.
TypecheckedUnisonFile v a
-> Map v (a, Id, Maybe FilePath, Term v a, Type v a)
UF.hashTermsId TypecheckedUnisonFile Symbol Ann
unisonFile) of
        Just (Ann
_, Id
_, Maybe FilePath
_, Term Symbol Ann
_, Type Symbol Ann
ty) -> Type Symbol Ann -> Transaction (Type Symbol Ann)
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Type Symbol Ann
ty
        Maybe (Ann, Id, Maybe FilePath, Term Symbol Ann, Type Symbol Ann)
Nothing ->
          -- This is super unlikely in practice (but has been observed in a transcript) - the term name matches an
          -- unnamed test watch's generated name. In this case, the map lookup above (by Name.toVar name) won't find the
          -- unnamed test watch, as it has a var type of UnnamedWatch, not User.
          case Name -> Map Name (Type Symbol Ann) -> Maybe (Type Symbol Ann)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Name
name Map Name (Type Symbol Ann)
unnamedTestWatchesByName of
            Maybe (Type Symbol Ann)
Nothing -> Codebase m Symbol Ann
-> TermReference -> Transaction (Type Symbol Ann)
forall a (m :: * -> *).
BuiltinAnnotation a =>
Codebase m Symbol a -> TermReference -> Transaction (Type Symbol a)
Codebase.expectTypeOfTerm Codebase m Symbol Ann
codebase TermReference
ref
            Just Type Symbol Ann
ty -> Type Symbol Ann -> Transaction (Type Symbol Ann)
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Type Symbol Ann
ty

    unnamedTestWatchesByName :: Map Name (Type Symbol Ann)
    unnamedTestWatchesByName :: Map Name (Type Symbol Ann)
unnamedTestWatchesByName =
      ((FilePath, [(Symbol, Ann, Term Symbol Ann, Type Symbol Ann)])
 -> Map Name (Type Symbol Ann) -> Map Name (Type Symbol Ann))
-> Map Name (Type Symbol Ann)
-> [(FilePath, [(Symbol, Ann, Term Symbol Ann, Type Symbol Ann)])]
-> Map Name (Type Symbol Ann)
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (FilePath, [(Symbol, Ann, Term Symbol Ann, Type Symbol Ann)])
-> Map Name (Type Symbol Ann) -> Map Name (Type Symbol Ann)
f Map Name (Type Symbol Ann)
forall k a. Map k a
Map.empty TypecheckedUnisonFile Symbol Ann
unisonFile.watchComponents
      where
        f ::
          (WatchKind, [(Symbol, Ann, Term Symbol Ann, Type Symbol Ann)]) ->
          Map Name (Type Symbol Ann) ->
          Map Name (Type Symbol Ann)
        f :: (FilePath, [(Symbol, Ann, Term Symbol Ann, Type Symbol Ann)])
-> Map Name (Type Symbol Ann) -> Map Name (Type Symbol Ann)
f (FilePath
WatchKind.TestWatch, [(Symbol, Ann, Term Symbol Ann, Type Symbol Ann)]
component) Map Name (Type Symbol Ann)
acc = ((Symbol, Ann, Term Symbol Ann, Type Symbol Ann)
 -> Map Name (Type Symbol Ann) -> Map Name (Type Symbol Ann))
-> Map Name (Type Symbol Ann)
-> [(Symbol, Ann, Term Symbol Ann, Type Symbol Ann)]
-> Map Name (Type Symbol Ann)
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (Symbol, Ann, Term Symbol Ann, Type Symbol Ann)
-> Map Name (Type Symbol Ann) -> Map Name (Type Symbol Ann)
g Map Name (Type Symbol Ann)
acc [(Symbol, Ann, Term Symbol Ann, Type Symbol Ann)]
component
        f (FilePath, [(Symbol, Ann, Term Symbol Ann, Type Symbol Ann)])
_ Map Name (Type Symbol Ann)
acc = Map Name (Type Symbol Ann)
acc

        g ::
          (Symbol, Ann, Term Symbol Ann, Type Symbol Ann) ->
          Map Name (Type Symbol Ann) ->
          Map Name (Type Symbol Ann)
        g :: (Symbol, Ann, Term Symbol Ann, Type Symbol Ann)
-> Map Name (Type Symbol Ann) -> Map Name (Type Symbol Ann)
g (Symbol
var, Ann
_, Term Symbol Ann
_, Type Symbol Ann
ty) Map Name (Type Symbol Ann)
acc =
          case Symbol -> Type
forall v. Var v => v -> Type
Var.typeOf Symbol
var of
            Var.UnnamedWatch FilePath
_ Text
_ -> Name
-> Type Symbol Ann
-> Map Name (Type Symbol Ann)
-> Map Name (Type Symbol Ann)
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert (Symbol -> Name
forall v. Var v => v -> Name
Name.unsafeParseVar Symbol
var) Type Symbol Ann
ty Map Name (Type Symbol Ann)
acc
            Type
_ -> Map Name (Type Symbol Ann)
acc

slurpTypes ::
  Codebase m Symbol Ann ->
  TypecheckedUnisonFile Symbol Ann ->
  Bool ->
  Map Name (Set TypeReference) ->
  Map Name (Set TypeReference) ->
  Sqlite.Transaction (Map Name TypeSlurp)
slurpTypes :: forall (m :: * -> *).
Codebase m Symbol Ann
-> TypecheckedUnisonFile Symbol Ann
-> Bool
-> Map Name (Set TermReference)
-> Map Name (Set TermReference)
-> Transaction (Map Name TypeSlurp)
slurpTypes Codebase m Symbol Ann
codebase TypecheckedUnisonFile Symbol Ann
unisonFile Bool
isUpdate =
  WhenMissing Transaction Name (Set TermReference) TypeSlurp
-> WhenMissing Transaction Name (Set TermReference) TypeSlurp
-> WhenMatched
     Transaction Name (Set TermReference) (Set TermReference) TypeSlurp
-> Map Name (Set TermReference)
-> Map Name (Set TermReference)
-> Transaction (Map Name TypeSlurp)
forall (f :: * -> *) k a c b.
(Applicative f, Ord k) =>
WhenMissing f k a c
-> WhenMissing f k b c
-> WhenMatched f k a b c
-> Map k a
-> Map k b
-> f (Map k c)
Map.mergeA
    ( if Bool
isUpdate
        then (Name -> Set TermReference -> Transaction TypeSlurp)
-> WhenMissing Transaction Name (Set TermReference) TypeSlurp
forall (f :: * -> *) k x y.
Applicative f =>
(k -> x -> f y) -> WhenMissing f k x y
Map.traverseMissing \Name
_ -> (DeclOrBuiltin Symbol Ann -> TypeSlurp)
-> Transaction (DeclOrBuiltin Symbol Ann) -> Transaction TypeSlurp
forall a b. (a -> b) -> Transaction a -> Transaction b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap DeclOrBuiltin Symbol Ann -> TypeSlurp
TypeSlurp'Delete (Transaction (DeclOrBuiltin Symbol Ann) -> Transaction TypeSlurp)
-> (Set TermReference -> Transaction (DeclOrBuiltin Symbol Ann))
-> Set TermReference
-> Transaction TypeSlurp
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TermReference -> Transaction (DeclOrBuiltin Symbol Ann)
getOldDecl (TermReference -> Transaction (DeclOrBuiltin Symbol Ann))
-> (Set TermReference -> TermReference)
-> Set TermReference
-> Transaction (DeclOrBuiltin Symbol Ann)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Set TermReference -> TermReference
forall a. Set a -> a
Set.findMin
        else WhenMissing Transaction Name (Set TermReference) TypeSlurp
forall (f :: * -> *) k x y. Applicative f => WhenMissing f k x y
Map.dropMissing
    )
    ((Name -> Set TermReference -> Transaction TypeSlurp)
-> WhenMissing Transaction Name (Set TermReference) TypeSlurp
forall (f :: * -> *) k x y.
Applicative f =>
(k -> x -> f y) -> WhenMissing f k x y
Map.traverseMissing \Name
name -> (DeclOrBuiltin Symbol Ann -> TypeSlurp)
-> Transaction (DeclOrBuiltin Symbol Ann) -> Transaction TypeSlurp
forall a b. (a -> b) -> Transaction a -> Transaction b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap DeclOrBuiltin Symbol Ann -> TypeSlurp
TypeSlurp'Add (Transaction (DeclOrBuiltin Symbol Ann) -> Transaction TypeSlurp)
-> (Set TermReference -> Transaction (DeclOrBuiltin Symbol Ann))
-> Set TermReference
-> Transaction TypeSlurp
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Name -> TermReference -> Transaction (DeclOrBuiltin Symbol Ann)
getNewDecl Name
name (TermReference -> Transaction (DeclOrBuiltin Symbol Ann))
-> (Set TermReference -> TermReference)
-> Set TermReference
-> Transaction (DeclOrBuiltin Symbol Ann)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Set TermReference -> TermReference
forall a. Set a -> a
Set.findMin)
    ( (Name
 -> Set TermReference
 -> Set TermReference
 -> Transaction (Maybe TypeSlurp))
-> WhenMatched
     Transaction Name (Set TermReference) (Set TermReference) TypeSlurp
forall (f :: * -> *) k x y z.
Applicative f =>
(k -> x -> y -> f (Maybe z)) -> WhenMatched f k x y z
Map.zipWithMaybeAMatched \Name
name Set TermReference
oldRefs Set TermReference
newRefs ->
        let oldRef :: TermReference
oldRef = Set TermReference -> TermReference
forall a. Set a -> a
Set.findMin Set TermReference
oldRefs
            newRef :: TermReference
newRef = Set TermReference -> TermReference
forall a. Set a -> a
Set.findMin Set TermReference
newRefs
         in if TermReference
oldRef TermReference -> TermReference -> Bool
forall a. Eq a => a -> a -> Bool
/= TermReference
newRef
              then (TypeSlurp -> Maybe TypeSlurp)
-> Transaction TypeSlurp -> Transaction (Maybe TypeSlurp)
forall a b. (a -> b) -> Transaction a -> Transaction b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap TypeSlurp -> Maybe TypeSlurp
forall a. a -> Maybe a
Just do
                oldDecl <- TermReference -> Transaction (DeclOrBuiltin Symbol Ann)
getOldDecl TermReference
oldRef
                newDecl <- getNewDecl name newRef
                pure (TypeSlurp'Update (Updated oldDecl newDecl))
              else
                Maybe TypeSlurp -> Transaction (Maybe TypeSlurp)
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
                  if Bool
isUpdate
                    then case Symbol
-> TypecheckedUnisonFile Symbol Ann -> Maybe (Id, Decl Symbol Ann)
forall v a.
Ord v =>
v -> TypecheckedUnisonFile v a -> Maybe (Id, Decl v a)
UF.lookupDecl (Name -> Symbol
forall v. Var v => Name -> v
Name.toVar Name
name) TypecheckedUnisonFile Symbol Ann
unisonFile of
                      Maybe (Id, Decl Symbol Ann)
Nothing -> Maybe TypeSlurp
forall a. Maybe a
Nothing
                      Just (Id, Decl Symbol Ann)
_ -> TypeSlurp -> Maybe TypeSlurp
forall a. a -> Maybe a
Just TypeSlurp
TypeSlurp'Unchanged
                    else TypeSlurp -> Maybe TypeSlurp
forall a. a -> Maybe a
Just TypeSlurp
TypeSlurp'Unchanged
    )
  where
    getOldDecl :: TypeReference -> Sqlite.Transaction (DeclOrBuiltin Symbol Ann)
    getOldDecl :: TermReference -> Transaction (DeclOrBuiltin Symbol Ann)
getOldDecl = \case
      Reference.DerivedId Id
ref -> Decl Symbol Ann -> DeclOrBuiltin Symbol Ann
forall a b. b -> OrBuiltin a b
NotBuiltin (Decl Symbol Ann -> DeclOrBuiltin Symbol Ann)
-> Transaction (Decl Symbol Ann)
-> Transaction (DeclOrBuiltin Symbol Ann)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Codebase m Symbol Ann -> Id -> Transaction (Decl Symbol Ann)
forall (m :: * -> *) v a.
HasCallStack =>
Codebase m v a -> Id -> Transaction (Decl v a)
Codebase.unsafeGetTypeDeclaration Codebase m Symbol Ann
codebase Id
ref
      Reference.Builtin Text
builtin -> DeclOrBuiltin Symbol Ann -> Transaction (DeclOrBuiltin Symbol Ann)
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ConstructorType -> DeclOrBuiltin Symbol Ann
forall a b. a -> OrBuiltin a b
Builtin (Text -> ConstructorType
Builtin.expectBuiltinConstructorType Text
builtin))
    getNewDecl :: Name -> TypeReference -> Sqlite.Transaction (DeclOrBuiltin Symbol Ann)
    getNewDecl :: Name -> TermReference -> Transaction (DeclOrBuiltin Symbol Ann)
getNewDecl Name
name = \case
      Reference.DerivedId Id
ref ->
        case Symbol
-> TypecheckedUnisonFile Symbol Ann -> Maybe (Id, Decl Symbol Ann)
forall v a.
Ord v =>
v -> TypecheckedUnisonFile v a -> Maybe (Id, Decl v a)
UF.lookupDecl (Name -> Symbol
forall v. Var v => Name -> v
Name.toVar Name
name) TypecheckedUnisonFile Symbol Ann
unisonFile of
          Just (Id
_, Decl Symbol Ann
decl) -> DeclOrBuiltin Symbol Ann -> Transaction (DeclOrBuiltin Symbol Ann)
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Decl Symbol Ann -> DeclOrBuiltin Symbol Ann
forall a b. b -> OrBuiltin a b
NotBuiltin Decl Symbol Ann
decl)
          Maybe (Id, Decl Symbol Ann)
Nothing -> Decl Symbol Ann -> DeclOrBuiltin Symbol Ann
forall a b. b -> OrBuiltin a b
NotBuiltin (Decl Symbol Ann -> DeclOrBuiltin Symbol Ann)
-> Transaction (Decl Symbol Ann)
-> Transaction (DeclOrBuiltin Symbol Ann)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Codebase m Symbol Ann -> Id -> Transaction (Decl Symbol Ann)
forall (m :: * -> *) v a.
HasCallStack =>
Codebase m v a -> Id -> Transaction (Decl v a)
Codebase.unsafeGetTypeDeclaration Codebase m Symbol Ann
codebase Id
ref
      Reference.Builtin Text
builtin -> DeclOrBuiltin Symbol Ann -> Transaction (DeclOrBuiltin Symbol Ann)
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ConstructorType -> DeclOrBuiltin Symbol Ann
forall a b. a -> OrBuiltin a b
Builtin (Text -> ConstructorType
Builtin.expectBuiltinConstructorType Text
builtin))

getTermAliases :: Relation Name Referent -> Map Name TermSlurp -> Map Referent (NESet Name)
getTermAliases :: Relation Name Referent
-> Map Name TermSlurp -> Map Referent (NESet Name)
getTermAliases Relation Name Referent
existingTerms Map Name TermSlurp
slurpTerms =
  -- For the purpose of identifying aliases to call out, we omit names that are changing by this update.
  let (Set Name
changedNames, Set Referent
changedRefs) =
        ((Set Name, Set Referent)
 -> Name -> TermSlurp -> (Set Name, Set Referent))
-> (Set Name, Set Referent)
-> Map Name TermSlurp
-> (Set Name, Set Referent)
forall a k b. (a -> k -> b -> a) -> a -> Map k b -> a
Map.foldlWithKey'
          ( \ ~acc :: (Set Name, Set Referent)
acc@(Set Name
names, Set Referent
refs) Name
name -> \case
              TermSlurp'Add (Typed TermReference
ref Type Symbol Ann
_) ->
                let !names1 :: Set Name
names1 = Name -> Set Name -> Set Name
forall a. Ord a => a -> Set a -> Set a
Set.insert Name
name Set Name
names
                    !refs1 :: Set Referent
refs1 = Referent -> Set Referent -> Set Referent
forall a. Ord a => a -> Set a -> Set a
Set.insert (TermReference -> Referent
Referent.Ref TermReference
ref) Set Referent
refs
                 in (Set Name
names1, Set Referent
refs1)
              TermSlurp'Delete (Typed TermReference
ref Type Symbol Ann
_) ->
                let !names1 :: Set Name
names1 = Name -> Set Name -> Set Name
forall a. Ord a => a -> Set a -> Set a
Set.insert Name
name Set Name
names
                    !refs1 :: Set Referent
refs1 = Referent -> Set Referent -> Set Referent
forall a. Ord a => a -> Set a -> Set a
Set.insert (TermReference -> Referent
Referent.Ref TermReference
ref) Set Referent
refs
                 in (Set Name
names1, Set Referent
refs1)
              TermSlurp'Update (Updated (Typed Referent
old Type Symbol Ann
_) (Typed Referent
new Type Symbol Ann
_)) ->
                let !names1 :: Set Name
names1 = Name -> Set Name -> Set Name
forall a. Ord a => a -> Set a -> Set a
Set.insert Name
name Set Name
names
                    !refs1 :: Set Referent
refs1 = Referent -> Set Referent -> Set Referent
forall a. Ord a => a -> Set a -> Set a
Set.insert Referent
new (Referent -> Set Referent -> Set Referent
forall a. Ord a => a -> Set a -> Set a
Set.insert Referent
old Set Referent
refs)
                 in (Set Name
names1, Set Referent
refs1)
              TermSlurp
TermSlurp'Unchanged -> (Set Name, Set Referent)
acc
          )
          (Set Name
forall a. Set a
Set.empty, Set Referent
forall a. Set a
Set.empty)
          Map Name TermSlurp
slurpTerms

      step :: Map Referent (NESet Name) -> Referent -> Map Referent (NESet Name)
step Map Referent (NESet Name)
acc Referent
ref =
        let existingNames :: Set Name
existingNames = Referent -> Relation Name Referent -> Set Name
forall b a. Ord b => b -> Relation a b -> Set a
Relation.lookupRan Referent
ref Relation Name Referent
existingTerms
         in case Set Name -> Maybe (NESet Name)
forall a. Set a -> Maybe (NESet a)
Set.NonEmpty.nonEmptySet (Set Name -> Set Name -> Set Name
forall a. Ord a => Set a -> Set a -> Set a
Set.difference Set Name
existingNames Set Name
changedNames) of
              Maybe (NESet Name)
Nothing -> Map Referent (NESet Name)
acc
              Just NESet Name
aliases -> Referent
-> NESet Name
-> Map Referent (NESet Name)
-> Map Referent (NESet Name)
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert Referent
ref NESet Name
aliases Map Referent (NESet Name)
acc
   in (Map Referent (NESet Name)
 -> Referent -> Map Referent (NESet Name))
-> Map Referent (NESet Name)
-> Set Referent
-> Map Referent (NESet Name)
forall a b. (a -> b -> a) -> a -> Set b -> a
Set.foldl' Map Referent (NESet Name) -> Referent -> Map Referent (NESet Name)
step Map Referent (NESet Name)
forall k a. Map k a
Map.empty Set Referent
changedRefs

-- | A definition of the codebase that the file uses, and that itself uses something the file redefines, is made part of
-- the file, unchanged (its source is added at the end), so that the file typechecks against one version of what it
-- redefines and `update` saves that definition rebuilt. Without this, the file sees two types of the same name: its own,
-- and the codebase's through that definition. The same goes for what those definitions use, transitively, as long as
-- it depends on the redefinition.
pullInDependentsOfRedefinitions ::
  Codebase IO Symbol Ann ->
  Names ->
  Parser.ParsingEnv Sqlite.Transaction ->
  Text ->
  Text ->
  UF.UnisonFile Symbol Ann ->
  -- | The text and the file as typechecked, and what was pulled in
  Cli (Text, UF.UnisonFile Symbol Ann, Maybe PulledIn)
pullInDependentsOfRedefinitions :: Codebase IO Symbol Ann
-> Names
-> ParsingEnv Transaction
-> Text
-> Text
-> UnisonFile Symbol Ann
-> Cli (Text, UnisonFile Symbol Ann, Maybe PulledIn)
pullInDependentsOfRedefinitions Codebase IO Symbol Ann
codebase Names
names ParsingEnv Transaction
parsingEnv Text
sourceName Text
text UnisonFile Symbol Ann
uf =
  IO (Maybe ([Name], [Name], Text))
-> Cli (Maybe ([Name], [Name], Text))
forall a. IO a -> Cli a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Codebase IO Symbol Ann
-> Names
-> UnisonFile Symbol Ann
-> IO (Maybe ([Name], [Name], Text))
pulledInDefinitions Codebase IO Symbol Ann
codebase Names
names UnisonFile Symbol Ann
uf) Cli (Maybe ([Name], [Name], Text))
-> (Maybe ([Name], [Name], Text)
    -> Cli (Text, UnisonFile Symbol Ann, Maybe PulledIn))
-> Cli (Text, UnisonFile Symbol Ann, Maybe PulledIn)
forall a b. Cli a -> (a -> Cli b) -> Cli b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
    Maybe ([Name], [Name], Text)
Nothing -> (Text, UnisonFile Symbol Ann, Maybe PulledIn)
-> Cli (Text, UnisonFile Symbol Ann, Maybe PulledIn)
forall a. a -> Cli a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text
text, UnisonFile Symbol Ann
uf, Maybe PulledIn
forall a. Maybe a
Nothing)
    Just ([Name]
pulledNames, [Name]
redefinedNames, Text
source) -> do
      let (Text
text', Int
firstLine, Int
lastLine) = Text -> Text -> (Text, Int, Int)
insertAboveFold Text
text ([Name] -> Text
pulledInHeader [Name]
redefinedNames Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
source)
      uf' <-
        Transaction (Either (Err Symbol) (UnisonFile Symbol Ann))
-> Cli (Either (Err Symbol) (UnisonFile Symbol Ann))
forall a. Transaction a -> Cli a
Cli.runTransaction (FilePath
-> FilePath
-> ParsingEnv Transaction
-> Transaction (Either (Err Symbol) (UnisonFile Symbol Ann))
forall (m :: * -> *) v.
(Monad m, Var v) =>
FilePath
-> FilePath
-> ParsingEnv m
-> m (Either (Err v) (UnisonFile v Ann))
Parsers.parseFile (Text -> FilePath
Text.unpack Text
sourceName) (Text -> FilePath
Text.unpack Text
text') ParsingEnv Transaction
parsingEnv)
          Cli (Either (Err Symbol) (UnisonFile Symbol Ann))
-> (Cli (Either (Err Symbol) (UnisonFile Symbol Ann))
    -> Cli (UnisonFile Symbol Ann))
-> Cli (UnisonFile Symbol Ann)
forall a b. a -> (a -> b) -> b
& (Err Symbol -> Cli (UnisonFile Symbol Ann))
-> Cli (Either (Err Symbol) (UnisonFile Symbol Ann))
-> Cli (UnisonFile Symbol Ann)
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> m (Either a b) -> m b
onLeftM \Err Symbol
err -> Output -> Cli (UnisonFile Symbol Ann)
forall a. Output -> Cli a
Cli.returnEarly (Text -> Text -> [Err Symbol] -> Output
Output.ParseErrors Text
sourceName Text
text' [Err Symbol
err])
      -- When the source is a real file, the definitions go into it, so that errors point at lines the user can see and
      -- the user edits them like the rest. A `unison` block of a transcript has no file to write.
      env <- ask
      let path = Text -> FilePath
Text.unpack Text
sourceName
      written <- liftIO (Directory.doesFileExist path)
      when written do
        liftIO do
          Directory.removeFile path
          env.writeSource sourceName text' False
        -- The file watcher will report this write; it isn't a change of the user's.
        #latestFile ?= (path, True)
      Cli.respond (Output.PulledInDependents pulledNames written)
      pure (text', uf', Just PulledIn {names = pulledNames, starts = pulledInStarts pulledNames uf', firstLine, lastLine, written})

-- | The comment that goes above pulled-in definitions in a file, naming what the file changes. Lines of at most 70
-- characters.
pulledInHeader :: [Name] -> Text
pulledInHeader :: [Name] -> Text
pulledInHeader [Name]
changed =
  [Text] -> Text
Text.unlines (Int -> Text -> [Text]
wrapComment Int
70 Text
sentence) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\n"
  where
    sentence :: Text
sentence =
      Text
"Added these definitions from the branch, since they depend on "
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> [Text] -> Text
Text.intercalate Text
", " ((Name -> Text) -> [Name] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (\Name
n -> Text
"`" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Name -> Text
Name.toText Name
n Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"`") [Name]
changed)
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
", which this file changes. Edit them here if they no longer typecheck, and `update` will save them with the rest."

-- | A sentence as comment lines (`-- ` and the words), none longer than the width unless a word is.
wrapComment :: Int -> Text -> [Text]
wrapComment :: Int -> Text -> [Text]
wrapComment Int
width = [Text] -> [Text] -> [Text]
go [] ([Text] -> [Text]) -> (Text -> [Text]) -> Text -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Text]
Text.words
  where
    go :: [Text] -> [Text] -> [Text]
go [Text]
line [] = [[Text] -> Text
render [Text]
line | Bool -> Bool
not ([Text] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Text]
line)]
    go [Text]
line (Text
w : [Text]
ws)
      | [Text] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Text]
line = [Text] -> [Text] -> [Text]
go [Text
w] [Text]
ws
      | Text -> Int
Text.length ([Text] -> Text
render ([Text]
line [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [Text
w])) Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
width = [Text] -> [Text] -> [Text]
go ([Text]
line [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [Text
w]) [Text]
ws
      | Bool
otherwise = [Text] -> Text
render [Text]
line Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: [Text] -> [Text] -> [Text]
go [Text
w] [Text]
ws
    render :: [Text] -> Text
render [Text]
ws = Text
"-- " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> [Text] -> Text
Text.unwords [Text]
ws

-- | What 'pullInDependentsOfRedefinitions' added to a file: the names, where each starts in the text as typechecked
-- (1-based lines), and the first and last line of the added region.
data PulledIn = PulledIn
  { PulledIn -> [Name]
names :: [Name],
    PulledIn -> [(Int, Name)]
starts :: [(Int, Name)],
    PulledIn -> Int
firstLine :: Int,
    PulledIn -> Int
lastLine :: Int,
    -- | Whether the definitions were written into the file, so that its lines are the typechecked text's
    PulledIn -> Bool
written :: Bool
  }

-- | The file's text with source added where Unison still reads it: before the first fold line (a line starting with
-- `---`, which hides the rest of the file), or else at the end. Also the first and last line (1-based) of the added
-- source in the result.
insertAboveFold :: Text -> Text -> (Text, Int, Int)
insertAboveFold :: Text -> Text -> (Text, Int, Int)
insertAboveFold Text
text Text
source =
  let ([Text]
above, [Text]
below) = (Text -> Bool) -> [Text] -> ([Text], [Text])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Text -> Text -> Bool
Text.isPrefixOf Text
"---" (Text -> Bool) -> (Text -> Text) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
Text.stripStart) (Text -> [Text]
Text.lines Text
text)
      firstLine :: Int
firstLine = [Text] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Text]
above Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2
      sourceLines :: [Text]
sourceLines = Text -> [Text]
Text.lines Text
source
   in ( [Text] -> Text
Text.unlines ([Text]
above [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [Text
""] [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [Text]
sourceLines [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [Text
""] [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [Text]
below),
        Int
firstLine,
        Int
firstLine Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 ([Text] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Text]
sourceLines Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1)
      )

-- | The line (1-based) on which each of the named definitions starts in a parsed file, in order. For the definitions
-- 'pulledInDefinitions' added, which come after the file's own lines, this says which definition an error line is in.
pulledInStarts :: [Name] -> UF.UnisonFile Symbol Ann -> [(Int, Name)]
pulledInStarts :: [Name] -> UnisonFile Symbol Ann -> [(Int, Name)]
pulledInStarts [Name]
names UnisonFile Symbol Ann
uf =
  ((Int, Name) -> Int) -> [(Int, Name)] -> [(Int, Name)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Int, Name) -> Int
forall a b. (a, b) -> a
fst [(Int
line, Name
name) | Name
name <- [Name]
names, Just Int
line <- [Symbol -> Maybe Int
start (Name -> Symbol
forall v. Var v => Name -> v
Name.toVar Name
name)]]
  where
    start :: Symbol -> Maybe Int
start Symbol
v =
      (Symbol
-> Map Symbol (Ann, Term Symbol Ann)
-> Maybe (Ann, Term Symbol Ann)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Symbol
v (UnisonFile Symbol Ann -> Map Symbol (Ann, Term Symbol Ann)
forall v a. UnisonFile v a -> Map v (a, Term v a)
UF.terms UnisonFile Symbol Ann
uf) Maybe (Ann, Term Symbol Ann)
-> ((Ann, Term Symbol Ann) -> Maybe Int) -> Maybe Int
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Ann -> Maybe Int
Ann.startingLine (Ann -> Maybe Int)
-> ((Ann, Term Symbol Ann) -> Ann)
-> (Ann, Term Symbol Ann)
-> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Ann, Term Symbol Ann) -> Ann
forall a b. (a, b) -> a
fst)
        Maybe Int -> Maybe Int -> Maybe Int
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> (Symbol
-> Map Symbol (Id, DataDeclaration Symbol Ann)
-> Maybe (Id, DataDeclaration Symbol Ann)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Symbol
v (UnisonFile Symbol Ann
-> Map Symbol (Id, DataDeclaration Symbol Ann)
forall v a. UnisonFile v a -> Map v (Id, DataDeclaration v a)
UF.dataDeclarationsId UnisonFile Symbol Ann
uf) Maybe (Id, DataDeclaration Symbol Ann)
-> ((Id, DataDeclaration Symbol Ann) -> Maybe Int) -> Maybe Int
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Ann -> Maybe Int
Ann.startingLine (Ann -> Maybe Int)
-> ((Id, DataDeclaration Symbol Ann) -> Ann)
-> (Id, DataDeclaration Symbol Ann)
-> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DataDeclaration Symbol Ann -> Ann
forall v a. DataDeclaration v a -> a
DataDeclaration.annotation (DataDeclaration Symbol Ann -> Ann)
-> ((Id, DataDeclaration Symbol Ann) -> DataDeclaration Symbol Ann)
-> (Id, DataDeclaration Symbol Ann)
-> Ann
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Id, DataDeclaration Symbol Ann) -> DataDeclaration Symbol Ann
forall a b. (a, b) -> b
snd)
        Maybe Int -> Maybe Int -> Maybe Int
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> (Symbol
-> Map Symbol (Id, EffectDeclaration Symbol Ann)
-> Maybe (Id, EffectDeclaration Symbol Ann)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Symbol
v (UnisonFile Symbol Ann
-> Map Symbol (Id, EffectDeclaration Symbol Ann)
forall v a. UnisonFile v a -> Map v (Id, EffectDeclaration v a)
UF.effectDeclarationsId UnisonFile Symbol Ann
uf) Maybe (Id, EffectDeclaration Symbol Ann)
-> ((Id, EffectDeclaration Symbol Ann) -> Maybe Int) -> Maybe Int
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Ann -> Maybe Int
Ann.startingLine (Ann -> Maybe Int)
-> ((Id, EffectDeclaration Symbol Ann) -> Ann)
-> (Id, EffectDeclaration Symbol Ann)
-> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DataDeclaration Symbol Ann -> Ann
forall v a. DataDeclaration v a -> a
DataDeclaration.annotation (DataDeclaration Symbol Ann -> Ann)
-> ((Id, EffectDeclaration Symbol Ann)
    -> DataDeclaration Symbol Ann)
-> (Id, EffectDeclaration Symbol Ann)
-> Ann
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EffectDeclaration Symbol Ann -> DataDeclaration Symbol Ann
forall v a. EffectDeclaration v a -> DataDeclaration v a
DataDeclaration.toDataDecl (EffectDeclaration Symbol Ann -> DataDeclaration Symbol Ann)
-> ((Id, EffectDeclaration Symbol Ann)
    -> EffectDeclaration Symbol Ann)
-> (Id, EffectDeclaration Symbol Ann)
-> DataDeclaration Symbol Ann
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Id, EffectDeclaration Symbol Ann) -> EffectDeclaration Symbol Ann
forall a b. (a, b) -> b
snd)

-- | The name of the pulled-in definition that a line of the typechecked text is in, if it is in the pulled-in region.
pulledInDefinitionAt :: PulledIn -> Int -> Maybe Name
pulledInDefinitionAt :: PulledIn -> Int -> Maybe Name
pulledInDefinitionAt PulledIn
pulled Int
line
  | Int
line Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< PulledIn
pulled.firstLine Bool -> Bool -> Bool
|| Int
line Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> PulledIn
pulled.lastLine = Maybe Name
forall a. Maybe a
Nothing
  | Bool
otherwise = (Int, Name) -> Name
forall a b. (a, b) -> b
snd ((Int, Name) -> Name) -> Maybe (Int, Name) -> Maybe Name
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [(Int, Name)] -> Maybe (Int, Name)
forall a. [a] -> Maybe a
lastMay (((Int, Name) -> Bool) -> [(Int, Name)] -> [(Int, Name)]
forall a. (a -> Bool) -> [a] -> [a]
takeWhile ((Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
line) (Int -> Bool) -> ((Int, Name) -> Int) -> (Int, Name) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int, Name) -> Int
forall a b. (a, b) -> a
fst) PulledIn
pulled.starts)

-- | The line a type error points at, when it points somewhere.
typeErrorLine :: Context.ErrorNote Symbol Ann -> Maybe Int
typeErrorLine :: ErrorNote Symbol Ann -> Maybe Int
typeErrorLine ErrorNote Symbol Ann
note =
  TypeError Symbol Ann -> Maybe Ann
forall {v} {a}. TypeError v a -> Maybe a
site (ErrorNote Symbol Ann -> TypeError Symbol Ann
forall loc v.
(Ord loc, Show loc, Var v) =>
ErrorNote v loc -> TypeError v loc
TypeError.typeErrorFromNote ErrorNote Symbol Ann
note) Maybe Ann -> (Ann -> Maybe Int) -> Maybe Int
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Ann -> Maybe Int
Ann.startingLine
  where
    site :: TypeError v a -> Maybe a
site = \case
      TypeError.Mismatch {Term v a
mismatchSite :: Term v a
mismatchSite :: forall v loc. TypeError v loc -> Term v loc
mismatchSite} -> a -> Maybe a
forall a. a -> Maybe a
Just (Term v a -> a
forall (f :: * -> *) v a. Term f v a -> a
ABT.annotation Term v a
mismatchSite)
      TypeError.BooleanMismatch {Term v a
mismatchSite :: forall v loc. TypeError v loc -> Term v loc
mismatchSite :: Term v a
mismatchSite} -> a -> Maybe a
forall a. a -> Maybe a
Just (Term v a -> a
forall (f :: * -> *) v a. Term f v a -> a
ABT.annotation Term v a
mismatchSite)
      TypeError.ExistentialMismatch {Term v a
mismatchSite :: forall v loc. TypeError v loc -> Term v loc
mismatchSite :: Term v a
mismatchSite} -> a -> Maybe a
forall a. a -> Maybe a
Just (Term v a -> a
forall (f :: * -> *) v a. Term f v a -> a
ABT.annotation Term v a
mismatchSite)
      TypeError.ActionRestrictionFailure {Term v a
mismatchSite :: forall v loc. TypeError v loc -> Term v loc
mismatchSite :: Term v a
mismatchSite} -> a -> Maybe a
forall a. a -> Maybe a
Just (Term v a -> a
forall (f :: * -> *) v a. Term f v a -> a
ABT.annotation Term v a
mismatchSite)
      TypeError.FunctionUnderApplied {Term v a
mismatchSite :: forall v loc. TypeError v loc -> Term v loc
mismatchSite :: Term v a
mismatchSite} -> a -> Maybe a
forall a. a -> Maybe a
Just (Term v a -> a
forall (f :: * -> *) v a. Term f v a -> a
ABT.annotation Term v a
mismatchSite)
      TypeError.FunctionApplication {Term v a
f :: Term v a
f :: forall v loc. TypeError v loc -> Term v loc
f} -> a -> Maybe a
forall a. a -> Maybe a
Just (Term v a -> a
forall (f :: * -> *) v a. Term f v a -> a
ABT.annotation Term v a
f)
      TypeError.NotFunctionApplication {Term v a
f :: forall v loc. TypeError v loc -> Term v loc
f :: Term v a
f} -> a -> Maybe a
forall a. a -> Maybe a
Just (Term v a -> a
forall (f :: * -> *) v a. Term f v a -> a
ABT.annotation Term v a
f)
      TypeError.AbilityCheckFailure {a
abilityCheckFailureSite :: a
abilityCheckFailureSite :: forall v loc. TypeError v loc -> loc
abilityCheckFailureSite} -> a -> Maybe a
forall a. a -> Maybe a
Just a
abilityCheckFailureSite
      TypeError.AbilitySubtypeFailure {a
abilityCheckFailureSite :: forall v loc. TypeError v loc -> loc
abilityCheckFailureSite :: a
abilityCheckFailureSite} -> a -> Maybe a
forall a. a -> Maybe a
Just a
abilityCheckFailureSite
      TypeError.AbilityEqFailure {a
abilityCheckFailureSite :: forall v loc. TypeError v loc -> loc
abilityCheckFailureSite :: a
abilityCheckFailureSite} -> a -> Maybe a
forall a. a -> Maybe a
Just a
abilityCheckFailureSite
      TypeError.UnknownType {a
typeSite :: a
typeSite :: forall v loc. TypeError v loc -> loc
typeSite} -> a -> Maybe a
forall a. a -> Maybe a
Just a
typeSite
      TypeError.UnknownTerm {a
termSite :: a
termSite :: forall v loc. TypeError v loc -> loc
termSite} -> a -> Maybe a
forall a. a -> Maybe a
Just a
termSite
      TypeError.RedundantPattern a
loc -> a -> Maybe a
forall a. a -> Maybe a
Just a
loc
      TypeError.UncoveredPatterns a
loc NonEmpty (Pattern ())
_ -> a -> Maybe a
forall a. a -> Maybe a
Just a
loc
      TypeError v a
_ -> Maybe a
forall a. Maybe a
Nothing

-- | The definitions of the codebase to make part of a parsed file (see 'pullInDependentsOfRedefinitions'): their names,
-- and their source, rendered with the given names. The LSP uses this too, on the file as it is being edited.
pulledInDefinitions :: Codebase IO Symbol Ann -> Names -> UF.UnisonFile Symbol Ann -> IO (Maybe ([Name], [Name], Text))
pulledInDefinitions :: Codebase IO Symbol Ann
-> Names
-> UnisonFile Symbol Ann
-> IO (Maybe ([Name], [Name], Text))
pulledInDefinitions Codebase IO Symbol Ann
codebase Names
names UnisonFile Symbol Ann
uf = do
  let fileTermNames :: Set Name
fileTermNames = (Symbol -> Name) -> Set Symbol -> Set Name
forall b a. Ord b => (a -> b) -> Set a -> Set b
Set.map Symbol -> Name
forall v. Var v => v -> Name
Name.unsafeParseVar (UnisonFile Symbol Ann -> Set Symbol
forall v a. Var v => UnisonFile v a -> Set v
UFN.toTermAndWatchNames UnisonFile Symbol Ann
uf)
      fileTypeNames :: Set Name
fileTypeNames = (Symbol -> Name) -> Set Symbol -> Set Name
forall b a. Ord b => (a -> b) -> Set a -> Set b
Set.map Symbol -> Name
forall v. Var v => v -> Name
Name.unsafeParseVar (Map Symbol (Id, DataDeclaration Symbol Ann) -> Set Symbol
forall k a. Map k a -> Set k
Map.keysSet (UnisonFile Symbol Ann
-> Map Symbol (Id, DataDeclaration Symbol Ann)
forall v a. UnisonFile v a -> Map v (Id, DataDeclaration v a)
UF.dataDeclarationsId UnisonFile Symbol Ann
uf) Set Symbol -> Set Symbol -> Set Symbol
forall a. Semigroup a => a -> a -> a
<> Map Symbol (Id, EffectDeclaration Symbol Ann) -> Set Symbol
forall k a. Map k a -> Set k
Map.keysSet (UnisonFile Symbol Ann
-> Map Symbol (Id, EffectDeclaration Symbol Ann)
forall v a. UnisonFile v a -> Map v (Id, EffectDeclaration v a)
UF.effectDeclarationsId UnisonFile Symbol Ann
uf))
      redefined :: Defns (Set TermReference) (Set TermReference)
redefined =
        Defns
          { terms :: Set TermReference
terms = (Name -> Set TermReference) -> Set Name -> Set TermReference
forall m a. Monoid m => (a -> m) -> Set a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Names -> Name -> Set TermReference
Names.refTermsNamed Names
names) Set Name
fileTermNames,
            types :: Set TermReference
types = (Name -> Set TermReference) -> Set Name -> Set TermReference
forall m a. Monoid m => (a -> m) -> Set a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Names -> Name -> Set TermReference
Names.typesNamed Names
names) Set Name
fileTypeNames
          }
  if Set TermReference -> Bool
forall a. Set a -> Bool
Set.null Defns (Set TermReference) (Set TermReference)
redefined.terms Bool -> Bool -> Bool
&& Set TermReference -> Bool
forall a. Set a -> Bool
Set.null Defns (Set TermReference) (Set TermReference)
redefined.types
    then Maybe ([Name], [Name], Text) -> IO (Maybe ([Name], [Name], Text))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe ([Name], [Name], Text)
forall a. Maybe a
Nothing
    else do
      let scope :: DefnsF Set Id Id
scope =
            Set Id -> Set Id -> DefnsF Set Id Id
forall terms types. terms -> types -> Defns terms types
Defns
              ([Id] -> Set Id
forall a. Ord a => [a] -> Set a
Set.fromList [Id
id | Referent.Ref TermReference
ref <- Set Referent -> [Referent]
forall a. Set a -> [a]
Set.toList (Relation Name Referent -> Set Referent
forall a b. Relation a b -> Set b
Relation.ran Names
names.terms), Just Id
id <- [TermReference -> Maybe Id
Reference.toId TermReference
ref]])
              ([Id] -> Set Id
forall a. Ord a => [a] -> Set a
Set.fromList ((TermReference -> Maybe Id) -> [TermReference] -> [Id]
forall a b. (a -> Maybe b) -> [a] -> [b]
forall (f :: * -> *) a b.
Filterable f =>
(a -> Maybe b) -> f a -> f b
mapMaybe TermReference -> Maybe Id
Reference.toId (Set TermReference -> [TermReference]
forall a. Set a -> [a]
Set.toList (Relation Name TermReference -> Set TermReference
forall a b. Relation a b -> Set b
Relation.ran Names
names.types))))
      (pulledNames, types, terms) <-
        Codebase IO Symbol Ann
-> Transaction
     ([Name], Map TermReference (DisplayObject () (Decl Symbol Ann)),
      Map
        TermReference (DisplayObject (Type Symbol Ann) (Term Symbol Ann)))
-> IO
     ([Name], Map TermReference (DisplayObject () (Decl Symbol Ann)),
      Map
        TermReference (DisplayObject (Type Symbol Ann) (Term Symbol Ann)))
forall (m :: * -> *) v a b.
MonadIO m =>
Codebase m v a -> Transaction b -> m b
Codebase.runTransaction Codebase IO Symbol Ann
codebase do
          dependents <- DefnsF Set Id Id
-> Defns (Set TermReference) (Set TermReference)
-> Transaction (DefnsF Set Id Id)
Operations.transitiveDependentsWithinScope DefnsF Set Id Id
scope Defns (Set TermReference) (Set TermReference)
redefined
          let -- The dependents that the file doesn't define itself (its own version of a dependent is the one to use).
              affected :: Defns (Set TermReference) (Set TypeReference)
              affected =
                Set TermReference
-> Set TermReference
-> Defns (Set TermReference) (Set TermReference)
forall terms types. terms -> types -> Defns terms types
Defns
                  ((Id -> TermReference) -> Set Id -> Set TermReference
forall b a. Ord b => (a -> b) -> Set a -> Set b
Set.map Id -> TermReference
Reference.fromId DefnsF Set Id Id
dependents.terms Set TermReference -> Set TermReference -> Set TermReference
forall a. Ord a => Set a -> Set a -> Set a
`Set.difference` Defns (Set TermReference) (Set TermReference)
redefined.terms)
                  ((Id -> TermReference) -> Set Id -> Set TermReference
forall b a. Ord b => (a -> b) -> Set a -> Set b
Set.map Id -> TermReference
Reference.fromId DefnsF Set Id Id
dependents.types Set TermReference -> Set TermReference -> Set TermReference
forall a. Ord a => Set a -> Set a -> Set a
`Set.difference` Defns (Set TermReference) (Set TermReference)
redefined.types)
              used = UnisonFile Symbol Ann
-> Defns (Set TermReference) (Set TermReference)
forall a v.
(Monoid a, Var v) =>
UnisonFile v a -> Defns (Set TermReference) (Set TermReference)
UF.dependencies UnisonFile Symbol Ann
uf
              start = Set TermReference
-> Set TermReference
-> Defns (Set TermReference) (Set TermReference)
forall terms types. terms -> types -> Defns terms types
Defns (Set TermReference -> Set TermReference -> Set TermReference
forall a. Ord a => Set a -> Set a -> Set a
Set.intersection Defns (Set TermReference) (Set TermReference)
used.terms Defns (Set TermReference) (Set TermReference)
affected.terms) (Set TermReference -> Set TermReference -> Set TermReference
forall a. Ord a => Set a -> Set a -> Set a
Set.intersection Defns (Set TermReference) (Set TermReference)
used.types Defns (Set TermReference) (Set TermReference)
affected.types)
              -- What the pulled-in definitions use, as long as it is affected too.
              close Defns (Set TermReference) (Set TermReference)
acc = do
                termDeps <- [TermReference]
-> (TermReference
    -> Transaction (Defns (Set TermReference) (Set TermReference)))
-> Transaction [Defns (Set TermReference) (Set TermReference)]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
t a -> (a -> f b) -> f (t b)
for (Set TermReference -> [TermReference]
forall a. Set a -> [a]
Set.toList Defns (Set TermReference) (Set TermReference)
acc.terms) \TermReference
ref ->
                  Defns (Set TermReference) (Set TermReference)
-> (Term Symbol Ann
    -> Defns (Set TermReference) (Set TermReference))
-> Maybe (Term Symbol Ann)
-> Defns (Set TermReference) (Set TermReference)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Defns (Set TermReference) (Set TermReference)
forall a. Monoid a => a
mempty Term Symbol Ann -> Defns (Set TermReference) (Set TermReference)
forall v vt at ap a.
(Ord v, Ord vt) =>
Term2 vt at ap v a -> Defns (Set TermReference) (Set TermReference)
Term.dependencies (Maybe (Term Symbol Ann)
 -> Defns (Set TermReference) (Set TermReference))
-> Transaction (Maybe (Term Symbol Ann))
-> Transaction (Defns (Set TermReference) (Set TermReference))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Transaction (Maybe (Term Symbol Ann))
-> (Id -> Transaction (Maybe (Term Symbol Ann)))
-> Maybe Id
-> Transaction (Maybe (Term Symbol Ann))
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Maybe (Term Symbol Ann) -> Transaction (Maybe (Term Symbol Ann))
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe (Term Symbol Ann)
forall a. Maybe a
Nothing) (Codebase IO Symbol Ann
-> Id -> Transaction (Maybe (Term Symbol Ann))
forall (m :: * -> *) v a.
Codebase m v a -> Id -> Transaction (Maybe (Term v a))
Codebase.getTerm Codebase IO Symbol Ann
codebase) (TermReference -> Maybe Id
Reference.toId TermReference
ref)
                typeDeps <- for (Set.toList acc.types) \TermReference
ref ->
                  Defns (Set TermReference) (Set TermReference)
-> (Decl Symbol Ann
    -> Defns (Set TermReference) (Set TermReference))
-> Maybe (Decl Symbol Ann)
-> Defns (Set TermReference) (Set TermReference)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Defns (Set TermReference) (Set TermReference)
forall a. Monoid a => a
mempty (Set TermReference
-> Set TermReference
-> Defns (Set TermReference) (Set TermReference)
forall terms types. terms -> types -> Defns terms types
Defns Set TermReference
forall a. Set a
Set.empty (Set TermReference
 -> Defns (Set TermReference) (Set TermReference))
-> (Decl Symbol Ann -> Set TermReference)
-> Decl Symbol Ann
-> Defns (Set TermReference) (Set TermReference)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DataDeclaration Symbol Ann -> Set TermReference
forall v a. Ord v => DataDeclaration v a -> Set TermReference
DataDeclaration.typeDependencies (DataDeclaration Symbol Ann -> Set TermReference)
-> (Decl Symbol Ann -> DataDeclaration Symbol Ann)
-> Decl Symbol Ann
-> Set TermReference
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Decl Symbol Ann -> DataDeclaration Symbol Ann
forall v a. Decl v a -> DataDeclaration v a
DataDeclaration.asDataDecl)
                    (Maybe (Decl Symbol Ann)
 -> Defns (Set TermReference) (Set TermReference))
-> Transaction (Maybe (Decl Symbol Ann))
-> Transaction (Defns (Set TermReference) (Set TermReference))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Transaction (Maybe (Decl Symbol Ann))
-> (Id -> Transaction (Maybe (Decl Symbol Ann)))
-> Maybe Id
-> Transaction (Maybe (Decl Symbol Ann))
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Maybe (Decl Symbol Ann) -> Transaction (Maybe (Decl Symbol Ann))
forall a. a -> Transaction a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe (Decl Symbol Ann)
forall a. Maybe a
Nothing) (Codebase IO Symbol Ann
-> Id -> Transaction (Maybe (Decl Symbol Ann))
forall (m :: * -> *) v a.
Codebase m v a -> Id -> Transaction (Maybe (Decl v a))
Codebase.getTypeDeclaration Codebase IO Symbol Ann
codebase) (TermReference -> Maybe Id
Reference.toId TermReference
ref)
                let more = [Defns (Set TermReference) (Set TermReference)]
-> Defns (Set TermReference) (Set TermReference)
forall m. Monoid m => [m] -> m
forall (t :: * -> *) m. (Foldable t, Monoid m) => t m -> m
fold [Defns (Set TermReference) (Set TermReference)]
termDeps Defns (Set TermReference) (Set TermReference)
-> Defns (Set TermReference) (Set TermReference)
-> Defns (Set TermReference) (Set TermReference)
forall a. Semigroup a => a -> a -> a
<> [Defns (Set TermReference) (Set TermReference)]
-> Defns (Set TermReference) (Set TermReference)
forall m. Monoid m => [m] -> m
forall (t :: * -> *) m. (Foldable t, Monoid m) => t m -> m
fold [Defns (Set TermReference) (Set TermReference)]
typeDeps
                    acc' =
                      Set TermReference
-> Set TermReference
-> Defns (Set TermReference) (Set TermReference)
forall terms types. terms -> types -> Defns terms types
Defns
                        (Set TermReference -> Set TermReference -> Set TermReference
forall a. Ord a => Set a -> Set a -> Set a
Set.union Defns (Set TermReference) (Set TermReference)
acc.terms (Set TermReference -> Set TermReference -> Set TermReference
forall a. Ord a => Set a -> Set a -> Set a
Set.intersection Defns (Set TermReference) (Set TermReference)
more.terms Defns (Set TermReference) (Set TermReference)
affected.terms))
                        (Set TermReference -> Set TermReference -> Set TermReference
forall a. Ord a => Set a -> Set a -> Set a
Set.union Defns (Set TermReference) (Set TermReference)
acc.types (Set TermReference -> Set TermReference -> Set TermReference
forall a. Ord a => Set a -> Set a -> Set a
Set.intersection Defns (Set TermReference) (Set TermReference)
more.types Defns (Set TermReference) (Set TermReference)
affected.types))
                if acc' == acc then pure acc else close acc'
          pulled <- close start
          let pulledNames =
                Names
                  { terms :: Relation Name Referent
terms = Set Referent -> Relation Referent Name -> Relation Referent Name
forall a b. (Ord a, Ord b) => Set a -> Relation a b -> Relation a b
Relation.restrictDom ((TermReference -> Referent) -> Set TermReference -> Set Referent
forall b a. Ord b => (a -> b) -> Set a -> Set b
Set.map TermReference -> Referent
Referent.Ref Defns (Set TermReference) (Set TermReference)
pulled.terms) (Relation Name Referent -> Relation Referent Name
forall a b. Relation a b -> Relation b a
Relation.swap Names
names.terms) Relation Referent Name
-> (Relation Referent Name -> Relation Name Referent)
-> Relation Name Referent
forall a b. a -> (a -> b) -> b
& Relation Referent Name -> Relation Name Referent
forall a b. Relation a b -> Relation b a
Relation.swap,
                    types :: Relation Name TermReference
types = Set TermReference
-> Relation TermReference Name -> Relation TermReference Name
forall a b. (Ord a, Ord b) => Set a -> Relation a b -> Relation a b
Relation.restrictDom Defns (Set TermReference) (Set TermReference)
pulled.types (Relation Name TermReference -> Relation TermReference Name
forall a b. Relation a b -> Relation b a
Relation.swap Names
names.types) Relation TermReference Name
-> (Relation TermReference Name -> Relation Name TermReference)
-> Relation Name TermReference
forall a b. a -> (a -> b) -> b
& Relation TermReference Name -> Relation Name TermReference
forall a b. Relation a b -> Relation b a
Relation.swap
                  }
          (types, terms) <- getNamesForEdit codebase ppe pulledNames
          pure (Set.toList (Relation.dom pulledNames.terms <> Relation.dom pulledNames.types), types, terms)
      if null pulledNames
        then pure Nothing
        else do
          rendered <- newIORef Nothing
          _ <- renderToFile codebase (const True) (\Text
_ Text
txt Bool
_ -> IORef (Maybe Text) -> Maybe Text -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef IORef (Maybe Text)
rendered (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
txt)) Nothing "pulled" AboveFold ppe terms types
          let redefinedNames =
                Set Name -> [Name]
forall a. Set a -> [a]
Set.toList ((Name -> Bool) -> Set Name -> Set Name
forall a. (a -> Bool) -> Set a -> Set a
Set.filter (Bool -> Bool
not (Bool -> Bool) -> (Name -> Bool) -> Name -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Set TermReference -> Bool
forall a. Set a -> Bool
Set.null (Set TermReference -> Bool)
-> (Name -> Set TermReference) -> Name -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Names -> Name -> Set TermReference
Names.refTermsNamed Names
names) Set Name
fileTermNames)
                  [Name] -> [Name] -> [Name]
forall a. Semigroup a => a -> a -> a
<> Set Name -> [Name]
forall a. Set a -> [a]
Set.toList ((Name -> Bool) -> Set Name -> Set Name
forall a. (a -> Bool) -> Set a -> Set a
Set.filter (Bool -> Bool
not (Bool -> Bool) -> (Name -> Bool) -> Name -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Set TermReference -> Bool
forall a. Set a -> Bool
Set.null (Set TermReference -> Bool)
-> (Name -> Set TermReference) -> Name -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Names -> Name -> Set TermReference
Names.typesNamed Names
names) Set Name
fileTypeNames)
          fmap (pulledNames,redefinedNames,) <$> readIORef rendered
  where
    ppe :: PrettyPrintEnvDecl
ppe = Namer -> Suffixifier -> PrettyPrintEnvDecl
PPED.makePPED (Int -> Names -> Namer
PPE.hqNamer Int
10 Names
names) (Names -> Suffixifier
PPE.suffixifyByHashName Names
names)

parseAndTypecheckUnisonFile ::
  Names ->
  Text ->
  Text ->
  Cli (TypecheckedUnisonFile Symbol Ann)
parseAndTypecheckUnisonFile :: Names -> Text -> Text -> Cli (TypecheckedUnisonFile Symbol Ann)
parseAndTypecheckUnisonFile Names
names Text
sourceName Text
text0 = do
  let text :: Text
text = Text
text0
  pp <- Cli ProjectPath
Cli.getCurrentProjectPath
  State.modify' \LoopState
loopState ->
    LoopState
loopState
      LoopState -> (LoopState -> LoopState) -> LoopState
forall a b. a -> (a -> b) -> b
& (ASetter
  LoopState
  LoopState
  (Maybe (FilePath, Bool))
  (Maybe (FilePath, Bool))
#latestFile ASetter
  LoopState
  LoopState
  (Maybe (FilePath, Bool))
  (Maybe (FilePath, Bool))
-> Maybe (FilePath, Bool) -> LoopState -> LoopState
forall s t a b. ASetter s t a b -> b -> s -> t
.~ (FilePath, Bool) -> Maybe (FilePath, Bool)
forall a. a -> Maybe a
Just (Text -> FilePath
Text.unpack Text
sourceName, Bool
False))
      LoopState -> (LoopState -> LoopState) -> LoopState
forall a b. a -> (a -> b) -> b
& (ASetter
  LoopState
  LoopState
  (Maybe
     (Either
        (UnisonFile Symbol Ann) (TypecheckedUnisonFile Symbol Ann)))
  (Maybe
     (Either
        (UnisonFile Symbol Ann) (TypecheckedUnisonFile Symbol Ann)))
#latestTypecheckedFile ASetter
  LoopState
  LoopState
  (Maybe
     (Either
        (UnisonFile Symbol Ann) (TypecheckedUnisonFile Symbol Ann)))
  (Maybe
     (Either
        (UnisonFile Symbol Ann) (TypecheckedUnisonFile Symbol Ann)))
-> Maybe
     (Either (UnisonFile Symbol Ann) (TypecheckedUnisonFile Symbol Ann))
-> LoopState
-> LoopState
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Maybe
  (Either (UnisonFile Symbol Ann) (TypecheckedUnisonFile Symbol Ann))
forall a. Maybe a
Nothing)
  Cli.Env {codebase, generateUniqueName} <- ask
  uniqueName <- liftIO generateUniqueName
  let parsingEnv =
        Parser.ParsingEnv
          { uniqueNames :: UniqueName
uniqueNames = UniqueName
uniqueName,
            uniqueTypeGuid :: Name -> Transaction (Maybe Text)
uniqueTypeGuid = ProjectPath -> Name -> Transaction (Maybe Text)
Cli.loadUniqueTypeGuid ProjectPath
pp,
            Names
names :: Names
names :: Names
names,
            maybeNamespace :: Maybe Name
maybeNamespace = Maybe Name
forall a. Maybe a
Nothing,
            localNamespacePrefixedTypesAndConstructors :: Names
localNamespacePrefixedTypesAndConstructors = Names
forall a. Monoid a => a
mempty
          }
  unisonFile0 <-
    Cli.runTransaction (Parsers.parseFile (Text.unpack sourceName) (Text.unpack text) parsingEnv)
      & onLeftM \Err Symbol
err -> Output -> Cli (UnisonFile Symbol Ann)
forall a. Output -> Cli a
Cli.returnEarly (Text -> Text -> [Err Symbol] -> Output
Output.ParseErrors Text
sourceName Text
text [Err Symbol
err])
  (text, unisonFile, pulledIn) <- pullInDependentsOfRedefinitions codebase names parsingEnv sourceName text unisonFile0
  -- set that the file at least parsed (but didn't typecheck)
  State.modify' (& #latestTypecheckedFile .~ Just (Left unisonFile))
  typecheckingEnv <-
    Cli.runTransaction do
      computeTypecheckingEnvironment (FileParsers.ShouldUseTndr'Yes parsingEnv) codebase [] unisonFile
  let Result.Result notes maybeTypecheckedUnisonFile = FileParsers.synthesizeFile typecheckingEnv unisonFile
      tws = [Warn Symbol Ann] -> [Warn Symbol Ann]
forall a. [a] -> [a]
reverse [Warn Symbol Ann
wrn | Result.TypeWarning Warn Symbol Ann
wrn <- Seq (Note Symbol Ann) -> [Note Symbol Ann]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Seq (Note Symbol Ann)
notes]
      suffixifiedPPE = PrettyPrintEnvDecl -> PrettyPrintEnv
PPED.suffixifiedPPE PrettyPrintEnvDecl
pped
      pped =
        let ns :: Names
ns =
              Names
names
                -- Shadow just the type decl and constructor names (because the unison file didn't typecheck so we
                -- don't have term `Names`)
                Names -> (Names -> Names) -> Names
forall a b. a -> (a -> b) -> b
& Names -> Names -> Names
Names.shadowing (UnisonFile Symbol Ann -> Names
forall v a. Var v => UnisonFile v a -> Names
UF.toNames UnisonFile Symbol Ann
unisonFile)
         in Namer -> Suffixifier -> PrettyPrintEnvDecl
PPED.makePPED
              (Int -> Names -> Namer
PPE.hqNamer Int
10 Names
ns)
              ( Set Name -> Names -> Suffixifier
PPE.suffixifyByHashWithUnhashedTermsInScope
                  ( Set Name -> Set Name -> Set Name
forall a. Ord a => Set a -> Set a -> Set a
Set.union
                      ((Symbol -> Name) -> Set Symbol -> Set Name
forall b a. Ord b => (a -> b) -> Set a -> Set b
Set.map Symbol -> Name
forall v. Var v => v -> Name
Name.unsafeParseVar (Map Symbol (Ann, Term Symbol Ann) -> Set Symbol
forall k a. Map k a -> Set k
Map.keysSet (UnisonFile Symbol Ann -> Map Symbol (Ann, Term Symbol Ann)
forall v a. UnisonFile v a -> Map v (a, Term v a)
UF.terms UnisonFile Symbol Ann
unisonFile)))
                      ( ([(Symbol, Ann, Term Symbol Ann)] -> Set Name)
-> Map FilePath [(Symbol, Ann, Term Symbol Ann)] -> Set Name
forall m a. Monoid m => (a -> m) -> Map FilePath a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap
                          ( ((Symbol, Ann, Term Symbol Ann) -> Set Name)
-> [(Symbol, Ann, Term Symbol Ann)] -> Set Name
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap \case
                              (Symbol
v, Ann
_, Term Symbol Ann
_) ->
                                case Symbol -> Type
forall v. Var v => v -> Type
Var.typeOf Symbol
v of
                                  Var.User Text
_ -> Name -> Set Name
forall a. a -> Set a
Set.singleton (Symbol -> Name
forall v. Var v => v -> Name
Name.unsafeParseVar Symbol
v)
                                  Type
_ -> Set Name
forall a. Set a
Set.empty
                          )
                          (UnisonFile Symbol Ann
-> Map FilePath [(Symbol, Ann, Term Symbol Ann)]
forall v a. UnisonFile v a -> Map FilePath [(v, a, Term v a)]
UF.watches UnisonFile Symbol Ann
unisonFile)
                      )
                  )
                  Names
ns
              )
              -- A definition can still mention something the file shadowed. Name it by its name in the codebase, with
              -- the hash to tell it apart from the file's definition of that name.
              PrettyPrintEnvDecl -> PrettyPrintEnvDecl -> PrettyPrintEnvDecl
`PPED.addFallback` Namer -> Suffixifier -> PrettyPrintEnvDecl
PPED.makePPED (Int -> Names -> Namer
PPE.alwaysHqNamer Int
10 Names
names) (Names -> Suffixifier
PPE.suffixifyByHash Names
names)

  when (not $ null tws) do
    currentPath <- Cli.getCurrentPath
    Cli.respond $
      Output.TypeWarns sourceName currentPath text suffixifiedPPE tws

  maybeTypecheckedUnisonFile & onNothing do
    let tes = [ErrorNote Symbol Ann
err | Result.TypeError ErrorNote Symbol Ann
err <- Seq (Note Symbol Ann) -> [Note Symbol Ann]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Seq (Note Symbol Ann)
notes]
        cbs =
          [ CompilerBug Symbol Ann
bug
          | Result.CompilerBug (Result.TypecheckerBug CompilerBug Symbol Ann
bug) <-
              Seq (Note Symbol Ann) -> [Note Symbol Ann]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Seq (Note Symbol Ann)
notes
          ]

    when (not (null tes)) do
      currentPath <- Cli.getCurrentPath
      Cli.respond (Output.TypeErrors sourceName currentPath text suffixifiedPPE tes)
      -- An error in a definition that was pulled in is in code the user didn't write: say which definition it is in.
      for_ pulledIn \PulledIn
pulled -> Bool -> Cli () -> Cli ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not PulledIn
pulled.written) do
        let inPulledIn :: [Name]
inPulledIn = Set Name -> [Name]
forall a. Set a -> [a]
Set.toList ([Name] -> Set Name
forall a. Ord a => [a] -> Set a
Set.fromList ((ErrorNote Symbol Ann -> Maybe Name)
-> [ErrorNote Symbol Ann] -> [Name]
forall a b. (a -> Maybe b) -> [a] -> [b]
forall (f :: * -> *) a b.
Filterable f =>
(a -> Maybe b) -> f a -> f b
mapMaybe (ErrorNote Symbol Ann -> Maybe Int
typeErrorLine (ErrorNote Symbol Ann -> Maybe Int)
-> (Int -> Maybe Name) -> ErrorNote Symbol Ann -> Maybe Name
forall (m :: * -> *) a b c.
Monad m =>
(a -> m b) -> (b -> m c) -> a -> m c
>=> PulledIn -> Int -> Maybe Name
pulledInDefinitionAt PulledIn
pulled) [ErrorNote Symbol Ann]
tes))
        Bool -> Cli () -> Cli ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not ([Name] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Name]
inPulledIn)) do
          Output -> Cli ()
Cli.respond (Int -> Int -> [Name] -> Output
Output.TypeErrorsInPulledIn PulledIn
pulled.firstLine PulledIn
pulled.lastLine [Name]
inPulledIn)
    when (not (null cbs)) do
      Cli.respond (Output.CompilerBugs text suffixifiedPPE cbs)
    Cli.returnEarlyWithoutOutput

-- | Evaluate all watched expressions in a UnisonFile and return
-- their results, keyed by the name of the watch variable. The tuple returned
-- has the form:
--   (hash, (ann, sourceTerm, evaluatedTerm, isCacheHit))
--
-- where
--   `hash` is the hash of the original watch expression definition
--   `ann` gives the location of the watch expression
--   `sourceTerm` is a closed term (no free vars) for the watch expression
--   `evaluatedTerm` is the result of evaluating that `sourceTerm`
--   `isCacheHit` is True if the result was computed by just looking up
--   in a cache
--
-- It's expected that the user of this action might add the
-- `(hash, evaluatedTerm)` mapping to a cache to make future evaluations
-- of the same watches instantaneous.
evalUnisonFile ::
  EvalMode ->
  PPE.PrettyPrintEnv ->
  TypecheckedUnisonFile Symbol Ann ->
  [String] ->
  Cli
    ( Either
        Error
        ( [(Symbol, Term Symbol ())],
          Map Symbol (Ann, WatchKind, Reference.Id, Term Symbol (), Term Symbol (), Bool)
        )
    )
evalUnisonFile :: EvalMode
-> PrettyPrintEnv
-> TypecheckedUnisonFile Symbol Ann
-> [FilePath]
-> Cli
     (Either
        Error
        ([(Symbol, Term Symbol ())],
         Map
           Symbol (Ann, FilePath, Id, Term Symbol (), Term Symbol (), Bool)))
evalUnisonFile EvalMode
mode PrettyPrintEnv
ppe TypecheckedUnisonFile Symbol Ann
unisonFile [FilePath]
args = do
  env <- Cli Env
forall r (m :: * -> *). MonadReader r m => m r
ask

  let theRuntime = case EvalMode
mode of
        EvalMode
Sandboxed -> Env
env.sandboxedRuntime
        Permissive ProfileSpec
_ -> Env
env.runtime
      prof = EvalMode -> ProfileSpec
modeProfSpec EvalMode
mode

  let watchCache :: Reference.Id -> IO (Maybe (Term Symbol ()))
      watchCache Id
ref = do
        maybeTerm <- Codebase IO Symbol Ann
-> Transaction (Maybe (Term Symbol Ann))
-> IO (Maybe (Term Symbol Ann))
forall (m :: * -> *) v a b.
MonadIO m =>
Codebase m v a -> Transaction b -> m b
Codebase.runTransaction Env
env.codebase (Codebase IO Symbol Ann
-> Id -> Transaction (Maybe (Term Symbol Ann))
forall (m :: * -> *) v a.
Codebase m v a -> Id -> Transaction (Maybe (Term v a))
Codebase.lookupWatchCache Env
env.codebase Id
ref)
        pure (Term.amap (\(Ann
_ :: Ann) -> ()) <$> maybeTerm)

  Cli.with_ (withArgs args) do
    let codeLookup = Codebase IO Symbol Ann -> CodeLookup Symbol IO Ann
forall (m :: * -> *).
MonadIO m =>
Codebase m Symbol Ann -> CodeLookup Symbol m Ann
Codebase.codebaseToCodeLookup Env
env.codebase
    liftIO (Runtime.evaluateWatches codeLookup ppe prof watchCache theRuntime unisonFile) >>= \case
      Right ([(Symbol, Term Symbol ())]
nts, Response DecompError
resp, Map
  Symbol (Ann, FilePath, Id, Term Symbol (), Term Symbol (), Bool)
map) -> do
        cache <- case Response DecompError
resp of
          Runtime.DecompErrs [DecompError]
errs
            | Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ [DecompError] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [DecompError]
errs ->
                Bool
False Bool -> Cli () -> Cli Bool
forall a b. a -> Cli b -> Cli a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ [DecompError] -> Cli ()
RuntimeUtils.displayDecompileErrors [DecompError]
errs
          Runtime.Profile Pretty ColorText
prof ->
            Bool
True Bool -> Cli () -> Cli Bool
forall a b. a -> Cli b -> Cli a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Output -> Cli ()
Cli.respond (Pretty ColorText -> Output
Output.Literal Pretty ColorText
prof)
          Response DecompError
_ -> Bool -> Cli Bool
forall a. a -> Cli a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True
        for_ (Map.elems map) \(Ann
_loc, FilePath
kind, Id
hash, Term Symbol ()
_src, Term Symbol ()
value, Bool
isHit) -> do
          -- only update the watch cache when there are no errors
          Bool -> Cli () -> Cli ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not Bool
isHit Bool -> Bool -> Bool
&& Bool
cache) do
            let value' :: Term Symbol Ann
value' = (() -> Ann) -> Term Symbol () -> Term Symbol Ann
forall v a a2. Ord v => (a -> a2) -> Term v a -> Term v a2
Term.amap (\() -> Ann
Ann.External) Term Symbol ()
value
            Transaction () -> Cli ()
forall a. Transaction a -> Cli a
Cli.runTransaction (FilePath -> Id -> Term Symbol Ann -> Transaction ()
Codebase.putWatch FilePath
kind Id
hash Term Symbol Ann
value')
        pure (Right (nts, map))
      Left Error
err -> Either
  Error
  ([(Symbol, Term Symbol ())],
   Map
     Symbol (Ann, FilePath, Id, Term Symbol (), Term Symbol (), Bool))
-> Cli
     (Either
        Error
        ([(Symbol, Term Symbol ())],
         Map
           Symbol (Ann, FilePath, Id, Term Symbol (), Term Symbol (), Bool)))
forall a. a -> Cli a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error
-> Either
     Error
     ([(Symbol, Term Symbol ())],
      Map
        Symbol (Ann, FilePath, Id, Term Symbol (), Term Symbol (), Bool))
forall a b. a -> Either a b
Left Error
err)