-- | Python's @with@ statement and its context managers (D176), written as Python forms Vibe -- already has before anything else reads the module: a dataclass with @__enter__(self)@ and -- @__exit__(self, exc_type, exc, tb)@ is a context manager, and -- -- > with m as x: -- > body -- -- calls @__enter__@, binds its result, runs the body in a @try@ whose handler passes the -- exception to @__exit__@ (and raises it again unless @__exit__@ returns True) and whose -- @finally@ calls @__exit__(None, None, None)@ on every other way out (the end of the body, -- @return@, @break@, @continue@), as Python does. Several items nest. -- -- Vibe's values are copied where Python's objects are shared, so an @__enter__@ that returns -- @self@ gives the name a copy: the body's changes go back to the manager before @__exit__@ -- runs, and @__exit__@'s come back to the name after it (each class gets the two operations -- that do it, which do nothing when its @__enter__@ returns another value). @__exit__@'s -- parameters are typed as Vibe can: the exception's name and its message as @str | None@ -- (None when the body ended without one), and the traceback, always None. module Verada.Vibe.With (contextManagers) where import Verada.Diagnostics (Diagnostic (..), Phase (..), diagnostic, label) import Verada.Diagnostics.Codes (DiagCode (..)) import Verada.Vibe.Syntax import Verada.Source (Span (..)) import Control.Monad (forM, unless, when) import Control.Monad.State.Strict (State, gets, modify', runState) import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe, isNothing, listToMaybe) import Data.Text (Text) import Data.Text qualified as Text data St = St { counter :: Int , diags :: [Diagnostic] } type W = State St -- | The module with its context managers' classes completed and its @with@ statements -- written as Vibe's other forms, and what was wrong with them. contextManagers :: Module -> (Module, [Diagnostic]) contextManagers m = let classes = Map.fromList [(c.name, c) | PyStmt {node = ClassStmt c} <- m.body] (body, st) = runState (statements classes m.body) St {counter = 0, diags = []} in (Module {body}, reverse st.diags) reject :: Span -> Text -> Text -> W () reject s message what = modify' \st -> st {diags = (diagnostic VibeExcluded Syntax message) {primary = Just (label s what)} : st.diags} statements :: Map Text ClassDef -> [PyStmt] -> W [PyStmt] statements classes = fmap concat . mapM statement where within = statements classes statement st = case st.node of ClassStmt c -> do body <- within c.body c' <- managerClass classes (classWith c body) pure [again (ClassStmt c')] FunctionStmt f -> (\b -> [again (FunctionStmt (functionWith f f.parameters f.returns b))]) <$> within f.body If arms e -> do arms' <- forM arms \(c, b) -> (c,) <$> within b e' <- within e pure [again (If arms' e')] While c b e -> (\b' e' -> [again (While c b' e')]) <$> within b <*> within e For t x b e -> (\b' e' -> [again (For t x b' e')]) <$> within b <*> within e Match x cs -> (\cs' -> [again (Match x cs')]) <$> forM cs \c -> (\b -> MatchCase {pattern = c.pattern, guard = c.guard, body = b}) <$> within c.body Try b hs e f -> do b' <- within b hs' <- forM hs \h -> (\hb -> ExceptClause {span = h.span, exceptions = h.exceptions, name = h.name, body = hb}) <$> within h.body e' <- within e f' <- within f pure [again (Try b' hs' e' f')] With items b -> within b >>= withItems classes st.span items _ -> pure [st] where again node = PyStmt {span = st.span, node} -- | @with a as x, b as y:@ is @with a as x:@ around @with b as y:@. withItems :: Map Text ClassDef -> Span -> [(PyExpr, Maybe PyExpr)] -> [PyStmt] -> W [PyStmt] withItems classes sp items body = go (zip [0 ..] items) body where -- (each statement and expression made gets a place of its own, since Vibe's forms are -- told apart by their places: from the `with` keyword, where nothing written starts, to -- somewhere in the statement) limit = maximum (sp.end : [x.span.end | x <- body]) pool = [Span {file = sp.file, start = a, end = b} | a <- [sp.start .. sp.start + 3], b <- [a + 1 .. limit]] go numbered inner = case numbered of [] -> pure inner (i, (e, t)) : more -> go more inner >>= withItem classes (drop (i * placesPerItem) pool) sp e t -- | How many places one item's statements and expressions take. placesPerItem :: Int placesPerItem = 91 withItem :: Map Text ClassDef -> [Span] -> Span -> PyExpr -> Maybe PyExpr -> [PyStmt] -> W [PyStmt] withItem classes places sp e target body = do -- (a class of this module that is no context manager: said here, where it is used) case e.node of Call PyExpr {node = NameRef c} _ | Just cls <- Map.lookup c classes , not (hasMethod "__enter__" cls && hasMethod "__exit__" cls) -> reject e.span ("`" <> c <> "` is not a context manager: a `with` statement's object is of a class with `__enter__(self)` and `__exit__(self, exc_type, exc, tb)`") "no `__enter__` and `__exit__`" _ -> pure () k <- gets (.counter) modify' \st -> st {counter = k + 1} entered <- case target of Nothing -> pure ("Verada_Entered_" <> Text.pack (show (k + 1))) Just PyExpr {node = NameRef x} -> pure x Just t -> ("Verada_Entered_" <> Text.pack (show (k + 1))) <$ reject t.span "a `with` statement binds its object to a name (`with open_log() as log:`)" "not a name" let n = Text.pack (show (k + 1)) at i = fromMaybe sp (listToMaybe (drop i places)) name i x = PyExpr {span = at i, node = NameRef x} stmt i node = PyStmt {span = at i, node} arg x = Argument {keyword = Nothing, value = x} method i x m args = PyExpr {span = at i, node = Call PyExpr {span = at (i + 1), node = Attribute (name (i + 2) x) m} (map arg args)} manager = "Verada_Manager_" <> n raised = "Verada_Raised_" <> n occurrence = "Verada_Exception_" <> n suppressed = "Verada_Suppressed_" <> n exited = "Verada_Exited_" <> n kind = "Verada_Kind_" <> n message = "Verada_Message_" <> n absent = "Verada_Absent_" <> n -- (each `__exit__` call keeps the manager and the name in step around it) rejoin i = stmt i (ExprStmt (method (i + 1) manager "Verada_Rejoin" [name (i + 4) entered])) reflect i = stmt i (ExprStmt (method (i + 1) manager "Verada_Reflect" [name (i + 4) entered])) none i = PyExpr {span = at i, node = NoneLit} -- (`x: str | None = v`: what `__exit__` is given, typed, since its name may be several -- classes' operation) optional i x v = stmt i (AnnAssign (name (i + 1) x) PyExpr {span = at (i + 2), node = BinOp "|" (name (i + 3) "str") (none (i + 4))} (Just v)) handler = ExceptClause { span = at 5 , exceptions = Nothing , name = Just occurrence , body = [ stmt 6 (Assign [name 7 raised] PyExpr {span = at 8, node = BoolLit True}) , rejoin 9 -- the exception's name and message, and no traceback -- (declared, then assigned: the text the name is made into ends with that -- statement, as it does written in Vada or Varc) , optional 14 kind (none 19) , stmt 88 (Assign [name 89 kind] PyExpr {span = at 90, node = Call (name 20 "Verada_Exception_Name") [arg (name 21 occurrence)]}) , optional 22 message PyExpr {span = at 27, node = Call (name 28 "str") [arg (name 29 occurrence)]} , optional 30 absent (none 35) , stmt 36 (Assign [name 37 suppressed] (method 38 manager "Verada_Exit" [name 41 kind, name 42 message, name 43 absent])) , reflect 44 , stmt 49 (If [(PyExpr {span = at 50, node = UnaryOp "not" (name 51 suppressed)}, [stmt 52 (Raise Nothing)])] []) ] } -- (what `__exit__` returns when no exception was raised is not used, as in Python) finally = [ stmt 53 (If [(PyExpr {span = at 54, node = UnaryOp "not" (name 55 raised)}, normalExit)] []) ] normalExit = [ rejoin 56 , optional 61 absent (none 66) , stmt 67 (Assign [name 68 exited] (method 69 manager "Verada_Exit" [name 72 absent, name 73 absent, name 74 absent])) , reflect 75 , stmt 80 (If [(name 81 exited, [stmt 82 Pass])] []) ] pure [ PyStmt {span = e.span, node = Assign [name 0 manager] e} , stmt 1 (Assign [maybe (name 2 entered) (\t -> PyExpr {span = t.span, node = NameRef entered}) target] (method 3 manager "Verada_Enter" [])) , stmt 83 (AnnAssign (name 84 raised) (name 85 "bool") (Just PyExpr {span = at 86, node = BoolLit False})) , stmt 87 (Try body [handler] [] finally) ] hasMethod :: Text -> ClassDef -> Bool hasMethod n c = n `elem` [f.name | PyStmt {node = FunctionStmt f} <- c.body] -- | A class with @__enter__@ and @__exit__@: both checked and typed as Vibe takes them, and -- the two operations a @with@ statement uses to keep the manager and the name it binds in -- step. managerClass :: Map Text ClassDef -> ClassDef -> W ClassDef managerClass classes c | not (hasMethod "__enter__" c || hasMethod "__exit__" c) = pure c | otherwise = do let named n = [f | PyStmt {node = FunctionStmt f} <- c.body, f.name == n] case (named "__enter__", named "__exit__") of ([], f : _) -> reject f.nameSpan ("`" <> c.name <> "` has `__exit__` but no `__enter__`: a context manager has both, `__enter__(self)` giving what `with ... as x` binds") "no `__enter__`" (f : _, []) -> reject f.nameSpan ("`" <> c.name <> "` has `__enter__` but no `__exit__`: a context manager has both, `__exit__(self, exc_type, exc, tb)` run however the `with` statement's body ends") "no `__exit__`" _ -> pure () body <- concat <$> forM c.body \st -> case st.node of FunctionStmt f | f.name == "__enter__" -> do unless (length f.parameters == 1) (reject f.nameSpan "`__enter__` takes `self` alone" "parameters") pure [PyStmt {span = st.span, node = FunctionStmt (if selfEntering f then functionWith f f.parameters (Just PyExpr {span = f.nameSpan, node = NameRef c.name}) f.body else f)}] FunctionStmt f | f.name == "__exit__" -> do unless (length f.parameters == 4) (reject f.nameSpan "`__exit__` takes `self`, then the exception's type, the exception and its traceback (`exc_type`, `exc`, `tb`), which are None when the body ends without one" "parameters") pure [PyStmt {span = st.span, node = FunctionStmt (exitMethod f)}] _ -> pure [st] -- (a class written back from Vada or Varc has them already) helpers <- if hasMethod "Verada_Rejoin" c then pure [] else syncOperations classes c pure (classWith c (body <> helpers)) -- | Whether @__enter__@ returns its object: every @return@ is @return self@. selfEntering :: FunctionDef -> Bool selfEntering f = let returns = [v | PyStmt {node = Return v} <- ownStatements f.body] in not (null returns) && all (== Just "self") (map (fmap nameOf) returns) where nameOf x = case x.node of NameRef n -> n _ -> "" -- | @__exit__@ as Vibe types it: the exception's name, its message and the traceback as -- @str | None@ whatever their annotations, and a @bool@ result (False where Python's would -- be None: the exception is not suppressed). exitMethod :: FunctionDef -> FunctionDef exitMethod f = functionWith f (take 1 f.parameters <> [Parameter {span = p.span, name = p.name, annotation = Just optionalStr, defaultValue = p.defaultValue} | p <- drop 1 f.parameters]) (Just PyExpr {span = f.nameSpan, node = NameRef "bool"}) (falseReturns f.body <> [PyStmt {span = f.nameSpan, node = Return (Just false)} | not (endsInReturn f.body)]) where sp = f.nameSpan optionalStr = PyExpr {span = sp, node = BinOp "|" PyExpr {span = sp, node = NameRef "str"} PyExpr {span = sp, node = NoneLit}} false = PyExpr {span = sp, node = BoolLit False} falseReturns = map \st -> case st.node of Return Nothing -> PyStmt {span = st.span, node = Return (Just false)} Return (Just PyExpr {node = NoneLit}) -> PyStmt {span = st.span, node = Return (Just false)} If arms e -> PyStmt {span = st.span, node = If [(c, falseReturns b) | (c, b) <- arms] (falseReturns e)} While c b e -> PyStmt {span = st.span, node = While c (falseReturns b) (falseReturns e)} For t x b e -> PyStmt {span = st.span, node = For t x (falseReturns b) (falseReturns e)} Match x cs -> PyStmt {span = st.span, node = Match x [MatchCase {pattern = mc.pattern, guard = mc.guard, body = falseReturns mc.body} | mc <- cs]} Try b hs e fin -> PyStmt {span = st.span, node = Try (falseReturns b) [ExceptClause {span = h.span, exceptions = h.exceptions, name = h.name, body = falseReturns h.body} | h <- hs] (falseReturns e) (falseReturns fin)} _ -> st endsInReturn b = case reverse b of PyStmt {node = Return _} : _ -> True _ -> False -- | @Verada_Rejoin(self, entered)@ and @Verada_Reflect(self, entered)@: what the body did to -- the name a @with@ binds goes back to the manager, and what @__exit__@ did comes back to -- the name, when @__enter__@ returns @self@ (field by field: Python's name and manager are -- one object); nothing when it returns another value. syncOperations :: Map Text ClassDef -> ClassDef -> W [PyStmt] syncOperations classes c = case [f | PyStmt {node = FunctionStmt f} <- c.body, f.name == "__enter__"] of f : _ -> do let sp = f.nameSpan entering = selfEntering f known = fieldsOrNothing classes c fields = fromMaybe [] known name x = PyExpr {span = sp, node = NameRef x} field x n = PyExpr {span = sp, node = Attribute (name x) n} copyFields from to = [PyStmt {span = sp, node = Assign [field to n] (field from n)} | n <- fields] orPass ss = if null ss then [PyStmt {span = sp, node = Pass}] else ss enteredType = if entering then Just (name c.name) else f.returns operation n b = PyStmt { span = sp , node = FunctionStmt FunctionDef { name = n , nameSpan = sp , decorators = [] , typeParameters = [] , parameters = [Parameter {span = sp, name = "self", annotation = Nothing, defaultValue = Nothing}, Parameter {span = sp, name = "entered", annotation = enteredType, defaultValue = Nothing}] , returns = Just PyExpr {span = sp, node = NoneLit} , body = orPass b } } when (entering && isNothing known) (reject sp ("`" <> c.name <> "`'s `__enter__` returns `self`, so the name a `with` statement binds is the manager, which Vibe keeps in step field by field: its parent class is declared in another module, whose fields are not known here; declare the context manager's class without a parent from another module") "parent's fields unknown") when (not entering && isNothing f.returns) (reject sp "`__enter__` returns `self`, or says what it returns (`-> Handle`)" "no result type") pure [ operation "Verada_Rejoin" (if entering then copyFields "entered" "self" else []) , operation "Verada_Reflect" (if entering then copyFields "self" "entered" else []) ] [] -> pure [] -- | A dataclass's fields, its parents' first, when every parent is a class of the module. fieldsOrNothing :: Map Text ClassDef -> ClassDef -> Maybe [Text] fieldsOrNothing classes c = do inherited <- case [b | b@PyExpr {node = NameRef _} <- c.bases, b.node `notElem` map NameRef ignoredBases] of [] -> Just [] PyExpr {node = NameRef p} : _ -> Map.lookup p classes >>= fieldsOrNothing classes _ -> Nothing pure (inherited <> [n | PyStmt {node = AnnAssign PyExpr {node = NameRef n} _ _} <- c.body]) where ignoredBases = ["ABC", "Protocol", "Generic"] -- | The statements of a list and those nested in them, not a nested function's or class's. ownStatements :: [PyStmt] -> [PyStmt] ownStatements = concatMap \s -> s : ownStatements (concat (bodies s)) where bodies s = case s.node of If arms e -> map snd arms <> [e] While _ b e -> [b, e] For _ _ b e -> [b, e] Match _ cs -> map (.body) cs Try b hs e f -> b : map (.body) hs <> [e, f] With _ b -> [b] _ -> [] -- | A class with another body. classWith :: ClassDef -> [PyStmt] -> ClassDef classWith c body = ClassDef {name = c.name, nameSpan = c.nameSpan, typeParameters = c.typeParameters, decorators = c.decorators, bases = c.bases, keywords = c.keywords, body} -- | A function with other parameters, result and body. functionWith :: FunctionDef -> [Parameter] -> Maybe PyExpr -> [PyStmt] -> FunctionDef functionWith f parameters returns body = FunctionDef {name = f.name, nameSpan = f.nameSpan, decorators = f.decorators, typeParameters = f.typeParameters, parameters, returns, body}