-- | Vibe's meaning (vibe-syntax sections 4-5): a Vibe module's syntax tree to Varc's file -- structure over the shared AST, so that Varc's extraction, case-sensitive names and the -- rest of Verada take it from there. A module is a package (a module that only defines -- @main@ is the main subprogram); a name with a leading underscore is private to it. -- Python forms keep Python's meaning: floor division is exact floor division, @%@ is Ada's -- @mod@, comparisons chain, @and@ and @or@ short-circuit, @print@ writes Python's images; -- a local is declared where it is first assigned (a block to the end of the statements it -- is assigned in) and is a constant when assigned once. What Vibe does not take yet, or -- never, is a numbered diagnostic (B0401, B0402). module Verada.Vibe.Desugar ( desugarModule , desugarReplInput ) where import Verada.Diagnostics (Diagnostic (..), Phase (..), diagnostic, label) import Verada.Diagnostics.Codes (DiagCode (..)) import Verada.Vibe.Syntax import Verada.Vibe.Types (PyType (..), TypeEnv (..), annotationType, bindTarget, typeAnnotation) import Verada.Vibe.Types qualified as Types import Verada.Vibe.Names (resolveImportAliases) import Verada.Vibe.Parser (parseModule) import Verada.Vibe.PlainClasses (plainClasses) import Verada.Vibe.Raises (inferredRaises) import Verada.Vibe.With (contextManagers) import Verada.Varc.Extract (Extracted (..), bodySpan, extractPackage) import Verada.Varc.Syntax (FieldVisibility (..), GenericPackage (..), Item (..), ItemNode (..), VarcFile (..), VarcPackage (..), VarcUnit (..), StructDecl (..), UnitDecl (..), UnitNode (..), Visibility (..)) import Verada.Result (Result (..)) import Verada.Source (FileId (..), Span (..), mkSourceFile) import Verada.Syntax.AST.Decl qualified as D import Verada.Syntax.AST.Expr qualified as E import Verada.Syntax.AST.Stmt qualified as S import Verada.Syntax.AST.Type qualified as T import Verada.Syntax.AST.Unit qualified as U import Verada.Syntax.Frontend (ReplClass (..), ReplInput (..), ReplPart (..), ReplRead (..), ReplValue (..)) import Verada.Syntax.FormatSpec (formatCall, formatSpec) import Verada.Syntax.Pipeline (pipelineOver, substituteName) import Control.Monad (forM, forM_, unless, when) import Control.Monad.State.Strict (State, get, gets, modify', put, runState) import Data.ByteString qualified as ByteString import Data.Char (isAlphaNum, isAscii, isDigit, isLower, isUpper, ord) import Data.Data (Data, cast, gmapQ, gmapT) import Data.Functor ((<&>)) import Data.List (isPrefixOf, nub, sortOn) import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe, mapMaybe) import Data.Set (Set) import Data.Set qualified as Set import Data.Text (Text) import Data.Text qualified as Text import Data.Text.Encoding (encodeUtf8) -- | What the module declares that changes how later code reads: its classes (by kind). data ClassKind = ArrayClass | RecordClass | ScalarClass | -- | a class of `Exception`: an exception ExceptionClass | -- | a dataclass another derives from, or that derives from one, or is abstract: a tagged -- type, whose parameters take its subclasses too (`T'Class`) TaggedClass deriving stock (Eq, Show) data St = St { diags :: [Diagnostic] , classes :: Map Text ClassKind , counter :: Int , usesPrint :: Bool , usesText :: Bool -- ^ the module has Python strings as values or `str` as a type: texts (T30) , bindsOccurrences :: Bool -- ^ an `except E as e` binds the exception handled, an Ada.Exceptions.Exception_Occurrence , tagged :: Set Text -- ^ the module's classes that are tagged types (found before the classes are read) , unions :: Map Text Text -- ^ the dataclasses of a union (`type Shape = Circle | Rect`), with its name: each derives -- from the union, an abstract tagged type , unionsDeclared :: Set Text , protectedObjects :: Set Text -- ^ the module's objects of a class of `Protected`: their methods are called by name , protectedClasses :: Set Text , protocols :: Set Text -- ^ the module's classes of `Protocol`: interfaces , protocolMethods :: Map Text [FunctionDef] -- ^ their methods, which a type parameter they bound takes as formal subprograms , inProtected :: Maybe (Set Text, Bool) -- ^ in a protected operation: the components it sees, and whether it is an entry (one with -- a result is a procedure with an `out` result, as any that changes the components is) , genericClasses :: Map Text [([Text], Text)] -- ^ the module's generic classes (`class Box[T]`), each with the instances the module's -- own uses need (actual type names, instance name), declared after the generic , importedFrom :: Map Text [Text] , enums :: Map Text [Text] -- ^ the module's `Enum` classes, with their members -- ^ the names `from m import n` brings in, with their module (another module's `list[n]` -- is the one m declares) , localInstances :: Map Text [([Text], Text, [Text])] -- ^ by the module's class they follow: the instances of Python's generic types whose actuals -- name the module's own classes (each declared in the package, after its last class; an -- implicit instance at library level could not name them), with their names and actuals , owned :: Set Text , refFields :: Set Text , neverNull :: Set Text , moduleVariables :: Set Text , changedParameters :: Map Text [(Text, Bool)] -- ^ the module's functions (by name) and methods (by `.` and name), each parameter with -- whether the function changes it (inferred `in out`), through the calls it makes too -- ^ the module's own variables, which a function's `global` may name -- ^ the names (objects, parameters, fields) the module annotates `Owned[T]` alone, never -- null, and never otherwise: `del` cannot leave one null -- ^ the fields of the module's classes that are `Ref[T]`s: binding a name to one copies -- the reference (Python's sharing exactly), so the name is no view of the field , enclaveModule :: Bool -- ^ the module is a proof enclave (`enclave()`, EU1): `Ref[T]` is legal in it -- ^ the module's classes that `Owned[X]` names: each has an access type, `Owned_X`, and a -- `Free` for it , fieldNames :: Map Text [Text] -- ^ each dataclass's fields in order (for positional patterns) , generics :: Set [Text] -- ^ the generics Python's types the module names are instances of (`list`, `tuple`) , modules :: Set Text -- ^ the names imports bind (a call through one is not a method's) , sessionPackages :: Set Text -- ^ in the REPL: the packages earlier inputs declared (a dataclass's list, `Vectors_P`) , enclosing :: Set Text -- ^ in a nested function: the names of the functions around it, which its `nonlocal` may -- name , nestedFunctions :: Set Text -- ^ the nested functions in scope, which are no values (a closure does not escape) , parentClass :: Maybe Text -- ^ in a method: its class's parent, whose operations `super()` calls , starImports :: [[Text]] -- ^ the modules imported with `from m import *` , procedureFunctions :: Map Text PyExpr -- ^ the module's functions with a result that are procedures underneath because they do -- input or output, or may propagate an exception (`raises`), each with its result's -- annotation (a call of one inside an expression is made first, into a local); a method's -- name is after a `.` , genericFormals :: Set Text -- ^ the type parameters of the generic function being read (`def first[T]`) , formalPackages :: [(Text, [Text], [Text])] -- ^ its formal packages, one for each container of a type parameter it names -- (`list[T]`): the package's name, its generic, its actuals , functionParameters :: Map Text [(Text, Maybe PyExpr)] -- ^ the module's functions' parameters, in order, with their defaults , properties :: Set Text -- ^ the names of the module's classes' properties (`@property`), read as fields , enumValues :: Map Text [(Text, PyExpr)] -- ^ the module's `Enum` classes' members with the values written for them , exceptionParents :: Map Text Text -- ^ each exception class the module declares, with the one it derives from (Python's -- hierarchy, which `except` follows) , localTypes :: Map Text PyType -- ^ the types the annotations give the names in scope (Python's are a function's) , moduleTypes :: TypeEnv -- ^ the module's functions' results, its classes' fields and methods, its own names } type D = State St -- | A Vibe module (its file's base name is the package's name) as Varc's file structure. desugarModule :: Text -> Span -> Module -> Result VarcFile desugarModule unitName whole m00 = let (m0, plainDiags, _identity) = plainClasses (inferredRaises (Map.map fst builtinExceptions) m00) (m, managed0) = contextManagers m0 managed = plainDiags <> managed0 (file0, st) = runState (moduleUnits unitName whole m) (initialState m) file = extendedReturns file0 in Result {diagnostics = nub (managed <> reverse st.diags), value = Just file} initialState :: Module -> St initialState m = St {diags = [], classes = Map.empty, counter = 0, usesPrint = False, usesText = False, bindsOccurrences = False, generics = Set.empty, modules = Set.empty, tagged = Set.empty, unions = Map.empty, unionsDeclared = Set.empty, owned = Set.empty, refFields = Set.fromList [n | PyStmt {node = ClassStmt c} <- m.body, PyStmt {node = AnnAssign PyExpr {node = NameRef n} a _} <- c.body, isRefType a], neverNull = neverNullNames m, changedParameters = changedParametersOf m.body, moduleVariables = Set.fromList ([n | PyStmt {node = Assign [PyExpr {node = NameRef n}] _} <- m.body] <> [n | PyStmt {node = AnnAssign PyExpr {node = NameRef n} _ _} <- m.body]), enclaveModule = any isEnclaveMark m.body, localInstances = Map.empty, genericClasses = Map.empty, importedFrom = Map.empty, enums = Map.empty, protectedObjects = Set.empty, protectedClasses = Set.empty, protocols = Set.empty, protocolMethods = Map.empty, inProtected = Nothing, fieldNames = Map.empty, sessionPackages = Set.empty, enclosing = Set.empty, nestedFunctions = Set.empty, parentClass = Nothing, starImports = [], exceptionParents = Map.empty, enumValues = Map.empty, genericFormals = Set.empty, formalPackages = [], functionParameters = Map.fromList [(f.name, [(p.name, p.defaultValue) | p <- f.parameters]) | PyStmt {node = FunctionStmt f} <- m.body], properties = Set.fromList [f.name | PyStmt {node = ClassStmt c} <- m.body, PyStmt {node = FunctionStmt f} <- c.body, any ((== NameRef "property") . (.node)) f.decorators], procedureFunctions = procedureFunctionsOf m.body, localTypes = moduleEnv.names, moduleTypes = moduleEnv} where moduleEnv = moduleTypeEnv m.body -- | One REPL input: its imports, then the declarations Python's module -- level makes (`def`, `class`, `type`, an annotated name, and an assignment to a name the -- session has no object of), then statements (an assignment to one of the session's objects -- is an assignment, as Python's to a global); or an expression alone, whose value is shown as -- `print` shows it, or which runs as a call when it has none. The clauses Python's forms -- imply (`print`'s Ada.Text_IO) come with it. An input with a declaration after a statement -- is entered in pieces, since a piece's declarations are elaborated before its statements run. desugarReplInput :: ReplRead -> Span -> Module -> Result ReplInput desugarReplInput r whole m0 = let (m, managed) = contextManagers m0 known = initialState m prior = Map.withoutKeys (priorReplFunctions r) (replBindings m.body) priorEffects = Map.keysSet (Map.filter snd prior) priorResults = Map.mapMaybe (\(f, effectful) -> case f.returns of Just result | effectful, result.node /= NoneLit -> Just result _ -> Nothing) prior priorTypes = Map.mapMaybe (\(f, _) -> f.returns >>= annotationType) prior priorParameters = Map.map (\(f, _) -> [(p.name, p.defaultValue) | p <- f.parameters]) prior session = known { classes = Map.map kindOf r.sessionTypes , fieldNames = Map.mapMaybe fieldsOf r.sessionTypes , sessionPackages = r.packages , procedureFunctions = procedureFunctionsWith priorEffects priorResults m.body , functionParameters = Map.union known.functionParameters priorParameters , moduleTypes = known.moduleTypes {results = Map.union known.moduleTypes.results priorTypes} } (input, st) = runState (replInput r whole m) session in Result {diagnostics = managed <> reverse st.diags, value = Just (extendedReturns input)} where kindOf = \case ReplRecord _ -> RecordClass ReplTaggedRecord _ -> TaggedClass ReplArray -> ArrayClass fieldsOf = \case ReplRecord fs -> Just fs ReplTaggedRecord fs -> Just fs ReplArray -> Nothing -- | Recover a previous input's source-level callable information without guessing it -- from lowered type names. The accepted declaration decides whether the function has -- a hidden result parameter; its original source supplies the exact annotation and -- defaults. Each distinct input is parsed once, and later declarations hide earlier -- functions even when the new declaration is an object or a type. Dropped/rejected -- inputs never enter this context. priorReplFunctions :: ReplRead -> Map Text (FunctionDef, Bool) priorReplFunctions r = Map.mapMaybe function active where sources = Map.fromList [(d.span.file, bytes) | (d, bytes) <- r.priorDeclarations] parsed = Map.mapWithKey (\fid bytes -> resolveImportAliases <$> (parseModule (mkSourceFile fid "" bytes)).value) sources active = foldl' add Map.empty r.priorDeclarations add known (d, _) = foldl' (\m name -> Map.insert name d m) known (declarationNames d) function d = do spec <- case d.node of D.DSubprogram s -> Just s.spec D.DSubprogramBody b -> Just b.spec _ -> Nothing n <- case spec.name.node of E.ENameRef i -> Just i.text _ -> Nothing m <- Map.lookup spec.span.file parsed >>= id f <- listToMaybe [f | PyStmt {node = FunctionStmt f} <- m.body, f.name == n, f.nameSpan == spec.name.span] let hiddenResult = case reverse spec.profile.parameters of T.Parameter {names = [i], mode = T.ModeOut} : _ -> i.text == resultName _ -> False noResult = maybe False ((== NoneLit) . (.node)) f.returns effectful = spec.kind == D.ProcedureKind && (hiddenResult || noResult) pure (f, effectful) -- Vibe names retain case. The common AST name query folds them for Ada. declarationNames d = case d.node of D.DObject o -> map (.text) o.names D.DNumber n -> map (.text) n.names D.DType t -> t.name.text : case t.definition of T.Enumeration ls -> [i.text | T.EnumIdentifier i <- ls] _ -> [] D.DSubtype s -> [s.name.text] D.DSubprogram s -> named s.spec.name D.DSubprogramBody b -> named b.spec.name D.DPackage p -> named p.name D.DPackageBody b -> named b.name D.DPackageRenaming p -> named p.name D.DGenericRenaming g -> named g.name D.DGeneric g -> declarationNames g.unit D.DInstantiation i -> named i.name D.DObjectRenaming o -> [o.name.text] D.DException e -> map (.text) e.names _ -> [] named e = case e.node of E.ENameRef i -> [i.text] E.ESelected E.Selected {selector = E.SelectIdentifier i} -> [i.text] E.EString n -> [n] _ -> [] -- | Bindings introduced by this input shadow accepted callable metadata. A function's -- or class's local names do not shadow the session around it. replBindings :: [PyStmt] -> Set Text replBindings = Set.fromList . concatMap bound where bound s = case s.node of FunctionStmt f -> [f.name] ClassStmt c -> [c.name] TypeAlias n _ -> [n] Import path alias -> maybe (take 1 path) pure alias FromImport _ ns -> [fromMaybe n alias | (n, alias) <- ns, n /= "*"] Assign ts _ -> concatMap target ts AnnAssign t _ _ -> target t For t _ body other -> target t <> concatMap bound (body <> other) _ -> concatMap (concatMap bound) (innerBodies s) target e = case e.node of NameRef n -> [n] TupleLit xs -> concatMap target xs ListLit xs -> concatMap target xs Starred x -> target x _ -> [] replInput :: ReplRead -> Span -> Module -> D ReplInput replInput r whole m = do let defs = moduleDefinitions m imports = [s | s@PyStmt {node = n} <- defs, isImportNode n] rest = [s | s <- defs, not (isImportNode s.node)] noteModule defs imports -- (what the module's definitions tell, beside what the session's do) modify' \st -> st {modules = st.modules <> r.units, tagged = st.tagged <> Map.keysSet (Map.filter taggedRecord r.sessionTypes)} context <- concat <$> mapM importContext imports caseClashes defs procedures <- gets (.procedureFunctions) case rest of [PyStmt {node = ExprStmt e}] | not (isPrint e) -> do expression <- expr e let printed = PyStmt {span = e.span, node = ExprStmt PyExpr {span = e.span, node = Call PyExpr {span = e.span, node = NameRef "print"} [Argument {keyword = Nothing, value = e}]}} probe = PyStmt {span = e.span, node = Assign [PyExpr {span = e.span, node = NameRef "Verada_Type_Of"}] e} showing <- statements r.objects =<< pythonForms Nothing [printed] typeProbe <- statements Set.empty =<< pythonForms Nothing [probe] -- (a call Sema resolves as one: not a builtin's form, `len(x)`) asCall <- case e.node of Call {} -> statements r.objects rest <&> \case ss@[S.Stmt {node = S.SCall c}] | callShaped c -> ss _ -> [] _ -> pure [] implied <- impliedContext whole pure (ReplShown ReplValue {withClauses = context <> implied, expression, showing, asCall, typeProbe}) -- A later definition may evaluate defaults from an earlier effectful initializer. -- Finish that input first instead of moving its initialization past the definition. _ | Just boundary <- deferredDefinitionBoundary procedures rest -> pure (ReplPieces [boundary]) -- (a declaration after a statement: the input is entered as pieces, each declaring and -- then running, so that each declaration is elaborated after the statements before it) _ | breaks@(_ : _) <- [a.span.end | (a, b) <- zip rest (drop 1 rest), not (declares a), declares b] -> pure (ReplPieces breaks) _ -> do let (leading, later) = span declares rest (items, initializers, initializedObjects) <- replDeclarationItems leading let declarations = concatMap itemDeclarations items declared = Set.fromList [n.text | D.Decl {node = D.DObject o} <- declarations, n <- o.names] ss <- statements (r.objects <> declared) =<< pythonForms Nothing (initializers <> filter (not . declares) later) implied <- impliedContext whole pure (ReplUnit ReplPart {withClauses = context <> implied <> [c | Item {node = ItemImport c} <- items], declarations, statements = ss, initializedObjects}) where callShaped c = case c.node of E.EApply _ -> True E.ENameRef _ -> True E.ESelected _ -> True E.ESurfaceForm E.SurfaceForm {kind = E.FormMethod _ _} -> True _ -> False taggedRecord = \case ReplTaggedRecord _ -> True _ -> False isPrint e = case e.node of Call PyExpr {node = NameRef "print"} _ -> True _ -> False declares st = case st.node of FunctionStmt _ -> True ClassStmt _ -> True TypeAlias _ _ -> True AnnAssign PyExpr {node = NameRef _} _ (Just _) -> True Assign [PyExpr {node = NameRef n}] _ -> not (Set.member n r.objects) _ -> False -- (a REPL input's names are all the session's: Python's REPL has no private names) itemDeclarations i = case i.node of ItemDecl d -> [d] ItemStruct sd -> [D.Decl {span = i.span, node = D.DType sd.declaration}] ItemPackage p -> package id p ItemGenericPackage GenericPackage {formals, package = p} -> package (\d -> D.Decl {span = i.span, node = D.DGeneric D.GenericDecl {formals, unit = d}}) p ItemImport _ -> [] ItemInit _ -> [] where package wrap p = let Extracted {spec, body} = extractPackage p in wrap D.Decl {span = p.span, node = D.DPackage spec} : [D.Decl {span = bodySpan p, node = D.DPackageBody b} | Just b <- [body]] -- | Package-level object initializers cannot call a lowered procedure as an -- expression. Declare their typed storage, then perform the original initializers -- in the input's body, using the same hoisting as ordinary statements. Once one is -- deferred, later object initializers are deferred too, preserving evaluation order. -- The names returned here have compiler-generated unconditional initialization; -- arbitrary user assignments do not exempt a session object from its value check. replDeclarationItems :: [PyStmt] -> D ([Item], [PyStmt], [Text]) replDeclarationItems = go False where go _ [] = pure ([], [], []) go deferred (st : rest) = do procedures <- gets (.procedureFunctions) let binding = case st.node of Assign [target@PyExpr {node = NameRef n}] value -> Just (target, n, Nothing, value) AnnAssign target@PyExpr {node = NameRef n} annotation (Just value) -> Just (target, n, Just annotation, value) _ -> Nothing callsProcedure value = any (\e -> case e.node of Call PyExpr {node = NameRef n} _ -> Map.member n procedures _ -> False) (universePy value) (items, initializers, names, deferred') <- case binding of Just (target, n, written, value) | deferred || callsProcedure value -> do inferred <- pyType value annotation <- case written of Just a | isFinal a -> do reject a.span "an effectful REPL initializer needs a variable: give its value a typed variable first, then declare the Final name from that variable in another input" "constant initializer" pure a Just a -> pure a Nothing -> case value.node of Call PyExpr {node = NameRef callee} _ | Just result <- Map.lookup callee procedures -> pure result _ -> case inferred of Just t -> pure (typeAnnotation target.span t) Nothing -> do reject target.span ("give `" <> n <> "` a type for this REPL initializer: `" <> n <> ": T = ...`") "result type needed" pure PyExpr {span = target.span, node = NameRef "int"} mark <- typeExpr annotation let declaration = D.Decl {span = st.span, node = D.DObject D.ObjectDecl {names = [ident target.span n], aliased = False, constant = False, subtype = annotated annotation mark, initial = Nothing, aspects = []}} item = Item {span = st.span, visibility = visibilityOf n, node = ItemDecl declaration} initialize = PyStmt {span = st.span, node = Assign [target] value} pure ([item], [initialize], [n], True) _ -> do items <- moduleItem st pure (items, [], [], deferred) bindsTypes st (more, after, following) <- go deferred' rest pure (items <> more, initializers <> after, names <> following) isFinal a = case a.node of NameRef "Final" -> True Subscript PyExpr {node = NameRef "Final"} _ -> True _ -> False deferredDefinitionBoundary :: Map Text PyExpr -> [PyStmt] -> Maybe Int deferredDefinitionBoundary procedures = go Nothing where go _ [] = Nothing go pending (st : rest) = case st.node of FunctionStmt _ -> definition ClassStmt _ -> definition TypeAlias _ _ -> definition Assign [PyExpr {node = NameRef _}] value -> next value AnnAssign PyExpr {node = NameRef _} _ (Just value) -> next value _ -> Nothing where definition = case pending of Just boundary -> Just boundary Nothing -> go Nothing rest next value | isJust pending || any callsProcedure (universePy value) = go (Just st.span.end) rest | otherwise = go Nothing rest callsProcedure e = case e.node of Call PyExpr {node = NameRef n} _ -> Map.member n procedures _ -> False -- | A module's definitions: what is left out of its meaning (Vibe's own imports, the main -- guard, docstrings, the enclave mark) left out. moduleDefinitions :: Module -> [PyStmt] moduleDefinitions m = [s | s <- m.body, not (isPreludeImport s), not (isMainGuard s), not (isDocstring s), not (isEnclaveMark s)] -- | What a module's definitions tell the desugaring before it reads them: its imported -- modules, generic classes, protocols, unions and the like. noteModule :: [PyStmt] -> [PyStmt] -> D () noteModule defs imports = modify' \st -> st {enumValues = Map.fromList [(c.name, [(n, v) | PyStmt {node = Assign [PyExpr {node = NameRef n}] v} <- c.body]) | PyStmt {node = ClassStmt c} <- defs, [PyExpr {node = NameRef "Enum"}] <- [c.bases]], enums = Map.fromList [(c.name, [n | PyStmt {node = Assign [PyExpr {node = NameRef n}] _} <- c.body]) | PyStmt {node = ClassStmt c} <- defs, [PyExpr {node = NameRef "Enum"}] <- [c.bases]], modules = Set.fromList ([n | PyStmt {node = Import (n : _) _} <- imports] <> [n | PyStmt {node = FromImport (n : _) _} <- imports]), localInstances = localInstancesOf defs, genericClasses = genericClassesOf defs, importedFrom = Map.fromList [(n, path) | PyStmt {node = FromImport path names} <- imports, (n, Nothing) <- names, n /= "*"], starImports = [path | PyStmt {node = FromImport path names} <- imports, ("*", _) <- names], owned = ownedClasses defs, protocols = Set.fromList [c.name | PyStmt {node = ClassStmt c} <- defs, [PyExpr {node = NameRef "Protocol"}] <- [c.bases]], protocolMethods = Map.fromList [(c.name, [f | PyStmt {node = FunctionStmt f} <- c.body]) | PyStmt {node = ClassStmt c} <- defs, [PyExpr {node = NameRef "Protocol"}] <- [c.bases]], tagged = taggedClasses defs <> Set.fromList (concat [u : ms | (u, ms) <- unionsOf defs]), unions = Map.fromList [(member, u) | (u, ms) <- unionsOf defs, member <- ms]} -- | `xs: list[T] = []`, statements, then `return xs`: the container is built in the -- function's result, as an extended return (`return xs : T do ... end return;`), since a -- container is limited and Ada returns a limited object only so (RM 7.5). extendedReturns :: (Data a) => a -> a extendedReturns x = case cast x of Just st -> fromMaybe x (cast (asExtendedReturn (gmapT extendedReturns (st :: S.Stmt)))) Nothing -> gmapT extendedReturns x where asExtendedReturn st = case st.node of S.SBlock b | Just [D.Decl {node = D.DObject o}] <- b.declarations , [n] <- o.names , not o.constant , container o.subtype , null b.handlers , Just (body, S.Stmt {node = S.SReturn (Just E.Expr {node = E.ENameRef r})}) <- unsnocList b.statements , r.text == n.text , not (any returns body) -> S.Stmt {span = st.span, node = S.SExtendedReturn S.ExtendedReturn {name = n, aliased = o.aliased, constant = False, subtype = o.subtype, initial = o.initial, aspects = o.aspects, statements = if null body then Nothing else Just body}} _ -> st container = \case T.Indication E.SubtypeIndication {mark = E.Expr {node = E.ESelected E.Selected {prefix = E.Expr {node = E.EInstance i}}}} -> lastOf i.generic `elem` ["Vectors", "Dictionaries", "Ordered_Sets"] _ -> False lastOf e = case e.node of E.ENameRef i -> i.text E.ESelected E.Selected {selector = E.SelectIdentifier i} -> i.text _ -> "" unsnocList xs = case reverse xs of l : rest -> Just (reverse rest, l) [] -> Nothing -- (a statement that returns, anywhere inside: such a body is left as it is) returns :: (Data b) => b -> Bool returns y = case cast y of Just S.Stmt {node = S.SReturn _} -> True Just S.Stmt {node = S.SExtendedReturn _} -> True _ -> or (gmapQ returns y) reject :: Span -> Text -> Text -> D () reject s message what = modify' \st -> st {diags = (diagnostic VibeExcluded Syntax message) {primary = Just (label s what)} : st.diags} ident :: Span -> Text -> E.Identifier ident s t = E.Identifier {span = s, text = t} nameE :: Span -> Text -> E.Expr nameE s t = E.Expr {span = s, node = E.ENameRef (ident s t)} -- | @A.B.C@ from its parts. dottedE :: Span -> [Text] -> E.Expr dottedE s = \case [] -> nameE s "" first : rest -> foldl (\p n -> E.Expr {span = s, node = E.ESelected E.Selected {prefix = p, selector = E.SelectIdentifier (ident s n)}}) (nameE s first) rest -- * Units moduleUnits :: Text -> Span -> Module -> D VarcFile moduleUnits unitName whole m = do let defs = moduleDefinitions m imports = [s | s@PyStmt {node = n} <- defs, isImportNode n] rest = [s | s <- defs, not (isImportNode s.node)] noteModule defs imports context <- concat <$> mapM importContext imports caseClashes defs case rest of -- a module that defines `main` (or the function its `if __name__ == "__main__":` calls) -- and only functions besides: the main subprogram, the other functions nested in it -- (where Python's module scope would have them) _ | [f] <- [g | PyStmt {node = FunctionStmt g} <- rest, g.name == mainName] , all isFunction rest -> do helpers <- mapM (functionDecl Public) [g | PyStmt {node = FunctionStmt g} <- rest, g.name /= mainName] decl <- functionDecl Public f implied <- impliedContext whole let nested d = case d.node of D.DSubprogramBody b -> D.Decl {span = d.span, node = D.DSubprogramBody D.SubprogramBody {spec = b.spec, aspects = b.aspects, declarations = map itemDecl helpers <> b.declarations, statements = b.statements, handlers = b.handlers, endName = b.endName}} _ -> d pure VarcFile {units = [VarcUnit {span = whole, context = context <> implied, privateChild = False, node = UnitDeclaration UnitDecl {visibility = Hidden, decl = nested (itemDecl decl)}}]} -- a module that defines `main` and plain declarations besides (types as well as -- functions): the main subprogram, with them nested in it, as for functions alone _ | [f] <- [g | PyStmt {node = FunctionStmt g} <- rest, g.name == mainName] -> do -- (read as declarations to nest; a package after all reads them again from here, as -- what reading them noted, a union's root declared, is then the package's) before <- get others <- concat <$> mapM moduleItem [x | x <- rest, not (isMainDef x)] let plain = [d | Item {node = ItemDecl d} <- others] if length plain == length others then do decl <- functionDecl Public f implied <- impliedContext whole let nested d = case d.node of D.DSubprogramBody b -> D.Decl {span = d.span, node = D.DSubprogramBody D.SubprogramBody {spec = b.spec, aspects = b.aspects, declarations = plain <> b.declarations, statements = b.statements, handlers = b.handlers, endName = b.endName}} _ -> d pure VarcFile {units = [VarcUnit {span = whole, context = context <> implied, privateChild = False, node = UnitDeclaration UnitDecl {visibility = Hidden, decl = nested (itemDecl decl)}}]} else put before >> packaged _ -> packaged where isMainDef x = case x.node of FunctionStmt g -> g.name == mainName _ -> False mainName = case [n | x@PyStmt {node = If [(_, [PyStmt {node = ExprStmt PyExpr {node = Call PyExpr {node = NameRef n} []}}])] []} <- m.body, isMainGuard x] of n : _ -> n [] -> "main" packaged = do let defs = [s | s <- m.body, not (isPreludeImport s), not (isMainGuard s), not (isDocstring s), not (isEnclaveMark s)] imports = [s | s@PyStmt {node = n} <- defs, isImportNode n] rest = [s | s <- defs, not (isImportNode s.node)] context <- concat <$> mapM importContext imports items <- concat <$> mapM moduleItem rest implied <- impliedContext whole -- a generic class is a generic library unit of its own, `M_Generic_Box`, beside the -- module's package: the instances the package declares are then of a generic whose -- body is elaborated before them let classes = [(cn, gp) | Item {node = ItemGenericPackage gp} <- items, E.ENameRef n <- [gp.package.name.node], Just cn <- [Text.stripPrefix "Generic_" n.text]] libraryName cn = unitName <> "_Generic_" <> cn renamed :: (Data x) => x -> x renamed x = case cast x of Just (e :: E.Expr) | E.ENameRef n <- e.node, Just cn <- Text.stripPrefix "Generic_" n.text, cn `elem` map fst classes -> fromMaybe x (cast (nameE e.span (libraryName cn))) _ -> gmapT renamed x withs = [U.ContextWith U.WithClause {span = whole, limited = False, private = False, names = [nameE whole (libraryName cn)]} | (cn, _) <- classes] classUnits = [VarcUnit {span = gp.package.span, context = context <> implied, privateChild = False, node = UnitGenericPackage (renamed gp)} | (_, gp) <- classes] -- (`enclave()`: the module is a proof enclave, EU1) enclaveAspect = [E.AspectSpec {span = s.span, mark = ident s.span "Annotate", classWide = False, value = Just E.Expr {span = s.span, node = E.EAggregate E.Aggregate {bracket = False, contents = E.PlainAggregate (E.Associations [E.PositionalAssoc (nameE s.span "Verada"), E.PositionalAssoc (nameE s.span "Enclave")])}}} | s <- m.body, isEnclaveMark s] package = VarcPackage {span = whole, name = nameE whole unitName, aspects = enclaveAspect, items = renamed [i | i <- items, not (isClass i)]} isClass i = case i.node of ItemGenericPackage gp | E.ENameRef n <- gp.package.name.node -> "Generic_" `Text.isPrefixOf` n.text _ -> False -- (a module that declares types beside its `main`, and runs it under `if __name__ == -- "__main__":`, is a package; the program is a procedure that calls its `main`) program <- if hasGuard && any isMainDef rest then do let callMain = PyStmt {span = whole, node = ExprStmt PyExpr {span = whole, node = Call PyExpr {span = whole, node = Attribute PyExpr {span = whole, node = NameRef unitName} mainName} []}} entry <- functionDecl Public FunctionDef {name = unitName <> "_Program", nameSpan = whole, decorators = [], typeParameters = [], parameters = [], returns = Just PyExpr {span = whole, node = NoneLit}, body = [callMain]} pure [VarcUnit {span = whole, context = [U.ContextWith U.WithClause {span = whole, limited = False, private = False, names = [nameE whole unitName]}], privateChild = False, node = UnitDeclaration UnitDecl {visibility = Hidden, decl = itemDecl entry}}] else pure [] pure VarcFile {units = classUnits <> [VarcUnit {span = whole, context = context <> implied <> withs, privateChild = False, node = UnitPackage package}] <> program} hasGuard = any isMainGuard m.body itemDecl i = case i.node of ItemDecl d -> d _ -> D.Decl {span = whole, node = D.DError} isFunction st = case st.node of FunctionStmt _ -> True _ -> False data Named = Named { span :: Span , name :: Text } -- | A method: a primitive subprogram whose first parameter, `self`, is of the class (any of -- its others of a tagged class take subclasses too). An `@abstractmethod` is abstract. methodItem :: Text -> FunctionDef -> D Item methodItem cls f = do let abstractMethod = any (\d -> d.node == NameRef "abstractmethod") f.decorators withSelf = case f.parameters of p : rest | p.name == "self", isNothing p.annotation -> p {annotation = Just PyExpr {span = p.span, node = NameRef cls}} : rest ps -> ps unless (case f.parameters of p : _ -> p.name == "self"; _ -> False) (reject f.nameSpan "a method takes `self` first; a function of the module is written outside the class" "no `self`") when (Text.isPrefixOf "__" f.name) (reject f.nameSpan ("Vibe does not take the special method `" <> f.name <> "`: Vibe's are `__str__`, `__repr__`, `__eq__`, `__lt__`, `__le__`, `__gt__`, `__ge__`, `__add__`, `__sub__`, `__mul__`, `__truediv__`, `__neg__`, `__len__`, `__getitem__`, `__setitem__` and `__contains__` (a dataclass makes its own `__init__`); give this operation an ordinary name and call it") "special method") -- (`@property`: a method without parameters, read as a field, `b.double`, which Sema -- resolves to the type's function of the name; a setter is not taken) forM_ [d | d@PyExpr {node = Attribute _ a} <- f.decorators, a `elem` ["setter", "deleter", "getter"]] \d -> reject d.span "a property's setter is not in Vibe: assign the field, or give the class a method that sets it" "setter" when (any ((== NameRef "property") . (.node)) f.decorators && length f.parameters /= 1) (reject f.nameSpan "a property takes `self` alone" "parameters") i <- functionDecl (visibilityOf f.name) f {parameters = withSelf, decorators = [d | d <- f.decorators, d.node `notElem` [NameRef "abstractmethod", NameRef "property"], not (isAccessor d)], body = if abstractMethod then [] else f.body} pure if abstractMethod then abstractOf i else i where isAccessor d = case d.node of Attribute _ a -> a `elem` ["setter", "deleter", "getter"] _ -> False -- (an abstract method's body is `...`) abstractOf i = case i.node of ItemDecl D.Decl {span = sp, node = D.DSubprogramBody b} -> Item {span = i.span, visibility = i.visibility, node = ItemDecl D.Decl {span = sp, node = D.DSubprogram D.SubprogramDecl {spec = b.spec, form = D.AbstractSpec, aspects = b.aspects}}} ItemDecl D.Decl {span = sp, node = D.DSubprogram d} -> Item {span = i.span, visibility = i.visibility, node = ItemDecl D.Decl {span = sp, node = D.DSubprogram D.SubprogramDecl {spec = d.spec, form = D.AbstractSpec, aspects = d.aspects}}} _ -> i -- | The instances of Python's generic types (`list[P]`) whose actuals are the module's own -- classes, by the last of those classes in the module: the instance follows it. localInstancesOf :: [PyStmt] -> Map Text [([Text], Text, [Text])] localInstancesOf defs = Map.fromListWith (flip (<>)) [(lastOf actuals, [(generic, instanceName generic actuals, actuals)]) | (generic, actuals) <- nub (uses defs <> everyList)] where -- (a class's, and a bounded type's, `type T = Annotated[float, Ge(a), Le(b)]`, whose -- lists are the module's own too) classOrder = concat [case d.node of { ClassStmt c -> [c.name]; TypeAlias n PyExpr {node = Subscript PyExpr {node = NameRef "Annotated"} _} -> [n]; _ -> [] } | d <- defs] -- (every dataclass has its list, so that another module's `list[P]` is the same type: -- it names this one) -- (one whose fields are all plain values: an owner or a container has no copy) -- (not an abstract class's, which has no objects of its own to hold) everyList = [(["Verada", "Containers", "Unbounded", "Vectors"], [c.name]) | PyStmt {node = ClassStmt c} <- defs, any (\d -> d.node == NameRef "dataclass") c.decorators, all plainField c.body, not (abstractClass c)] abstractClass c = any (\b -> b.node == NameRef "ABC") c.bases || not (null [() | PyStmt {node = FunctionStmt f} <- c.body, any (\d -> d.node == NameRef "abstractmethod") f.decorators]) plainField st = case st.node of AnnAssign _ PyExpr {node = Subscript _ _} _ -> False AnnAssign _ PyExpr {node = BinOp _ _ _} _ -> False _ -> True lastOf actuals = case [c | c <- reverse classOrder, c `elem` actuals || ("Owned_" <> c) `elem` actuals] of c : _ -> c [] -> "" instanceName generic actuals = Text.intercalate "_" (lastOf' generic : actuals) lastOf' g = maybe "" id (listToMaybe (reverse g)) -- (an element type by its name: a class's, or a reference's to one, `Ref[C]`, EU2) elementName e = case e.node of NameRef a -> Just a Subscript PyExpr {node = NameRef r} [PyExpr {node = NameRef c}] | r `elem` ["Ref", "Owned"] -> Just ("Owned_" <> c) _ -> Nothing uses :: (Data a) => a -> [([Text], [Text])] uses x = here <> concat (gmapQ uses x) where here = case cast x of Just PyExpr {node = BinOp "|" member@PyExpr {node = NameRef _} PyExpr {node = NoneLit}} | Just a <- elementName member , a `elem` classOrder -> [(["Verada", "Optionals"], [builtinType a])] Just PyExpr {node = Subscript PyExpr {node = NameRef n} elements} | Just (generic, _) <- pythonGeneric n (length elements) , let actuals = mapMaybe elementName elements , length actuals == length elements , any (\a -> a `elem` classOrder || any (\c -> a == "Owned_" <> c) classOrder) actuals -> [(generic, map builtinType actuals)] _ -> [] -- | The module's generic classes, each with the instances its uses in the module need. -- | A class named, perhaps through its module: `Box`, `m.Box`. classPath :: PyExpr -> Maybe [Text] classPath e = case e.node of NameRef n -> Just [n] Attribute PyExpr {node = NameRef m} n -> Just [m, n] _ -> Nothing genericClassesOf :: [PyStmt] -> Map Text [([Text], Text)] genericClassesOf defs = Map.fromList [(c, nub [(as, Text.intercalate "_" (c : as)) | (g, as) <- uses defs, g == c]) | c <- generic] where generic = [c.name | PyStmt {node = ClassStmt c} <- defs, not (null c.typeParameters)] uses :: (Data a) => a -> [(Text, [Text])] uses x = here <> concat (gmapQ uses x) where here = case cast x of Just PyExpr {node = Subscript PyExpr {node = NameRef n} elements} | n `elem` generic , let actuals = [builtinType a | PyExpr {node = NameRef a} <- elements] , length actuals == length elements , not (builtinActuals elements) -> [(n, actuals)] _ -> [] -- | Whether a generic class's actuals are all Python's own types (`int`, `float`, `bool`, -- `str`): its instance is then a library-level implicit one, the same in every module that -- names it, so that values pass between them. builtinActuals :: [PyExpr] -> Bool builtinActuals = all \e -> case e.node of NameRef a -> a `elem` ["int", "float", "bool", "str"] _ -> False -- | The module's classes `Owned[X]` names anywhere in it. ownedClasses :: [PyStmt] -> Set Text ownedClasses defs = Set.intersection classNames (Set.unions (map named defs)) where classNames = Set.fromList [c.name | PyStmt {node = ClassStmt c} <- defs] named :: (Data a) => a -> Set Text named x = here <> Set.unions (gmapQ named x) where here = case cast x of Just PyExpr {node = Subscript PyExpr {node = NameRef r} [PyExpr {node = NameRef n}]} | r `elem` ["Owned", "Ref"] -> Set.singleton n _ -> Set.empty -- | Module-level names that differ only in case (`buffer = Buffer()`): Ada does not tell -- them apart, and other modules see both. caseClashes :: [PyStmt] -> D () caseClashes defs = forM_ clashes \(later, earlier) -> reject later.span ("`" <> later.name <> "` and `" <> earlier.name <> "` differ only in case, which Ada (and so Verada) does not tell apart: rename one, as `" <> later.name <> "_obj` or `" <> earlier.name <> "Type`") "same name as another" where named = concat [names st | st <- defs] names st = case st.node of ClassStmt c -> [Named {span = c.nameSpan, name = c.name}] FunctionStmt f -> [Named {span = f.nameSpan, name = f.name}] TypeAlias n _ -> [Named {span = st.span, name = n}] Assign [PyExpr {node = NameRef n, span = sp}] _ -> [Named {span = sp, name = n}] AnnAssign PyExpr {node = NameRef n, span = sp} _ _ -> [Named {span = sp, name = n}] _ -> [] clashes = [(x, y) | (i, x) <- zip [0 :: Int ..] named, (j, y) <- zip [0 ..] named, j < i, x.name /= y.name, Text.toCaseFold x.name == Text.toCaseFold y.name] -- | The unions of a module's dataclasses: `type U = A | B`, with A and B classes of it. unionsOf :: [PyStmt] -> [(Text, [Text])] unionsOf defs = [(u, ms) | PyStmt {node = TypeAlias u v} <- defs, Just ms <- [members v], all (`Set.member` classNames) ms] where classNames = Set.fromList [c.name | PyStmt {node = ClassStmt c} <- defs] members v = case v.node of BinOp "|" a b -> (<>) <$> members a <*> members b NameRef n -> Just [n] _ -> Nothing -- | A method of a class of `Protected`: its declaration and its body. Its `self` is the -- protected object (named by its type, as Ada lets a protected body name its own), and one -- with `@entry` waits until its first statement's `when(c)` holds. protectedOperation :: Set Text -> FunctionDef -> D (D.Decl, D.Decl) protectedOperation components f = do let isEntry = any (\d -> d.node == NameRef "entry") f.decorators (barrier, rest) = case f.body of PyStmt {node = ExprStmt PyExpr {node = Call PyExpr {node = NameRef "when"} [Argument {value = c}]}} : more | isEntry -> (Just c, more) more -> (Nothing, more) withoutSelf = [p | p <- f.parameters, p.name /= "self"] when (isEntry && isNothing barrier) (reject f.nameSpan "an `@entry` starts with `when(condition)`, its barrier" "no barrier") modify' \st -> st {inProtected = Just (components, isEntry)} made <- functionDecl Public f {parameters = withoutSelf, decorators = [], body = selfless rest, typeParameters = []} modify' \st -> st {inProtected = Nothing} condition <- traverse (expr . selfless) barrier let sp = f.nameSpan pure case made.node of ItemDecl D.Decl {node = D.DSubprogramBody b} | Just c <- condition -> ( D.Decl {span = sp, node = D.DEntry D.EntryDecl {spec = b.spec, aspects = b.aspects}} , D.Decl {span = sp, node = D.DEntryBody D.EntryBody {spec = b.spec, barrier = c, aspects = [], declarations = b.declarations, statements = b.statements, handlers = b.handlers, endName = Nothing}} ) | otherwise -> ( D.Decl {span = sp, node = D.DSubprogram D.SubprogramDecl {spec = b.spec, form = D.PlainSpec, aspects = b.aspects}} , D.Decl {span = sp, node = D.DSubprogramBody D.SubprogramBody {spec = b.spec, aspects = [], declarations = b.declarations, statements = b.statements, handlers = b.handlers, endName = Nothing}} ) -- (a one-line function: a body that returns it) ItemDecl D.Decl {node = D.DSubprogram d} | D.ExpressionFunction v <- d.form -> ( D.Decl {span = sp, node = D.DSubprogram D.SubprogramDecl {spec = d.spec, form = D.PlainSpec, aspects = d.aspects}} , D.Decl {span = sp, node = D.DSubprogramBody D.SubprogramBody {spec = d.spec, aspects = [], declarations = [], statements = [S.Stmt {span = sp, node = S.SReturn (Just v)}], handlers = [], endName = Nothing}} ) _ -> (D.Decl {span = sp, node = D.DError}, D.Decl {span = sp, node = D.DError}) -- | `self.x` and `self.m(...)` in a protected operation: the component and the operation by -- name, as Ada's protected body names them. selfless :: (Data x) => x -> x selfless = rewrite where rewrite :: (Data y) => y -> y rewrite y = case cast y of Just PyExpr {node = Attribute PyExpr {node = NameRef "self"} n, span = sp} -> fromMaybe y (cast PyExpr {span = sp, node = NameRef n}) _ -> gmapT rewrite y -- | The classes of a module that are tagged: those derived from, deriving, or abstract. taggedClasses :: [PyStmt] -> Set Text taggedClasses defs = Set.fromList (concat [c.name : [b | PyExpr {node = NameRef b} <- c.bases, b /= "ABC"] | PyStmt {node = ClassStmt c} <- defs, derives c]) where classNames = Set.fromList [c.name | PyStmt {node = ClassStmt c} <- defs] derives c = any (\b -> case b.node of NameRef n -> n == "ABC" || Set.member n classNames; _ -> False) c.bases -- | The units Python's own forms need: @Ada.Text_IO@ and @Verada.Vibe@ for a module that -- prints, and the generics of the Python types it names. impliedContext :: Span -> D [U.ContextItem] impliedContext s = do printing <- gets (.usesPrint) generics <- gets (.generics) texts <- gets (.usesText) -- (an occurrence bound by `except E as e` is Ada.Exceptions', which a module need not import) occurrences <- gets (.bindsOccurrences) let textsUnit = dottedE s ["Verada", "Strings", "Texts"] pure ([U.ContextWith U.WithClause {span = s, limited = False, private = False, names} | (True, names) <- [(printing, [dottedE s ["Ada", "Text_IO"], dottedE s ["Verada", "Vibe"]]), (occurrences, [dottedE s ["Ada", "Exceptions"]])] <> [(True, [dottedE s g]) | g <- Set.toList generics]] -- (Python's `str` is a text, T30, its operations visible; a module that prints may -- print another module's texts) <> [U.ContextWith U.WithClause {span = s, limited = False, private = False, names = [textsUnit, dottedE s ["Verada", "Strings", "Text_Operations"]]} | texts || printing] <> [U.ContextUse D.UseClause {span = s, kind = D.UsePackage, names = [textsUnit]} | texts] <> [U.ContextUse D.UseClause {span = s, kind = D.UsePackage, names = [dottedE s bitwiseUnit]} | Set.member bitwiseUnit generics]) -- Only the three Integer operator overloads become use-visible in a module that uses them. bitwiseUnit :: [Text] bitwiseUnit = ["Verada", "Vibe", "Bitwise"] -- | Python's generic types: each is a type of an implicit instance of a Verada generic. pythonGeneric :: Text -> Int -> Maybe ([Text], Text) pythonGeneric n arity = case (n, arity) of ("list", 1) -> Just (["Verada", "Containers", "Unbounded", "Vectors"], "Vector") ("dict", 2) -> Just (["Verada", "Containers", "Unbounded", "Dictionaries"], "Dictionary") ("set", 1) -> Just (["Verada", "Containers", "Unbounded", "Ordered_Sets"], "Set") -- `Optional[T]`, `T | None`: a value that may be absent (Verada.Optionals' `Optional`) ("Optional", 1) -> Just (["Verada", "Optionals"], "Optional") ("tuple", k) | k `elem` [2 .. 12] -> Just (["Verada", "Vibe", "Tuple_" <> Text.pack (show k)], "Tuple") -- a model's sequence and an enclave's footprint (EU4, EU5): ghost values, for proof ("Seq", 1) -> Just (["Verada", "Containers", "Functional", "Sequences"], "Sequence") ("Cells", 1) -> Just (["Verada", "Footprints"], "Cells") _ -> Nothing isImportNode :: PyStmtNode -> Bool isImportNode = \case Import {} -> True FromImport {} -> True _ -> False -- | The names Vibe's own modules give: `verada`, `typing`, `dataclasses`, `enum`. isPreludeImport :: PyStmt -> Bool isPreludeImport s = case s.node of -- (`verada` itself; a unit below it, `verada.containers.hash_sets`, is Verada's library's) FromImport ["verada"] _ -> True Import ["verada"] _ -> True FromImport (m : _) _ -> m `elem` ["typing", "dataclasses", "enum", "abc", "__future__", "itertools"] Import (m : _) _ -> m `elem` ["typing", "dataclasses", "enum", "abc", "itertools"] _ -> False -- | @if __name__ == "__main__": main()@, which lets CPython run the program too. isMainGuard :: PyStmt -> Bool isMainGuard s = case s.node of If [(PyExpr {node = Compare PyExpr {node = NameRef "__name__"} [("==", PyExpr {node = StrLit "__main__"})]}, _)] [] -> True _ -> False -- | The names a module annotates only `Owned[T]`, never null. neverNullNames :: Module -> Set Text neverNullNames m = Map.keysSet (Map.filter and (Map.fromListWith (<>) (annotations m))) where annotations :: (Data a) => a -> [(Text, [Bool])] annotations x = here <> concat (gmapQ annotations x) where here = [(n, [ownedAlone a]) | Just PyStmt {node = AnnAssign PyExpr {node = NameRef n} a _} <- [cast x]] <> [(p.name, [ownedAlone a]) | Just (p :: Parameter) <- [cast x], Just a <- [p.annotation]] -- | A `Ref[T]` annotation, or `Ref[T] | None`. isRefType :: PyExpr -> Bool isRefType a = case a.node of Subscript PyExpr {node = NameRef "Ref"} _ -> True BinOp "|" l PyExpr {node = NoneLit} -> isRefType l _ -> False -- | `enclave()`: the module is a proof enclave (e4-user-enclaves.md EU1). isEnclaveMark :: PyStmt -> Bool isEnclaveMark s = case s.node of ExprStmt PyExpr {node = Call PyExpr {node = NameRef "enclave"} []} -> True _ -> False isDocstring :: PyStmt -> Bool isDocstring s = case s.node of ExprStmt PyExpr {node = StrLit _} -> True _ -> False importContext :: PyStmt -> D [U.ContextItem] importContext s = case s.node of Import path Nothing -> pure [withOf path] -- (its `as` name stands for the module's full name: Verada.Vibe.Names) Import path (Just _) -> pure [withOf path] FromImport path _ -> pure [withOf path, U.ContextUse D.UseClause {span = s.span, kind = D.UsePackage, names = [dottedE s.span path]}] _ -> pure [] where withOf path = U.ContextWith U.WithClause {span = s.span, limited = False, private = False, names = [dottedE s.span path]} -- | An expression with `self` as a type's name (its current instance, in an aspect); a -- method of `self` called with it first, `self.size()` as `size(Stack)`. selfAs :: Text -> PyExpr -> PyExpr selfAs c = go where go :: (Data a) => a -> a go x = case cast x of Just PyExpr {span = sp, node = NameRef "self"} -> fromMaybe x (cast PyExpr {span = sp, node = NameRef c}) Just PyExpr {span = sp, node = Call PyExpr {node = Attribute self@PyExpr {node = NameRef "self"} m, span = at} args} -> fromMaybe x (cast PyExpr {span = sp, node = Call PyExpr {span = at, node = NameRef m} (Argument {keyword = Nothing, value = go self} : go args)}) _ -> gmapT go x visibilityOf :: Text -> Visibility visibilityOf n = if "_" `Text.isPrefixOf` n then Hidden else Public -- | A class's: a `_` class in the private part, where a public class's private fields (its -- full view, there too) may name it, as an enclave's do (e4-user-enclaves.md EU7). classVisibility :: Text -> Visibility classVisibility n = if "_" `Text.isPrefixOf` n then ChildVisible else Public -- * Module items -- | `@task def worker()`. isTask :: FunctionDef -> Bool isTask f = any (\d -> d.node == NameRef "task") f.decorators -- | A task's declaration and body (Jorvik's: it runs from the start, and never ends). In a -- function, a task made at run time, which Sema reports as not in Verada. taskItems :: FunctionDef -> D [Item] taskItems f = do body <- functionDecl Hidden f {decorators = [], parameters = f.parameters} pure case body.node of ItemDecl D.Decl {node = D.DSubprogramBody b} -> [ Item {span = f.nameSpan, visibility = visibilityOf f.name, node = ItemDecl D.Decl {span = f.nameSpan, node = D.DTask D.TaskDecl {name = ident f.nameSpan f.name, isType = False, discriminants = Nothing, aspects = []}}} , Item {span = f.nameSpan, visibility = Hidden, node = ItemDecl D.Decl {span = f.nameSpan, node = D.DTaskBody D.TaskBody {name = ident f.nameSpan f.name, aspects = [], declarations = b.declarations, statements = b.statements, handlers = b.handlers, endName = Nothing}}} ] _ -> [body] moduleItem :: PyStmt -> D [Item] moduleItem s = case s.node of -- `@task def producer()`: a task (Jorvik's: it runs from the start, and never ends) FunctionStmt f | isTask f -> taskItems f -- `buffer = Buffer()` of a class of `Protected`: a protected object Assign [PyExpr {node = NameRef n, span = ns}] PyExpr {node = Call PyExpr {node = NameRef c} []} -> do protected <- gets (Set.member c . (.protectedClasses)) if protected then do modify' \st -> st {protectedObjects = Set.insert n st.protectedObjects} pure [Item {span = s.span, visibility = visibilityOf n, node = ItemDecl D.Decl {span = s.span, node = D.DObject D.ObjectDecl {names = [ident ns n], aliased = False, constant = False, subtype = indication s.span (nameE s.span c), initial = Nothing, aspects = []}}}] else plainModuleItem s _ -> plainModuleItem s plainModuleItem :: PyStmt -> D [Item] plainModuleItem s = case s.node of FunctionStmt f -> pure <$> functionDecl (visibilityOf f.name) f -- `class Box[T]`: a generic package of the class and its methods, then the instances the -- module's uses need ClassStmt c | not (null c.typeParameters) -> do inner <- classItem s.span ClassDef {name = c.name, nameSpan = c.nameSpan, typeParameters = [], decorators = c.decorators, bases = c.bases, keywords = c.keywords, body = c.body} instances <- gets (Map.findWithDefault [] c.name . (.genericClasses)) let sp = c.nameSpan formals = [D.FormalTypeNode D.TypeDecl {name = ident tsp t, discriminants = Nothing, definition = T.Private T.PrivateDefinition {abstract = False, tagged = False, limited = False}, aspects = []} | (t, tsp, _) <- c.typeParameters] generic = Item {span = s.span, visibility = classVisibility c.name, node = ItemGenericPackage GenericPackage {formals, package = VarcPackage {span = s.span, name = nameE sp ("Generic_" <> c.name), aspects = [], items = [Item {span = i.span, visibility = Public, node = i.node} | i <- inner]}}} past = s.span {start = s.span.end} instanceItems = [Item {span = past, visibility = classVisibility c.name, node = ItemDecl D.Decl {span = past, node = D.DInstantiation D.Instantiation {kind = D.InstantiatePackage, overriding = Nothing, name = nameE past name, generic = nameE past ("Generic_" <> c.name), actuals = [E.Argument {span = past, formal = Nothing, value = E.ArgExpr (actualE past a), reference = Nothing} | a <- actuals], aspects = []}}} | (actuals, name) <- instances] pure (generic : instanceItems) ClassStmt c -> do -- a union's root type comes before its first dataclass union <- gets (Map.lookup c.name . (.unions)) root <- maybe (pure []) (unionRoot s.span) union -- a class `Owned[X]` names: X declared first as incomplete, then its access type, and -- after it, its `Free` (`del`) isOwned <- gets (Set.member c.name . (.owned)) let at = s.span {end = s.span.start} typeItem n definition = Item {span = at, visibility = classVisibility c.name, node = ItemDecl D.Decl {span = at, node = D.DType D.TypeDecl {name = ident at n, discriminants = Nothing, definition, aspects = []}}} before = [typeItem c.name T.Incomplete, typeItem ("Owned_" <> c.name) (T.AccessType (T.AccessToObject T.AccessObject {notNull = False, accessKind = T.PoolSpecific, designated = E.SubtypeIndication {span = at, notNull = False, mark = nameE at c.name, constraint = Nothing}}))] after = [Item {span = at, visibility = Hidden, node = ItemDecl D.Decl {span = at, node = D.DInstantiation D.Instantiation {kind = D.InstantiateProcedure, overriding = Nothing, name = nameE at "Free", generic = dottedE at ["Ada", "Unchecked_Deallocation"], actuals = [E.Argument {span = at, formal = Nothing, value = E.ArgExpr (nameE at n), reference = Nothing} | n <- [c.name, "Owned_" <> c.name]], aspects = []}}}] when isOwned (modify' \st -> st {generics = Set.insert ["Ada", "Unchecked_Deallocation"] st.generics}) -- (a field named as its type, `items: Items`: one name to Ada) forM_ [(x, n, t) | x@PyStmt {node = AnnAssign PyExpr {node = NameRef n} PyExpr {node = NameRef t} _} <- c.body, n /= t, Text.toCaseFold n == Text.toCaseFold t] \(x, n, t) -> reject x.span ("the field `" <> n <> "` and its type `" <> t <> "` differ only in case, which Ada (and so Verada) does not tell apart: rename the field") "same name as its type" items <- classItem s.span c -- the instances (`list[P]`) whose last class this is locals <- gets (Map.findWithDefault [] c.name . (.localInstances)) forM_ locals \(generic, _, _) -> modify' \st -> st {generics = Set.insert generic st.generics} -- (at an empty place at the class's end: comments before the class are the class's) let past = s.span {start = s.span.end} instances = [Item {span = past, visibility = classVisibility c.name, node = ItemDecl D.Decl {span = past, node = D.DInstantiation D.Instantiation {kind = D.InstantiatePackage, overriding = Nothing, name = nameE past name, generic = dottedE past generic, actuals = [E.Argument {span = past, formal = Nothing, value = E.ArgExpr (actualE past a), reference = Nothing} | a <- actuals], aspects = []}}} | (generic, name, actuals) <- locals] pure (root <> (if isOwned then before <> items <> after else items) <> instances) TypeAlias n _ | BinOp "|" _ _ <- (aliasValue s).node -> do isUnion <- gets (elem n . Map.elems . (.unions)) if isUnion then unionRoot s.span n else [] <$ reject s.span "a union of types is taken when each is a dataclass of the module" "union" TypeAlias n v -> do item <- subtypeAlias s.span n v -- (the instances, `list[T]`, whose last type this is, after it) locals <- gets (Map.findWithDefault [] n . (.localInstances)) forM_ locals \(generic, _, _) -> modify' \st -> st {generics = Set.insert generic st.generics} let past = s.span {start = s.span.end} instances = [Item {span = past, visibility = visibilityOf n, node = ItemDecl D.Decl {span = past, node = D.DInstantiation D.Instantiation {kind = D.InstantiatePackage, overriding = Nothing, name = nameE past name, generic = dottedE past generic, actuals = [E.Argument {span = past, formal = Nothing, value = E.ArgExpr (actualE past a), reference = Nothing} | a <- actuals], aspects = []}}} | (generic, name, actuals) <- locals] pure (item : instances) AnnAssign PyExpr {node = NameRef n, span = ns} annotation (Just v) -> constantItem s.span ns n annotation v -- `started: Suspension_Object`: a module variable of a type that gives its objects their -- value (initialised by default, as a local so annotated is) AnnAssign PyExpr {node = NameRef n, span = ns} annotation Nothing -> do ty <- typeExpr annotation pure [Item {span = s.span, visibility = visibilityOf n, node = ItemDecl D.Decl {span = s.span, node = D.DObject D.ObjectDecl {names = [ident ns n], aliased = False, constant = False, subtype = annotated annotation ty, initial = Nothing, aspects = []}}}] Assign [PyExpr {node = NameRef n, span = ns}] v -> do -- a module-level variable value <- expr v pure [Item {span = s.span, visibility = visibilityOf n, node = ItemDecl D.Decl {span = s.span, node = D.DObject D.ObjectDecl {names = [ident ns n], aliased = False, constant = False, subtype = T.InferredType, initial = Just value, aspects = []}}}] _ -> do -- module statements run when the module is first imported: the package body's ss <- statements Set.empty [s] pure [Item {span = s.span, visibility = Hidden, node = ItemInit ss}] aliasValue :: PyStmt -> PyExpr aliasValue s = case s.node of TypeAlias _ v -> v _ -> PyExpr {span = s.span, node = NoneLit} -- | A union's root: an abstract tagged type with no components, declared once. unionRoot :: Span -> Text -> D [Item] unionRoot sp u = do done <- gets (Set.member u . (.unionsDeclared)) if done then pure [] else do modify' \st -> st {unionsDeclared = Set.insert u st.unionsDeclared, classes = Map.insert u TaggedClass st.classes} -- (at an empty place at the end of the class it comes before: comments go with that) let s = sp {start = sp.end} pure [Item {span = s, visibility = visibilityOf u, node = ItemStruct StructDecl {declaration = D.TypeDecl {name = ident s u, discriminants = Nothing, definition = T.RecordType T.RecordDefinition {abstract = True, tagged = True, limited = False, components = Nothing}, aspects = []}, fields = NoFields}}] -- | @NAME: Final = V@ (or @Final[T]@, or a type): a constant; with no type and a static -- number, a named number. constantItem :: Span -> Span -> Text -> PyExpr -> PyExpr -> D [Item] constantItem s ns n annotation v = do classes <- gets (.classes) let final = case annotation.node of NameRef "Final" -> Just Nothing Subscript PyExpr {node = NameRef "Final"} [t] -> Just (Just t) _ -> Nothing -- `T([...])` of an array class, or `T(f=...)` of a record class: an aggregate of T constructed = case v.node of Call PyExpr {node = NameRef c} _ | Map.member c classes -> Just c _ -> Nothing value <- if isNothing final && emptyContainer v then pure (nameE v.span "") else expr v case (final, constructed) of (Just Nothing, Nothing) | isNumber v -> pure [item (D.DNumber D.NumberDecl {names = [ident ns n], value})] (Just Nothing, Just c) -> pure [item (object True (typeOf v.span c) value)] (Just Nothing, Nothing) -> pure [item (object True T.InferredType value)] (Just (Just t), _) -> do ty <- typeExpr t pure [item (object True (annotated t ty) value)] -- (an empty container: the type's own default, empty) (Nothing, _) | emptyContainer v -> do ty <- typeExpr annotation pure [item (D.DObject D.ObjectDecl {names = [ident ns n], aliased = False, constant = False, subtype = annotated annotation ty, initial = Nothing, aspects = []})] (Nothing, _) -> do ty <- typeExpr annotation pure [item (object False (annotated annotation ty) value)] where item node = Item {span = s, visibility = visibilityOf n, node = ItemDecl D.Decl {span = s, node}} object constant subtype value = D.DObject D.ObjectDecl {names = [ident ns n], aliased = False, constant, subtype, initial = Just value, aspects = []} typeOf sp c = indication sp (nameE sp c) isNumber e = case e.node of IntLit _ -> True FloatLit _ _ -> True UnaryOp "-" x -> isNumber x _ -> False indication :: Span -> E.Expr -> T.ObjectType indication s mark = T.Indication E.SubtypeIndication {span = s, notNull = False, mark, constraint = Nothing} -- | The subtype an annotation gives, the type its mark names: `Owned[X]` alone is never -- null (`not null Owned_X`), `Owned[X] | None` may be. annotated :: PyExpr -> E.Expr -> T.ObjectType annotated a mark = T.Indication E.SubtypeIndication {span = a.span, notNull = ownedAlone a, mark, constraint = Nothing} ownedAlone :: PyExpr -> Bool ownedAlone a = case a.node of Subscript PyExpr {node = NameRef "Owned"} [_] -> True _ -> False -- | @type X = Annotated[T, Interval(ge=A, le=B)]@ (or @Ge(A)@, @Le(B)@), or an alias. subtypeAlias :: Span -> Text -> PyExpr -> D Item subtypeAlias s n v = do (base, constraint) <- case v.node of Subscript PyExpr {node = NameRef "Annotated"} (t : constraints) -> do b <- typeExpr t bounds <- concat <$> mapM rangeOf constraints let lo = [x | ("ge", x) <- bounds] hi = [x | ("le", x) <- bounds] c <- case (lo, hi) of ([l], [h]) -> pure (Just (E.RangeConstraint (E.Bounds E.RangeExpr {span = v.span, low = l, high = h}))) ([l], []) -> pure (Just (E.RangeConstraint (E.Bounds E.RangeExpr {span = v.span, low = l, high = attribute v.span b "Last"}))) ([], [h]) -> pure (Just (E.RangeConstraint (E.Bounds E.RangeExpr {span = v.span, low = attribute v.span b "First", high = h}))) _ -> Nothing <$ reject v.span "Vibe does not take this `Annotated` constraint: give `Interval(ge=..., le=...)`" "constraint" pure (b, c) _ -> (,Nothing) <$> typeExpr v pure Item {span = s, visibility = visibilityOf n, node = ItemDecl D.Decl {span = s, node = D.DSubtype D.SubtypeDecl {name = ident s n, indication = E.SubtypeIndication {span = v.span, notNull = False, mark = base, constraint}, aspects = []}}} where rangeOf c = case c.node of Call PyExpr {node = NameRef "Interval"} args -> fmap catMaybes . forM args $ \a -> case a.keyword of Just k | k `elem` ["ge", "le"] -> Just . (k,) <$> expr a.value _ -> Nothing <$ reject a.value.span "`Interval` takes `ge=` and `le=`" "argument" Call PyExpr {node = NameRef "Ge"} [a] -> pure . ("ge",) <$> expr a.value Call PyExpr {node = NameRef "Le"} [a] -> pure . ("le",) <$> expr a.value _ -> [] <$ reject c.span "Vibe does not take this `Annotated` constraint: give `Interval(ge=..., le=...)`, `Ge(...)` or `Le(...)`" "constraint" -- | A library unit the module's code names (its `with`). needs :: [Text] -> D () needs unit = modify' \st -> st {generics = Set.insert unit st.generics} attribute :: Span -> E.Expr -> Text -> E.Expr attribute s p a = E.Expr {span = s, node = E.EAttribute E.AttributeRef {prefix = p, designator = ident s a, arguments = []}} -- | A type written as an annotation: a name (Python's own types are Verada's), or a dotted -- name. typeExpr :: PyExpr -> D E.Expr typeExpr t = case t.node of -- a forward annotation, `"V"`: the class it names StrLit n | not (Text.null n), Text.all (\ch -> ch == '_' || ch == '.' || isAlphaNum ch) n -> typeExpr PyExpr {span = t.span, node = NameRef n} -- (Python's `str` is a text, by its full name, so that an instance of it needs only its -- package, T30) NameRef "str" -> do modify' \st -> st {usesText = True} pure (dottedE t.span ["Verada", "Strings", "Texts", "Text"]) NameRef n -> pure (nameE t.span (builtinType n)) -- `Owned[X] | None`: X's access type; `Owned[X]` alone, never null (its subtype) BinOp "|" PyExpr {node = Subscript PyExpr {node = NameRef "Owned"} [PyExpr {node = NameRef n}]} PyExpr {node = NoneLit} -> pure (nameE t.span ("Owned_" <> n)) Subscript PyExpr {node = NameRef "Owned"} [PyExpr {node = NameRef n}] -> pure (nameE t.span ("Owned_" <> n)) -- `Ghost[T]`: a field for proof (EU3); the models and footprints it holds take no storage Subscript PyExpr {node = NameRef "Ghost"} [x] -> typeExpr x -- an enclave's reference, which may be shared (EU2): the same access type, its cells the -- enclave's BinOp "|" PyExpr {node = Subscript PyExpr {node = NameRef "Ref"} [PyExpr {node = NameRef n}]} PyExpr {node = NoneLit} -> refOf n Subscript PyExpr {node = NameRef "Ref"} [PyExpr {node = NameRef n}] -> refOf n -- `T | None` (of a value, not an owner or a reference): `Optional[T]` BinOp "|" x PyExpr {node = NoneLit} -> typeExpr PyExpr {span = t.span, node = Subscript PyExpr {span = t.span, node = NameRef "Optional"} [x]} -- `Box[int]` of a generic class: the class of its instance (the module's own, or an -- implicit instance of another module's) Subscript PyExpr {node = NameRef n} elements | Nothing <- pythonGeneric n (length elements) -> do generics <- gets (.genericClasses) imported <- gets (.importedFrom) stars <- gets (.starImports) let actualNames = [builtinType a | PyExpr {node = NameRef a} <- elements] let shared generic = do modify' \st -> st {usesText = st.usesText || "Text" `elem` actualNames} pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix = E.Expr {span = t.span, node = E.EInstance E.InstanceRef {generic, actuals = [E.Argument {span = t.span, formal = Nothing, value = E.ArgExpr (actualE t.span a), reference = Nothing} | a <- actualNames]}}, selector = E.SelectIdentifier (ident t.span n)}} case (Map.lookup n generics, Map.lookup n imported) of -- (of Python's own types: the library-level instance every module shares) (Just _, _) | builtinActuals elements -> shared (nameE t.span ("Generic_" <> n)) -- (a class of the one module imported with `*`, as a translation writes its imports) (Nothing, Nothing) | builtinActuals elements, [m] <- stars -> do let unit = Text.intercalate "_" m <> "_Generic_" <> n modify' \st -> st {generics = Set.insert [unit] st.generics} shared (nameE t.span unit) (Nothing, Just m) | builtinActuals elements -> do let unit = Text.intercalate "_" m <> "_Generic_" <> n modify' \st -> st {generics = Set.insert [unit] st.generics} shared (nameE t.span unit) (Just instances, _) | Just name <- lookup actualNames instances -> pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix = nameE t.span name, selector = E.SelectIdentifier (ident t.span n)}} -- (another module's: the instance that module declares for its own uses, so that values -- pass between them; one it does not declare is not found) (_, Just m) -> pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix = dottedE t.span (m <> [Text.intercalate "_" (n : actualNames)]), selector = E.SelectIdentifier (ident t.span n)}} _ -> nameE t.span "Integer" <$ reject t.span "Vibe does not take this type: write `int`, `float`, `bool`, `str`, a class, `list[T]`, `dict[K, V]`, `set[T]`, `tuple[A, B]`, `Owned[T]`, or an instance of a generic class the module declares or imports (`Box[int]`)" "type" -- `m.Box[int]`: the class of the instance module `m` declares Subscript PyExpr {node = Attribute PyExpr {node = NameRef m} n} elements -> do modules <- gets (.modules) let actualNames = [builtinType a | PyExpr {node = NameRef a} <- elements] if Set.member m modules then if builtinActuals elements -- (of Python's own types: the library-level instance every module shares) then do modify' \st -> st {generics = Set.insert [m <> "_Generic_" <> n] st.generics, usesText = st.usesText || "Text" `elem` actualNames} pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix = E.Expr {span = t.span, node = E.EInstance E.InstanceRef {generic = nameE t.span (m <> "_Generic_" <> n), actuals = [E.Argument {span = t.span, formal = Nothing, value = E.ArgExpr (actualE t.span a), reference = Nothing} | a <- actualNames]}}, selector = E.SelectIdentifier (ident t.span n)}} else pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix = dottedE t.span [m, Text.intercalate "_" (n : actualNames)], selector = E.SelectIdentifier (ident t.span n)}} else nameE t.span "Integer" <$ reject t.span "Vibe does not take this type: write `int`, `float`, `bool`, `str`, a class, `list[T]`, `dict[K, V]`, `set[T]`, `tuple[A, B]`, `Owned[T]`, or an instance of a generic class the module declares or imports (`Box[int]`)" "type" -- `list[list[T]]`: a list of lists, Verada.Containers.Unbounded.Nested_Vectors' instance -- whose rows are the instance `list[T]` is, so that a row and a `list[T]` are of one type -- (D188) Subscript PyExpr {node = NameRef "list"} [inner@PyExpr {node = Subscript PyExpr {node = NameRef "list"} [_]}] -> do rowType <- typeExpr inner case rowType.node of E.ESelected E.Selected {prefix = rows} -> do let generic = ["Verada", "Containers", "Unbounded", "Nested_Vectors"] modify' \st -> st {generics = Set.insert generic st.generics} pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix = E.Expr {span = t.span, node = E.EInstance E.InstanceRef {generic = dottedE t.span generic, actuals = [E.Argument {span = t.span, formal = Nothing, value = E.ArgExpr rows, reference = Nothing}]}}, selector = E.SelectIdentifier (ident t.span "Vector")}} _ -> nameE t.span "Integer" <$ reject t.span "a list of lists takes a list type of its own as its rows'" "rows" -- `list[str]`: the library's list of texts, which its str operations (`s.split()`) give Subscript PyExpr {node = NameRef "list"} [PyExpr {node = NameRef "str"}] -> do modify' \st -> st {usesText = True} needs ["Verada", "Strings", "Text_Lists"] pure (dottedE t.span ["Verada", "Strings", "Text_Lists", "Vector"]) -- `list[T]`, `dict[K, V]`, `set[T]`, `tuple[A, B]`: the type of an implicit instance -- `list[T]` of a generic function's type parameter T: the container type of a formal -- package of the function, `Verada_Vectors_T.Vector`, whose actual is the package of the -- caller's list (D188) Subscript PyExpr {node = NameRef n} elements | Just (generic, typeName) <- pythonGeneric n (length elements) , n `elem` ["list", "set", "dict"] -> do formals <- gets (.genericFormals) let names = [a | PyExpr {node = NameRef a} <- elements] if length names == length elements && any (`Set.member` formals) names then do let package = "Verada_" <> fromMaybe "" (listToMaybe (reverse generic)) <> "_" <> Text.intercalate "_" names modify' \st -> st {formalPackages = nub (st.formalPackages <> [(package, generic, map builtinType names)]), generics = Set.insert generic st.generics} pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix = nameE t.span package, selector = E.SelectIdentifier (ident t.span typeName)}} else containerType' generic typeName elements Subscript PyExpr {node = NameRef n} elements | Just (generic, typeName) <- pythonGeneric n (length elements) -> containerType' generic typeName elements Attribute p n -> do prefix <- typeExpr p pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix, selector = E.SelectIdentifier (ident t.span n)}} _ -> nameE t.span "Integer" <$ reject t.span "Vibe does not take this type: write `int`, `float`, `bool`, `str`, a class, `list[T]`, `dict[K, V]`, `set[T]`, `tuple[A, B]`, `Owned[T]`, or an instance of a generic class the module declares or imports (`Box[int]`)" "type" where -- (an enclave's reference, EU2: in a module that is not an enclave, `Owned[T]` is the -- reference there is) refOf n = do inEnclave <- gets (.enclaveModule) unless inEnclave (reject t.span "a `Ref` may be shared, which only a proof enclave's code may do: write `enclave()` first in the module, or use `Owned[T]`, which is not shared" "not in an enclave") pure (nameE t.span ("Owned_" <> n)) containerType' generic typeName elements = do locals <- gets (concat . Map.elems . (.localInstances)) let actualNames = [builtinType a | Just a <- map referenceOrName elements] referenceOrName e = case e.node of NameRef a -> Just a Subscript PyExpr {node = NameRef r} [PyExpr {node = NameRef c}] | r `elem` ["Ref", "Owned"] -> Just ("Owned_" <> c) _ -> Nothing earlier <- gets (.sessionPackages) -- (an earlier REPL input's instance for its own class, its dataclass's list: the type -- values of it have) let ofSession = [name | let name = Text.intercalate "_" (fromMaybe "" (listToMaybe (reverse generic)) : actualNames), length actualNames == length elements, Set.member name earlier] case [name | (g, name, as) <- locals, g == generic, as == actualNames, length actualNames == length elements] <> ofSession of name : _ -> do modify' \st -> st {generics = Set.insert generic st.generics} pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix = nameE t.span name, selector = E.SelectIdentifier (ident t.span typeName)}} [] -> do imported <- gets (.importedFrom) modules <- gets (.modules) case (generic, elements) of -- `list[P]` of a dataclass another module declares: that module's list of it -- (or named through it: `list[shapes.Point]`) (["Verada", "Containers", "Unbounded", "Vectors"], [PyExpr {node = Attribute PyExpr {node = NameRef m} a}]) | Set.member m modules -> do modify' \st -> st {generics = Set.insert generic st.generics} pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix = dottedE t.span [m, "Vectors_" <> a], selector = E.SelectIdentifier (ident t.span typeName)}} (["Verada", "Containers", "Unbounded", "Vectors"], [PyExpr {node = NameRef a}]) | Just m <- Map.lookup a imported -> do modify' \st -> st {generics = Set.insert generic st.generics} pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix = dottedE t.span (m <> ["Vectors_" <> a]), selector = E.SelectIdentifier (ident t.span typeName)}} -- `dict[int, P]` (or `set[P]`) of a class another module declares, imported by name: -- the instance that module declares for its own use of the same type, so that values -- pass between them (one it does not use is not found) (_, _) | named <- [x | Just x <- map (elementOf imported modules) elements] , length named == length elements , names <- map fst named , (m : _) <- [m' | (_, Just m') <- named] , all (\(_, o) -> o `elem` [Nothing, Just m]) named -> do modify' \st -> st {generics = Set.insert generic st.generics} let instanceName = Text.intercalate "_" (maybe "" id (listToMaybe (reverse generic)) : map builtinType names) pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix = dottedE t.span (m <> [instanceName]), selector = E.SelectIdentifier (ident t.span typeName)}} _ -> implicitType generic typeName elements implicitType generic typeName elements = do es <- mapM typeExpr elements modify' \st -> st {generics = Set.insert generic st.generics} let instance' = E.Expr {span = t.span, node = E.EInstance E.InstanceRef {generic = dottedE t.span generic, actuals = [E.Argument {span = x.span, formal = Nothing, value = E.ArgExpr x, reference = Nothing} | x <- es]}} pure E.Expr {span = t.span, node = E.ESelected E.Selected {prefix = instance', selector = E.SelectIdentifier (ident t.span typeName)}} -- | A generic's actual by Verada's name for it (`Text`, Python's `str`, by its full name). actualE :: Span -> Text -> E.Expr actualE s = \case "Text" -> dottedE s ["Verada", "Strings", "Texts", "Text"] a -> nameE s a builtinType :: Text -> Text builtinType = \case "int" -> "Integer" "float" -> "Long_Float" "bool" -> "Boolean" "str" -> "Text" n -> n -- * Classes classItem :: Span -> ClassDef -> D [Item] classItem s c = do forM_ [d | d <- c.decorators, not (isDataclass d)] \d -> reject d.span "this decorator is not one Vibe takes: a class's is `@dataclass`" "decorator" -- (an option Vibe does not keep would be ignored, and a reader could take it to mean -- something: `limited=True` is the one Vibe takes) forM_ [a | PyExpr {node = Call PyExpr {node = NameRef "dataclass"} as} <- c.decorators, a <- as] \a -> case (a.keyword, a.value.node) of (Just "limited", BoolLit _) -> pure () (Just k, _) -> reject a.value.span ("`" <> k <> "=` is not a dataclass option Vibe takes: a Vibe dataclass is a record, built from its fields by name and compared field by field, and `limited=True` (its values are not copied) is its one option" <> optionAdvice k) "option" (Nothing, _) -> reject a.value.span "`@dataclass` takes its options by name, and Vibe's one option is `limited=True`" "option" protocolSet <- gets (.protocols) kinds <- gets (.classes) -- (`@dataclass(limited=True)`: a dataclass whose values are not copied, EU7) let decorators = [n | PyExpr {node = NameRef n} <- c.decorators] <> [n | PyExpr {node = Call PyExpr {node = NameRef n} _} <- c.decorators] limitedClass = not (null [() | PyExpr {node = Call PyExpr {node = NameRef "dataclass"} as} <- c.decorators, Argument {keyword = Just "limited", value = PyExpr {node = BoolLit True}} <- as]) vis = classVisibility c.name item node = Item {span = s, visibility = vis, node} typeDecl definition = D.TypeDecl {name = ident c.nameSpan c.name, discriminants = Nothing, definition, aspects = []} keyword k = lookup k c.keywords case (decorators, c.bases) of -- a dataclass (or an abstract class) and its methods: a record type, tagged when it is -- in a hierarchy, and its primitive subprograms (ds, bases) | ds == ["dataclass"] || abstractBase bases , Just parent <- parentOf protocolSet bases -> do let protocols = protocolSet inHierarchy <- gets (Set.member c.name . (.tagged)) let tagged = inHierarchy -- (the protocols it names: interfaces it implements) interfaces = [PyExpr {span = b.span, node = NameRef n} | b@PyExpr {node = NameRef n} <- bases, Set.member n protocols] union <- gets (Map.lookup c.name . (.unions)) -- (a dataclass's fields in order: its parent's, then its own, as Python's are) modify' \st -> st {fieldNames = Map.insert c.name (maybe [] (\p -> Map.findWithDefault [] p.name st.fieldNames) parent <> [n | PyStmt {node = AnnAssign PyExpr {node = NameRef n} _ _} <- c.body]) st.fieldNames} modify' \st -> st {classes = Map.insert c.name (if inHierarchy then TaggedClass else RecordClass) st.classes} fields <- forM [(x, n, a, d) | x@PyStmt {node = AnnAssign PyExpr {node = NameRef n} a d} <- c.body] \(x, n, a, d) -> do ty <- typeExpr a initial <- traverse expr d pure T.ComponentDecl {span = x.span, names = [ident x.span n], definition = T.ComponentDefinition {aliased = False, subtype = annotated a ty}, initial, aspects = []} -- (`__invariant__` is the type's invariant, EU6, and `__del__` its finalizer, EU8: -- functions of their own names) let special n = case n of "__invariant__" -> "Verada_Invariant" "__initial__" -> "Verada_Initial" "__del__" -> "Verada_Finalize" -- (and a context manager's, D176) "__enter__" -> "Verada_Enter" "__exit__" -> "Verada_Exit" -- (Python's special methods: the operations Verada's forms call, D188) _ | Just o <- lookup n specialMethods -> o _ -> n -- (the special ones last: they may use the others) methods = [FunctionDef {name = special f.name, nameSpan = f.nameSpan, decorators = f.decorators, typeParameters = f.typeParameters, parameters = f.parameters, returns = f.returns, body = f.body} | PyStmt {node = FunctionStmt f} <- sortOn (\x -> case x.node of { FunctionStmt g -> "__" `Text.isPrefixOf` g.name; _ -> False }) c.body] has n = n `elem` [f.name | PyStmt {node = FunctionStmt f} <- c.body] aspectOf n v = E.AspectSpec {span = c.nameSpan, mark = ident c.nameSpan n, classWide = False, value = Just v} classAspects = [aspectOf "Type_Invariant" (call c.nameSpan ["Verada_Invariant"] [nameE c.nameSpan c.name]) | has "__invariant__"] <> [aspectOf "Finalizable" E.Expr {span = c.nameSpan, node = E.EAggregate E.Aggregate {bracket = False, contents = E.PlainAggregate (E.Associations [named "Finalize" (nameE c.nameSpan "Verada_Finalize"), named "Relaxed_Finalization" (nameE c.nameSpan "True")])}} | has "__del__"] named k v = E.NamedAssocNode E.NamedAssoc {span = c.nameSpan, choices = [E.ChoiceExpr (nameE c.nameSpan k)], value = E.AssocExpr v} others = [x | x <- c.body, not (isField x), not (isPassOrDoc x), not (isMethod x)] abstract = abstractBase bases unless (null others) (reject s "a class body holds fields, methods and a docstring" "not a field or method") -- (Python's repr of a dataclass, `Point(x=1, y=2)`, unless it has its own: made where -- every field has a repr Vibe shows, D188) allFields <- gets (Map.findWithDefault [] c.name . (.fieldNames)) shown <- reprShown c.name fieldTypesHere <- gets (.moduleTypes.fieldTypes) enumsHere <- gets (.enums) let generatedRepr = [ FunctionDef { name = "Verada_Made_Repr" , nameSpan = c.nameSpan , decorators = [] , typeParameters = [] , parameters = [Parameter {span = c.nameSpan, name = "self", annotation = Nothing, defaultValue = Nothing}] , returns = Just PyExpr {span = c.nameSpan, node = NameRef "str"} , body = [PyStmt {span = c.nameSpan, node = Return (Just PyExpr {span = c.nameSpan, node = FString (reprParts allFields)})}] } | not (has "__repr__" || has "Verada_Repr" || has "Verada_Made_Repr") -- (an abstract class's objects are its subclasses', which have their own) , not abstract , null [() | PyStmt {node = FunctionStmt g} <- c.body, any (\d -> d.node == NameRef "abstractmethod") g.decorators] , not limitedClass , null c.typeParameters , shown ] -- (each piece at a place of its own, which no source has, as forms are told -- apart by their places: an empty span that ends before it starts) madeAt k = Span {file = c.nameSpan.file, start = c.nameSpan.start, end = c.nameSpan.start - 1 - k} fieldOf k fname = PyExpr {span = madeAt (6 * k + 1), node = Attribute PyExpr {span = madeAt (6 * k + 2), node = NameRef "self"} fname} -- (a field's repr; an `Enum` member's is ``, its name and its -- value's repr) shownField k fname = case Map.lookup fname =<< Map.lookup c.name fieldTypesHere of Just (PNamed e) | Map.member e enumsHere -> [ Left ("<" <> e <> ".") , Right PyExpr {span = madeAt (6 * k + 3), node = Attribute (fieldOf k fname) "name"} , Left ": " , Right PyExpr {span = madeAt (6 * k + 4), node = FormatField PyExpr {span = madeAt (6 * k + 5), node = Attribute (fieldOf k fname) "value"} (Just 'r') Nothing} , Left ">" ] _ -> [Right PyExpr {span = madeAt (6 * k), node = FormatField (fieldOf k fname) (Just 'r') Nothing}] reprParts fs = joinedTexts case fs of [] -> [Left (c.name <> "()")] _ -> Left (c.name <> "(") : concat [Left ((if k == 0 then "" else ", ") <> fname <> "=") : shownField k fname | (k, fname) <- zip [0 :: Int ..] fs] <> [Left ")"] -- (text pieces next to each other as one, as a translation writes them) joinedTexts = \case Left a : Left b : rest -> joinedTexts (Left (a <> b) : rest) x : rest -> x : joinedTexts rest [] -> [] let names = [n | PyStmt {node = AnnAssign PyExpr {node = NameRef n} _ _} <- c.body] visibility | null names = NoFields | all ("_" `Text.isPrefixOf`) names = NoFieldsPublic | otherwise = AllFieldsPublic componentList = T.ComponentList {components = fields, variant = Nothing, nullComponents = null fields} interfaceNames = [nameE b.span n | b@PyExpr {node = NameRef n} <- interfaces] definition = case (maybe (parent >>= notProtocol) (\u -> Just Named {span = c.nameSpan, name = u}) union, interfaceNames) of (Nothing, []) -> T.RecordType T.RecordDefinition {abstract, tagged, limited = limitedClass, components = Just componentList} -- (implementing protocols alone: derived from the first, `new I and J with`) (Nothing, i : is) -> T.Derived T.DerivedDefinition {abstract, limited = False, parent = E.SubtypeIndication {span = i.span, notNull = False, mark = i, constraint = Nothing}, interfaces = is, extension = Just (T.ExtensionRecord (if null fields then Nothing else Just componentList))} (Just p, is) -> T.Derived T.DerivedDefinition {abstract, limited = False, parent = E.SubtypeIndication {span = p.span, notNull = False, mark = nameE p.span p.name, constraint = Nothing}, interfaces = is, extension = Just (T.ExtensionRecord (if null fields then Nothing else Just componentList))} notProtocol p = if Set.member p.name protocols then Nothing else Just p -- (`__initial__`: what is true of a new object, before any operation, EU9; its -- expression itself, `self` the type's current instance, as clients must see it) initialAspect <- case [e | PyStmt {node = FunctionStmt f} <- c.body, f.name == "__initial__", [PyStmt {node = Return (Just e)}] <- [f.body]] of e : _ -> (\v -> [aspectOf "Default_Initial_Condition" v]) <$> expr (selfAs c.name e) [] -> pure [] modify' \st -> st {parentClass = (.name) <$> (parent >>= notProtocol)} subprograms <- forM [f | f <- methods <> generatedRepr, f.name /= "Verada_Initial"] (methodItem c.name) modify' \st -> st {parentClass = Nothing} pure (item (ItemStruct StructDecl {declaration = D.TypeDecl {name = ident c.nameSpan c.name, discriminants = Nothing, definition, aspects = classAspects <> initialAspect}, fields = visibility}) : subprograms) -- `class Drawable(Protocol)`: an interface, its methods abstract (a class implements it -- by naming it as a base: Verada's interfaces are nominal) ([], [PyExpr {node = NameRef "Protocol"}]) -> do modify' \st -> st {classes = Map.insert c.name TaggedClass st.classes} let methods = [f | PyStmt {node = FunctionStmt f} <- c.body] others = [x | x <- c.body, not (isPassOrDoc x), not (isMethod x)] unless (null others) (reject s "a protocol's body holds its methods (and a docstring)" "not a method") subprograms <- forM methods \f -> methodItem c.name FunctionDef {name = f.name, nameSpan = f.nameSpan, decorators = PyExpr {span = f.nameSpan, node = NameRef "abstractmethod"} : [d | d <- f.decorators, d.node /= NameRef "abstractmethod"], typeParameters = f.typeParameters, parameters = f.parameters, returns = f.returns, body = f.body} pure (item (ItemDecl D.Decl {span = s, node = D.DType (typeDecl (T.InterfaceType T.InterfaceDefinition {kind = T.PlainInterface, parents = []}))}) : subprograms) -- `class Buffer(Protected)`: a protected type, its fields its components and its -- methods its operations (`@entry` ones wait for their `when(...)`) ([], [PyExpr {node = NameRef "Protected"}]) -> do modify' \st -> st {protectedClasses = Set.insert c.name st.protectedClasses} components <- forM [(x, n, a, d) | x@PyStmt {node = AnnAssign PyExpr {node = NameRef n} a d} <- c.body] \(x, n, a, d) -> do ty <- typeExpr a initial <- traverse expr d pure D.Decl {span = x.span, node = D.DObject D.ObjectDecl {names = [ident x.span n], aliased = False, constant = False, subtype = annotated a ty, initial, aspects = []}} operations <- forM [f | PyStmt {node = FunctionStmt f} <- c.body] (protectedOperation (Set.fromList [n | PyStmt {node = AnnAssign PyExpr {node = NameRef n} _ _} <- c.body])) let protectedSpec = D.ProtectedSpec {name = ident c.nameSpan c.name, isType = True, discriminants = Nothing, aspects = [], visible = map fst operations, private = components, endName = Nothing} protectedBody = D.ProtectedBody {name = ident c.nameSpan c.name, aspects = [], declarations = map snd operations, endName = Nothing} pure [item (ItemDecl D.Decl {span = s, node = D.DProtected protectedSpec}), Item {span = s, visibility = Hidden, node = ItemDecl D.Decl {span = s, node = D.DProtectedBody protectedBody}}] -- `class Overdrawn(Exception): pass`: an exception (of another exception, `class -- Overdrawn(ValueError)`, one that `except ValueError` handles too) ([], [PyExpr {node = NameRef base}]) | base == "Exception" || Map.member base builtinExceptions || Map.lookup base kinds == Just ExceptionClass -> do modify' \st -> st {classes = Map.insert c.name ExceptionClass st.classes, exceptionParents = Map.insert c.name base st.exceptionParents} unless (all isPassOrDoc c.body) (reject s "an exception class has no body of its own in Vibe: `pass` or a docstring" "body") pure [item (ItemDecl D.Decl {span = s, node = D.DException D.ExceptionDecl {names = [ident c.nameSpan c.name], renamed = Nothing, aspects = []}})] ([], [PyExpr {node = NameRef "RangeInt"}]) -> do scalar c.name lo <- maybe (pure (nameE s "Integer")) expr (keyword "ge") hi <- maybe (pure (nameE s "Integer")) expr (keyword "le") unless (isJust (keyword "ge") && isJust (keyword "le")) (reject s "a `RangeInt` class gives its range: `ge=` and `le=`" "range") pure [item (ItemDecl D.Decl {span = s, node = D.DType (typeDecl (T.SignedInteger E.RangeExpr {span = s, low = lo, high = hi}))})] ([], [PyExpr {node = NameRef "Modular"}]) -> do scalar c.name m <- maybe (nameE s "1" <$ reject s "a `Modular` class gives its `modulus=`" "modulus") expr (keyword "modulus") pure [item (ItemDecl D.Decl {span = s, node = D.DType (typeDecl (T.Modular m))})] ([], [PyExpr {node = NameRef "Enum"}]) -> do scalar c.name let members = [(x.span, n, v) | x@PyStmt {node = Assign [PyExpr {node = NameRef n}] v} <- c.body] literals = [ident sp n | (sp, n, _) <- members] -- `.value` and `.name` of a member: functions of the type, each a choice among -- the members (`.value` the value written, when all are integers or all strings) self' = PyExpr {span = c.nameSpan, node = NameRef "self"} member n = PyExpr {span = c.nameSpan, node = Attribute PyExpr {span = c.nameSpan, node = NameRef c.name} n} choice result = case reverse members of (_, _, _) : _ -> let (sp0, n0, _) = last members in foldr (\(sp, n, v) e -> PyExpr {span = sp, node = IfExp PyExpr {span = sp, node = Compare self' [("==", member n)]} (result sp n v) e}) (result sp0 n0 (thd (last members))) (init members) [] -> PyExpr {span = c.nameSpan, node = NoneLit} thd (_, _, v) = v resultType = case [v.node | (_, _, v) <- members] of vs | all isInt vs -> Just "int" | all isStr vs -> Just "str" _ -> Nothing isInt = \case IntLit _ -> True UnaryOp "-" PyExpr {node = IntLit _} -> True _ -> False isStr = \case StrLit _ -> True _ -> False accessor n t result = FunctionDef {name = n, nameSpan = c.nameSpan, decorators = [], typeParameters = [], parameters = [Parameter {span = c.nameSpan, name = "self", annotation = Just PyExpr {span = c.nameSpan, node = NameRef c.name}, defaultValue = Nothing}], returns = Just PyExpr {span = c.nameSpan, node = NameRef t}, body = [PyStmt {span = c.nameSpan, node = Return (Just (choice result))}]} valueFn <- traverse (\t -> functionDecl vis (accessor "value" t (\_ _ v -> v))) resultType nameFn <- functionDecl vis (accessor "name" "str" (\sp n _ -> PyExpr {span = sp, node = StrLit n})) -- `Color(3)` and `Color["RED"]`: the member of a value and of a name, functions whose -- precondition is that there is one (Python's ValueError and KeyError otherwise, D188) let lookupFn fname t key = let v = PyExpr {span = c.nameSpan, node = NameRef "v"} anyOf = case members of [] -> PyExpr {span = c.nameSpan, node = BoolLit False} _ -> PyExpr {span = c.nameSpan, node = BoolOp "or" [PyExpr {span = sp, node = Compare v [("==", key sp n x)]} | (sp, n, x) <- members]} returns' = [PyStmt {span = sp, node = If [(PyExpr {span = sp, node = Compare v [("==", key sp n x)]}, [PyStmt {span = sp, node = Return (Just (member n))}])] []} | (sp, n, x) <- init members] final = [PyStmt {span = sp, node = Return (Just (member n))} | (sp, n, _) <- take 1 (reverse members)] in FunctionDef {name = fname, nameSpan = c.nameSpan, decorators = [], typeParameters = [], parameters = [Parameter {span = c.nameSpan, name = "v", annotation = Just PyExpr {span = c.nameSpan, node = NameRef t}, defaultValue = Nothing}], returns = Just PyExpr {span = c.nameSpan, node = NameRef c.name}, body = PyStmt {span = c.nameSpan, node = ExprStmt PyExpr {span = c.nameSpan, node = Call PyExpr {span = c.nameSpan, node = NameRef "requires"} [Argument {keyword = Nothing, value = anyOf}]}} : returns' <> final} ofValue <- traverse (\t -> functionDecl vis (lookupFn ("Verada_" <> c.name <> "_Of_Value") t (\_ _ x -> x))) (if null members then Nothing else resultType) ofName <- if null members then pure Nothing else Just <$> functionDecl vis (lookupFn ("Verada_" <> c.name <> "_Of_Name") "str" (\sp n _ -> PyExpr {span = sp, node = StrLit n})) pure ([item (ItemDecl D.Decl {span = s, node = D.DType (typeDecl (T.Enumeration (map T.EnumIdentifier literals)))})] <> maybe [] pure valueFn <> [nameFn | not (null members)] <> maybe [] pure ofValue <> maybe [] pure ofName) ([], [PyExpr {node = Subscript PyExpr {node = NameRef "Array"} [component]}]) -> do array c.name ct <- typeExpr component let zeroTo sp n = E.DiscreteBounds E.RangeExpr {span = sp, low = E.Expr {span = sp, node = E.EInteger 0}, high = binary sp E.OpSub n (E.Expr {span = sp, node = E.EInteger 1})} indices <- case (keyword "index", keyword "size") of -- `rank=N`: an array of N dimensions whose bounds each value has, indexed by value -- from 0 (a matrix: `rank=2`) -- (`index=T` with it: each dimension's bounds are of T, `index=Positive` from 1) _ | Just r <- keyword "rank" -> case r.node of IntLit n | n >= 1 -> T.UnconstrainedIndices . replicate (fromInteger n) <$> maybe (pure (nameE r.span "Natural")) typeExpr (keyword "index") _ -> T.ConstrainedIndices [] <$ reject r.span "an `Array` class's `rank=` is a whole number from 1" "rank" -- `shape=(M, N)`: each dimension's size, indexed from 0 _ | Just sh <- keyword "shape" -> case sh.node of TupleLit sizes@(_ : _) -> T.ConstrainedIndices <$> mapM (\n -> zeroTo n.span <$> expr n) sizes _ -> T.ConstrainedIndices [] <$ reject sh.span "an `Array` class's `shape=` is a tuple of sizes: `shape=(3, 3)`" "shape" (Just i, _) -> do it <- typeExpr i pure (T.ConstrainedIndices [E.DiscreteSubtype E.SubtypeIndication {span = i.span, notNull = False, mark = it, constraint = Nothing}]) (_, Just n) -> do size <- expr n pure (T.ConstrainedIndices [E.DiscreteBounds E.RangeExpr {span = n.span, low = E.Expr {span = n.span, node = E.EInteger 0}, high = binary n.span E.OpSub size (E.Expr {span = n.span, node = E.EInteger 1})}]) _ -> T.ConstrainedIndices [] <$ reject s "an `Array` class gives its `index=` type, its `size=`, its `shape=` or its `rank=`" "no bounds" pure [item (ItemDecl D.Decl {span = s, node = D.DType (typeDecl (T.ArrayType T.ArrayDefinition {indices, component = T.ComponentDefinition {aliased = False, subtype = indication component.span ct}}))})] _ -> [] <$ reject s "Vibe does not take this class: write a `@dataclass`, or a class of `RangeInt`, `Modular`, `Enum` or `Array[T]`" "class" where scalar n = modify' \st -> st {classes = Map.insert n ScalarClass st.classes} array n = modify' \st -> st {classes = Map.insert n ArrayClass st.classes} isField x = case x.node of AnnAssign {} -> True _ -> False isMethod x = case x.node of FunctionStmt _ -> True _ -> False -- `ABC` alone, or a class of the module (its parent), or none abstractBase bases = any (\b -> b.node == NameRef "ABC") bases -- (protocols aside: they are interfaces it implements) parentOf ps bases = case [b | b@PyExpr {node = NameRef n} <- bases, n /= "ABC", not (Set.member n ps)] of [] -> Just Nothing [PyExpr {node = NameRef n, span = sp}] -> Just (Just Named {span = sp, name = n}) _ -> Nothing isPassOrDoc x = case x.node of Pass -> True ExprStmt PyExpr {node = StrLit _} -> True ExprStmt PyExpr {node = NameRef "..."} -> True _ -> False -- * Subprograms -- | Whether @c.n@ names a member of an `Enum` class: the module's own, or one named by -- @from m import C@ or through its Vibe module (@m.C.N@). Another module's class is taken to be -- an enumeration when its member is selected, as no other class's attribute is a value in -- Vibe (`first` and `last` are its bounds). isEnumMember :: PyExpr -> Text -> D Bool isEnumMember c n | n `elem` ["first", "last"] = pure False | otherwise = case c.node of NameRef k -> do own <- gets (Map.lookup k . (.enums)) imported <- gets (Map.member k . (.importedFrom)) pure case own of Just members -> n `elem` members Nothing -> imported && startsUpper k -- (a Vibe module's class: `Ada.Text_IO.X` is a package's X) Attribute PyExpr {node = NameRef m} k | Text.toLower m `notElem` ["ada", "interfaces", "system", "gnat", "verada", "standard"] -> gets ((&& startsUpper k) . Set.member m . (.modules)) Attribute _ _ -> pure False _ -> pure False where startsUpper = maybe False (isUpper . fst) . Text.uncons -- | What to write instead of a dataclass option Vibe does not take. optionAdvice :: Text -> Text optionAdvice = \case "frozen" -> "; a value that must not change is a constant (`Final`), or an `in` parameter" "slots" -> "; a dataclass's fields are its only attributes already" "order" -> "; define the comparison as a function of the module" _ -> "" -- | `@dataclass`, or `@dataclass(limited=True)`. isDataclass :: PyExpr -> Bool isDataclass d = case d.node of NameRef "dataclass" -> True Call PyExpr {node = NameRef "dataclass"} _ -> True _ -> False -- | The decorators a Vibe function may have. knownFunctionDecorator :: PyExpr -> Bool knownFunctionDecorator d = case d.node of NameRef n -> n `elem` ["terminates", "ghost", "entry", "task", "abstractmethod"] _ -> False -- | What the module's annotations say of its names (Verada.Vibe.Types): its functions' -- results, its classes' fields (a plain class's `self.f` too) and methods' results, its own -- annotated names. moduleTypeEnv :: [PyStmt] -> TypeEnv moduleTypeEnv body = TypeEnv { names = Map.fromList [(n, t) | PyStmt {node = AnnAssign PyExpr {node = NameRef n} a _} <- body, Just t <- [annotationType a]] , results = Map.fromList [(f.name, t) | PyStmt {node = FunctionStmt f} <- body, Just r <- [f.returns], Just t <- [annotationType r]] , fieldTypes = Map.fromList [(c.name, Map.fromList (classFields c)) | c <- classDefs] , methodResults = Map.fromList [(c.name, Map.fromList [(f.name, t) | PyStmt {node = FunctionStmt f} <- c.body, Just r <- [f.returns], Just t <- [annotationType r]]) | c <- classDefs] , classNames = Set.fromList (map (.name) classDefs) } where classDefs = [c | PyStmt {node = ClassStmt c} <- body] classFields c = [(n, t) | PyStmt {node = AnnAssign PyExpr {node = NameRef n} a _} <- c.body, Just t <- [classVarless a]] -- (a property is read as a field) <> [(f.name, t) | PyStmt {node = FunctionStmt f} <- c.body, any ((== NameRef "property") . (.node)) f.decorators, Just r <- [f.returns], Just t <- [annotationType r]] -- (a plain class's fields, as its `__init__` assigns them) <> [ (n, t) | PyStmt {node = FunctionStmt f} <- c.body , f.name == "__init__" , let params = Map.fromList [(p.name, t') | p <- f.parameters, Just a <- [p.annotation], Just t' <- [annotationType a]] , (n, t) <- initFields params f.body ] classVarless a = case a.node of Subscript PyExpr {node = NameRef "ClassVar"} [x] -> annotationType x _ -> annotationType a initFields params ss = [(n, t) | PyStmt {node = AnnAssign PyExpr {node = Attribute PyExpr {node = NameRef "self"} n} a _} <- ss, Just t <- [annotationType a]] <> [(n, t) | PyStmt {node = Assign [PyExpr {node = Attribute PyExpr {node = NameRef "self"} n}] v} <- ss, Just t <- [Types.typeOf emptyEnv {names = params} v]] emptyEnv = TypeEnv {names = Map.empty, results = Map.empty, fieldTypes = Map.empty, methodResults = Map.empty, classNames = Set.empty} -- | The type Python gives an expression here, where the annotations fix it. pyType :: PyExpr -> D (Maybe PyType) pyType e = do st <- get pure (Types.typeOf st.moduleTypes {names = st.localTypes} e) -- | Names bound to types, for the rest of the function (Python's names are the function's). noteTypes :: Map Text PyType -> D () noteTypes ts = modify' \st -> st {localTypes = Map.union ts st.localTypes} -- | The types a statement gives the names it binds. bindsTypes :: PyStmt -> D () bindsTypes st = case st.node of AnnAssign PyExpr {node = NameRef n} a _ | Just t <- annotationType a -> noteTypes (Map.singleton n t) Assign targets v -> pyType v >>= \case Just t -> noteTypes (Map.unions [bindTarget x t | x <- targets]) Nothing -> case (targets, v.node) of -- (`a, b = 1, 2`: each its value's) ([PyExpr {node = TupleLit xs}], TupleLit vs) | length xs == length vs -> do ts <- mapM pyType vs noteTypes (Map.unions [bindTarget x t | (x, Just t) <- zip xs ts]) _ -> pure () For target source _ _ -> do st' <- get forM_ (Types.sourceElement st'.moduleTypes {names = st'.localTypes} source) (noteTypes . bindTarget target) _ -> pure () functionDecl :: Visibility -> FunctionDef -> D Item functionDecl vis f = do -- (the parameters' types, for the body; the names around a nested function's too) outerTypes <- gets (.localTypes) noteTypes (Map.fromList [(p.name, t) | p <- f.parameters, Just a <- [p.annotation], Just t <- [annotationType a]]) -- (and its locals', in the order they are bound: Python's names are the function's, and -- the forms read before the statements, `pythonForms`, need them too) mapM_ bindsTypes (ownStatements f.body) outerGeneric <- gets (\st -> (st.genericFormals, st.formalPackages)) unless (null f.typeParameters) (modify' \st -> st {genericFormals = Set.fromList [t | (t, _, _) <- f.typeParameters], formalPackages = []}) item <- functionDeclTyped vis f modify' \st -> st {localTypes = outerTypes, genericFormals = fst outerGeneric, formalPackages = snd outerGeneric} pure item functionDeclTyped :: Visibility -> FunctionDef -> D Item functionDeclTyped vis f = do -- (Python's positional-only and keyword-only markers restrict calls, which Vibe's calls, -- by position or by name in another module too, cannot keep: they are refused, not erased) forM_ [p | p <- f.parameters, p.name `elem` ["/", "*"]] \p -> reject p.span ("`" <> p.name <> "` in a parameter list is not in Vibe: a Vibe parameter is passed by position or by name") "parameter marker" -- (variadics, vibe-syntax section 8) forM_ [p | p <- f.parameters, variadic p] \p -> reject p.span (if "**" `Text.isPrefixOf` p.name then "`" <> p.name <> "` is not in Vibe: a Vibe function has a fixed list of typed parameters; give each its own name and type, with a default value where a caller may leave it out" else "`" <> p.name <> "` is not in Vibe: a Vibe function has a fixed list of typed parameters; take a `list` where the number of values varies") "variadic" -- (a decorator Vibe does not know would be ignored, and a reader could take it to mean -- something: it is refused) forM_ [d | d <- f.decorators, not (knownFunctionDecorator d)] \d -> reject d.span "this decorator is not one Vibe takes: a function's are `@terminates`, `@ghost`, `@entry`, `@task` and `@abstractmethod`" "decorator" -- (a parameter is changed where its components are assigned, or where it is passed to a -- function, or is the object of a method, that changes it: Python's object is the same) changedByCalls <- gets (callChanged f.body . (.changedParameters)) let componentWrites = throughViews f.body (Set.fromList (concatMap componentAssigned f.body) <> changedByCalls) params <- forM [p | p <- f.parameters, p.name `notElem` ["/", "*"], not (variadic p)] \p -> case p.annotation of Nothing -> Nothing <$ reject p.span ("give `" <> p.name <> "` a type: Vibe\x27s parameters are typed, as typed Python\x27s are") "no type" Just a -> do plain <- typeExpr a -- a parameter of a tagged class takes its subclasses too, as Python's does (`self` is -- the class itself: the subprogram is its primitive) classes <- gets (.classes) let ty = case a.node of NameRef n | Map.lookup n classes == Just TaggedClass, p.name /= "self" -> attribute a.span plain "Class" _ -> plain dflt <- traverse expr p.defaultValue -- (a finalizer changes its object, through whatever it calls: `__del__`, EU8) let mode = if p.name `Set.member` componentWrites || (f.name == "Verada_Finalize" && p.name == "self") then T.ModeInOut else T.ModeDefault pure (Just T.Parameter {span = p.span, names = [ident p.span p.name], aliased = False, mode, subtype = T.ParameterSubtype T.SubtypeMark {notNull = ownedAlone a, mark = ty}, initial = dflt, aspects = []}) -- a parameter the function assigns is its own local copy, as Python's name is: the body -- reads and assigns a local that starts as the parameter's value (not one whose object -- it changes too, which Python would change for the caller up to the assignment) let assignedParams = [p | p <- f.parameters, p.name `Set.member` rebound] forM_ [p | p <- assignedParams, p.name `Set.member` componentWrites || p.name == "self"] \p -> reject p.span ("`" <> p.name <> "` is a parameter the function both changes and assigns: in Python the changes before the assignment reach the caller's object and those after do not, which Vibe's copy cannot keep. Change it, or assign a new local name, `" <> p.name <> "_copy = copy(" <> p.name <> ")`") "parameter changed and assigned" result <- case f.returns of Nothing -> Nothing <$ reject f.nameSpan "give the function\x27s result type: `-> None` for none" "no result type" Just PyExpr {node = NoneLit} -> pure Nothing Just r -> Just . T.ReturnSubtype . T.SubtypeMark (ownedAlone r) <$> typeExpr r -- a function that changes an argument (Python's method that changes its object, and -- returns) is a procedure whose last parameter, `out`, is its result (LN11) protectedContext <- gets (.inProtected) procedures <- gets (.procedureFunctions) let changesComponents = case protectedContext of Just (cs, isEntry) -> isEntry || not (Set.null (Set.intersection cs (Set.fromList (concatMap assignedNames f.body <> concatMap componentAssigned f.body)))) Nothing -> False -- (a nested function that assigns its enclosing function's locals, `nonlocal`, changes -- them: a procedure, as one that changes its parameters is) upLevel = not (null [() | PyStmt {node = Nonlocal (_ : _)} <- ownStatements f.body]) -- (a context manager's `__enter__` and `__exit__` may change their object, print, -- close: procedures underneath, D176) managerOperation = f.name `elem` ["Verada_Enter", "Verada_Exit"] -- (a function that may propagate an exception, `raises(...)`, is a procedure too: a -- function's calls never raise, Verada's rule) propagates = not (null [() | PyStmt {node = ExprStmt PyExpr {node = Call PyExpr {node = NameRef "raises"} _}} <- contracts]) || Map.member key procedures -- (a method by its class's name and its own) (isMethod, key) = case f.parameters of p : _ | p.name == "self", Just PyExpr {node = NameRef c} <- p.annotation -> (True, "." <> c <> "." <> f.name) p : _ | p.name == "self" -> (True, "." <> f.name) _ -> (False, f.name) sideEffects = isJust result && (any (\p -> p.name `Set.member` componentWrites) f.parameters || changesComponents || upLevel || managerOperation || propagates) resultParam = [T.Parameter {span = f.nameSpan, names = [ident f.nameSpan resultName], aliased = False, mode = T.ModeOut, subtype = T.ParameterSubtype m, initial = Nothing, aspects = []} | sideEffects, Just (T.ReturnSubtype m) <- [result]] kind = if isJust result && not sideEffects then D.FunctionKind else D.ProcedureKind -- (an operator Python's special method defines, `__lt__`, is the operator's function) specName = if not (Text.null f.name) && Text.all (`elem` ("=<>+-*/" :: String)) f.name || f.name == "abs" && isMethod then E.Expr {span = f.nameSpan, node = E.EString f.name} else nameE f.nameSpan f.name spec = D.SubprogramSpec {span = f.nameSpan, kind, overriding = Nothing, name = specName, profile = T.SubprogramProfile {parameters = catMaybes params <> resultParam, result = if sideEffects then Nothing else result}} -- (`global` and `nonlocal` come first in Python, before the contracts that name them) (scopes, unscoped) = span isScope (dropDocstring f.body) (contracts, body0) = (\(cs, rest) -> (cs, scopes <> rest)) (span isContract unscoped) body = body0 copies = [p | p <- assignedParams, not (p.name `Set.member` componentWrites), p.name /= "self"] contractAspects <- (if sideEffects then map (resultAsParameter f.name) else id) . catMaybes <$> mapM (contractAspect f.name) contracts -- `@terminates`: Always_Terminates; `@ghost`: Ghost (EU3), for contracts and proof only let aspects = contractAspects <> [E.AspectSpec {span = d.span, mark = ident d.span a, classWide = False, value = Nothing} | d <- f.decorators, Just a <- [lookup d.node [(NameRef "terminates", "Always_Terminates"), (NameRef "ghost", "Ghost")]]] let paramNames = Set.fromList [p.name | p <- f.parameters] <> maybe Set.empty fst protectedContext node <- case body of -- one `return`: an expression function, whose value callers' proofs see -- (a generic's has a body of its own: Ada has no generic expression functions) -- (a public one that names the module's private declarations has a body instead: its -- expression, in the visible part, could not name them) [PyStmt {node = Return (Just v)}] | isJust result, null f.typeParameters, not sideEffects, vis /= Public || not (namesPrivate v) -> do value <- withResultOf f.name (expr v) pure (D.DSubprogram D.SubprogramDecl {spec, form = D.ExpressionFunction E.Expr {span = v.span, node = E.EParen value}, aspects}) _ -> do prepared <- pythonForms f.returns body ss <- (if sideEffects then map returnsIntoResult else id) <$> statements paramNames prepared -- (each copy declared over the body with the parameter's name, from the parameter's -- value held under another name in a block around it, the parameter being hidden) held <- forM [(p, a) | p <- copies, Just a <- [p.annotation]] \(p, a) -> do mark <- typeExpr a let other = "Verada_Parameter_" <> p.name object n v constant = D.Decl {span = p.span, node = D.DObject D.ObjectDecl {names = [ident p.span n], aliased = False, constant, subtype = indication p.span mark, initial = Just (nameE p.span v), aspects = []}} pure (object other p.name True, object p.name other False) let ss' = if null ss then [S.Stmt {span = f.nameSpan, node = S.SNull}] else ss block ds xs = S.Stmt {span = f.nameSpan, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just ds, statements = xs, handlers = [], endLabel = Nothing}} copied = if null held then ss' else [block (map fst held) [block (map snd held) ss']] pure (D.DSubprogramBody D.SubprogramBody {spec, aspects, declarations = [], statements = copied, handlers = [], endName = Nothing}) -- PEP 695's type parameters: a generic subprogram, each a private type -- (`T: Ordered` also takes T's `"<"`, by default the one visible at the instance; `T: P` -- of a protocol P takes P's methods, each by default the one visible at the instance) protocolBounds <- gets (.protocolMethods) packageFormals <- gets (.formalPackages) boundFormals <- forM f.typeParameters \(t, sp, bound) -> case bound >>= (`Map.lookup` protocolBounds) of Nothing -> pure [] Just methods -> forM methods \m -> do formalParams <- forM [p | p <- m.parameters, p.name `notElem` ["/", "*"]] \p -> do mark <- if p.name == "self" then pure (nameE sp t) else maybe (pure (nameE sp "Integer")) typeExpr p.annotation pure T.Parameter {span = sp, names = [ident sp p.name], aliased = False, mode = T.ModeDefault, subtype = T.ParameterSubtype T.SubtypeMark {notNull = False, mark}, initial = Nothing, aspects = []} result' <- case m.returns of Just PyExpr {node = NoneLit} -> pure Nothing Just r -> (\mark -> Just (T.ReturnSubtype T.SubtypeMark {notNull = False, mark})) <$> typeExpr r Nothing -> pure Nothing pure (D.FormalSubprogramNode D.FormalSubprogram {span = sp, spec = D.SubprogramSpec {span = sp, kind = if isJust result' then D.FunctionKind else D.ProcedureKind, overriding = Nothing, name = nameE sp m.name, profile = T.SubprogramProfile {parameters = formalParams, result = result'}}, abstract = False, defaultSubprogram = D.BoxDefault, aspects = []}) let formals = concat [D.FormalTypeNode D.TypeDecl {name = ident sp t, discriminants = Nothing, definition = T.Private T.PrivateDefinition {abstract = False, tagged = False, limited = False}, aspects = []} : [ordering sp t | bound == Just "Ordered"] <> fs | ((t, sp, bound), fs) <- zip f.typeParameters boundFormals] -- (a container of a type parameter, `list[T]`: a formal package, D188) <> [D.FormalPackageNode D.FormalPackage {span = f.nameSpan, name = ident f.nameSpan package, generic = dottedE f.nameSpan generic, actuals = D.GivenActuals [E.Argument {span = f.nameSpan, formal = Nothing, value = E.ArgExpr (actualE f.nameSpan a), reference = Nothing} | a <- actuals], aspects = []} | null [() | null f.typeParameters], (package, generic, actuals) <- packageFormals] ordering sp t = let param n = T.Parameter {span = sp, names = [ident sp n], aliased = False, mode = T.ModeDefault, subtype = T.ParameterSubtype T.SubtypeMark {notNull = False, mark = nameE sp t}, initial = Nothing, aspects = []} in D.FormalSubprogramNode D.FormalSubprogram {span = sp, spec = D.SubprogramSpec {span = sp, kind = D.FunctionKind, overriding = Nothing, name = E.Expr {span = sp, node = E.EString "<"}, profile = T.SubprogramProfile {parameters = [param "Left", param "Right"], result = Just (T.ReturnSubtype T.SubtypeMark {notNull = False, mark = nameE sp "Boolean"})}}, abstract = False, defaultSubprogram = D.BoxDefault, aspects = []} declared = D.Decl {span = f.nameSpan, node} -- (the generic at an empty place after the name: comments go with the subprogram) let after = f.nameSpan {start = f.nameSpan.end} pure Item {span = f.nameSpan, visibility = vis, node = ItemDecl if null formals then declared else D.Decl {span = after, node = D.DGeneric D.GenericDecl {formals, unit = declared}}} where namesPrivate :: (Data a) => a -> Bool namesPrivate x = case cast x of Just PyExpr {node = NameRef n} -> "_" `Text.isPrefixOf` n && n /= "_" && n `notElem` map (.name) f.parameters _ -> or (gmapQ namesPrivate x) variadic p = "*" `Text.isPrefixOf` p.name && p.name /= "*" rebound = Set.fromList (concatMap assignedNames f.body) -- (a change through a view, `b = p.inner; b.x = 1`, is a change of what it views) dropDocstring = \case PyStmt {node = ExprStmt PyExpr {node = StrLit _}} : rest -> rest ss -> ss isScope st = case st.node of Global _ -> True Nonlocal _ -> True _ -> False isContract st = case st.node of ExprStmt PyExpr {node = Call PyExpr {node = NameRef n} _} -> n `elem` ["requires", "ensures", "raises", "decreases"] _ -> False withResultOf _ = id -- | Each function of a module (by name) and method (by `.` and its name, all classes' -- together), each parameter with whether the function changes it: its components assigned -- (through views too), or passed to a parameter another one changes, to the fixed point. changedParametersOf :: [PyStmt] -> Map Text [(Text, Bool)] changedParametersOf defs = go (Map.map (\(f, own) -> [(p.name, Set.member p.name own) | p <- f.parameters]) functions) where functions = Map.fromListWith (\(f, a) (_, b) -> (f, a <> b)) ( [(f.name, (f, local f)) | PyStmt {node = FunctionStmt f} <- defs] <> [("." <> f.name, (f, local f)) | PyStmt {node = ClassStmt c} <- defs, PyStmt {node = FunctionStmt f} <- c.body] ) local f = throughViews f.body (Set.fromList (concatMap componentAssigned f.body)) <> Set.fromList ["self" | f.name == "__del__"] go known = let next = Map.map (\(f, own) -> let changed = throughViews f.body (own <> callChanged f.body known) in [(p.name, Set.member p.name changed) | p <- f.parameters]) functions in if next == known then known else go next -- | The module's functions (and methods, after a `.`) with a result that do input or output -- (`print`, `input`, or a call of another that does) or may propagate an exception -- (`raises(...)`), with their results' annotations: Verada's functions do neither, so each is -- a procedure with an `out` result. procedureFunctionsOf :: [PyStmt] -> Map Text PyExpr procedureFunctionsOf = procedureFunctionsWith Set.empty Map.empty -- | Previous accepted REPL functions seed propagation through new wrappers; their -- already-lowered profiles remain authoritative, rather than reinterpreting old bodies -- against the session's current names. procedureFunctionsWith :: Set Text -> Map Text PyExpr -> [PyStmt] -> Map Text PyExpr procedureFunctionsWith priorEffects prior defs = Map.union current prior where current = Map.fromList [(k, r) | (k, (f, r)) <- Map.toList withResults, Set.member k (Set.union own (go (priorEffects <> direct))), f.name /= "__init__"] withResults = Map.fromList ( [(f.name, (f, r)) | PyStmt {node = FunctionStmt f} <- defs, Just r <- [f.returns], r.node /= NoneLit] <> [("." <> c.name <> "." <> f.name, (f, r)) | PyStmt {node = ClassStmt c} <- defs, PyStmt {node = FunctionStmt f} <- c.body, Just r <- [f.returns], r.node /= NoneLit] ) everyFunction = [(f.name, f) | PyStmt {node = FunctionStmt f} <- defs] <> [("." <> c.name <> "." <> f.name, f) | PyStmt {node = ClassStmt c} <- defs, PyStmt {node = FunctionStmt f} <- c.body] -- (input and output pass to the callers; an exception a caller may handle, and a -- module variable's change, are the function's own) direct = Set.fromList [k | (k, f) <- everyFunction, any (`elem` ["print", "input"]) (calledNames f.body)] own = Set.fromList [k | (k, f) <- everyFunction, raisesIn f || writesGlobals f] -- (one that assigns a module variable, `global x`, changes the module's state) writesGlobals f = not (null [() | PyStmt {node = Global (_ : _)} <- f.body]) raisesIn f = not (null [() | PyStmt {node = ExprStmt PyExpr {node = Call PyExpr {node = NameRef "raises"} _}} <- f.body]) -- (one that calls a function doing input or output does it too) go known = -- (through calls of the module's functions; a method is known by its name alone, -- which other classes' methods may share, so its calls are not followed) let next = Set.union known (Set.fromList [k | (k, f) <- everyFunction, any (\c -> Set.member c known && not ("." `Text.isPrefixOf` c)) (calledNames f.body)]) in if next == known then known else go next -- | The names of the functions a body calls (and of the methods, after a `.`). calledNames :: (Data a) => a -> [Text] calledNames x = here <> concat (gmapQ calledNames x) where here = case cast x of Just PyExpr {node = Call PyExpr {node = NameRef f} _} -> [f] Just PyExpr {node = Call PyExpr {node = Attribute _ m} _} -> ["." <> m] _ -> [] -- | The names a body passes to a parameter that the callee changes (or calls a method that -- changes its object on), by what is known of the module's functions. callChanged :: [PyStmt] -> Map Text [(Text, Bool)] -> Set Text callChanged body known = Set.fromList (concatMap changedBy (calls body)) where calls :: (Data a) => a -> [(PyExpr, [Argument])] calls x = [(f, args) | Just PyExpr {node = Call f args} <- [cast x]] <> concat (gmapQ calls x) changedBy (f, args) = case f.node of NameRef g -> passed g args -- (a module's function, `m.f(x)`, is not the module's own; a method's object comes first) Attribute o m | Just _ <- rootName o -> passed ("." <> m) (Argument {keyword = Nothing, value = o} : args) _ -> [] passed g args = case Map.lookup g known of Just ps -> [ n | (k, a) <- zip [0 :: Int ..] args , let changed = case a.keyword of Nothing | k < length ps -> maybe False snd (listToMaybe (drop k ps)) Just kw -> fromMaybe False (lookup kw ps) _ -> False , changed , Just n <- [rootName a.value] ] Nothing -> [] rootName e = case e.node of NameRef n -> Just n Attribute p _ -> rootName p Subscript p _ -> rootName p _ -> Nothing -- | The `out` parameter that is a side-effecting function's result. resultName :: Text resultName = "Verada_Result" -- | A contract of a side-effecting function: its `result` is its result parameter. resultAsParameter :: Text -> E.AspectSpec -> E.AspectSpec resultAsParameter fname a = E.AspectSpec {span = a.span, mark = a.mark, classWide = a.classWide, value = rewrite <$> a.value} where rewrite :: (Data x) => x -> x rewrite x = case cast x of Just (e :: E.Expr) | E.EAttribute at <- e.node, at.designator.text == "Result", E.ENameRef n <- at.prefix.node, n.text == fname -> fromMaybe x (cast (nameE e.span resultName)) _ -> gmapT rewrite x -- | `return e` of a side-effecting function: its result parameter is e, then it returns. returnsIntoResult :: S.Stmt -> S.Stmt returnsIntoResult = rewrite where rewrite :: (Data x) => x -> x rewrite x = case cast x of Just (st :: S.Stmt) | S.SReturn (Just v) <- st.node -> fromMaybe x (cast S.Stmt {span = st.span, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Nothing, statements = [S.Stmt {span = st.span, node = S.SAssign S.Assignment {target = nameE st.span resultName, value = v}}, S.Stmt {span = st.span, node = S.SReturn Nothing}], handlers = [], endLabel = Nothing}}) _ -> gmapT rewrite x -- | @requires(c)@ and @ensures(c)@ as @Pre@ and @Post@. contractAspect :: Text -> PyStmt -> D (Maybe E.AspectSpec) contractAspect fname st = case st.node of -- `raises({E: c, ...})`: what holds when the subprogram propagates each exception ExprStmt PyExpr {node = Call PyExpr {node = NameRef "raises"} [Argument {value = PyExpr {node = DictLit cases}}]} -> do assocs <- forM cases \(e, c) -> do name <- expr e v <- inContract (expr c) pure (E.NamedAssocNode E.NamedAssoc {span = c.span, choices = [E.ChoiceExpr name], value = E.AssocExpr v}) pure (Just E.AspectSpec {span = st.span, mark = ident st.span "Exceptional_Cases", classWide = False, value = Just E.Expr {span = st.span, node = E.EAggregate E.Aggregate {bracket = False, contents = E.PlainAggregate (E.Associations assocs)}}}) -- `raises(E, ...)`: the subprogram may propagate each, whenever (`raises({E: True})`) ExprStmt PyExpr {node = Call PyExpr {node = NameRef "raises"} as@(_ : _)} | all (\a -> isNothing a.keyword && isName a.value) as -> contractAspect fname PyStmt {span = st.span, node = ExprStmt PyExpr {span = st.span, node = Call PyExpr {span = st.span, node = NameRef "raises"} [Argument {keyword = Nothing, value = PyExpr {span = st.span, node = DictLit [(a.value, PyExpr {span = a.value.span, node = BoolLit True}) | a <- as]}}]}} -- `decreases(e)` first in a function's body (in a loop's, it is the loop's variant): a -- value that each recursive call makes smaller, its `Subprogram_Variant` ExprStmt PyExpr {node = Call PyExpr {node = NameRef "decreases"} [a]} -> do v <- expr a.value let decreasing = E.NamedAssocNode E.NamedAssoc {span = a.value.span, choices = [E.ChoiceExpr (nameE st.span "Decreases")], value = E.AssocExpr v} pure (Just E.AspectSpec {span = st.span, mark = ident st.span "Subprogram_Variant", classWide = False, value = Just E.Expr {span = st.span, node = E.EAggregate E.Aggregate {bracket = False, contents = E.PlainAggregate (E.Associations [decreasing])}}}) ExprStmt PyExpr {node = Call PyExpr {node = NameRef n} [a]} -> do v <- inContract (expr a.value) pure (Just E.AspectSpec {span = st.span, mark = ident st.span (if n == "requires" then "Pre" else "Post"), classWide = False, value = Just v}) _ -> Nothing <$ reject st.span "a contract takes one condition" "contract" where isName x = case x.node of NameRef _ -> True Attribute q _ -> isName q _ -> False inContract = fmap (resultOf fname) -- | @result@ in a postcondition is the function\x27s @'Result@, @old(x)@ is @x'Old@. resultOf :: Text -> E.Expr -> E.Expr resultOf fname = go where go e = case e.node of E.ENameRef i | i.text == "result" -> attribute e.span (nameE e.span fname) "Result" E.EApply a | E.ENameRef i <- a.prefix.node , i.text == "old" , [E.Argument {value = E.ArgExpr x}] <- a.arguments -> attribute e.span (go x) "Old" _ -> mapChildren go e -- | The direct sub-expressions of an expression, rewritten. mapChildren :: (E.Expr -> E.Expr) -> E.Expr -> E.Expr mapChildren f e = E.Expr {span = e.span, node = case e.node of E.ESelected s -> E.ESelected E.Selected {prefix = f s.prefix, selector = s.selector} E.EApply a -> E.EApply E.Apply {prefix = f a.prefix, arguments = [E.Argument {span = arg.span, formal = arg.formal, value = mapArg arg.value, reference = arg.reference} | arg <- a.arguments], bracketed = a.bracketed} E.EAttribute a -> E.EAttribute E.AttributeRef {prefix = f a.prefix, designator = a.designator, arguments = map f a.arguments} E.EUnary u -> E.EUnary E.Unary {op = u.op, operand = f u.operand} E.EBinary b -> E.EBinary E.Binary {op = b.op, left = f b.left, right = f b.right} E.EParen x -> E.EParen (f x) E.EIf i -> E.EIf E.IfExpr {condition = f i.condition, thenValue = f i.thenValue, elsifs = [E.ElsifValue {condition = f x.condition, value = f x.value} | x <- i.elsifs], elseValue = f <$> i.elseValue} E.EQuantified q -> E.EQuantified E.Quantified {quantifier = q.quantifier, iterator = q.iterator, predicate = f q.predicate} E.EMembership m -> E.EMembership E.Membership {negated = m.negated, operand = f m.operand, choices = m.choices} E.ESurfaceForm sf -> E.ESurfaceForm E.SurfaceForm {kind = sf.kind, operands = map f sf.operands} n -> n} where mapArg = \case E.ArgExpr x -> E.ArgExpr (f x) v -> v -- | An expression of number literals, one at least a float's (a universal real in Ada). floatLiteral :: PyExpr -> Bool floatLiteral e = hasFloat e && literal e where literal x = case x.node of FloatLit _ _ -> True IntLit _ -> True UnaryOp _ y -> literal y BinOp _ y z -> literal y && literal z _ -> False hasFloat x = case x.node of FloatLit _ _ -> True UnaryOp _ y -> hasFloat y BinOp _ y z -> hasFloat y || hasFloat z _ -> False -- | A place another name's value is taken from (a variable, a field, an element): Python -- shares the object there, Vibe copies it (vibe-sharing design C, staged before D). isPlace :: PyExpr -> Bool isPlace e = case e.node of NameRef _ -> True Attribute p _ -> isPlace p -- (a slice is a new value, Python's too) Subscript _ [i] | isSlice i -> False Subscript p _ -> isPlace p _ -> False -- | Names a statement changes in place: their components, or by a method of theirs that -- changes its object. changedThrough :: PyStmt -> [Text] changedThrough = componentAssigned -- | Design C's second rule: an object stored into another (appended, put in a field or an -- element) and then changed, which Python's sharing would change in both places. sharing :: [PyStmt] -> D () sharing = go Set.empty where go _ [] = pure () go stored (st : rest) = do let changed = [n | n <- changedThrough st, Set.member n stored] forM_ (take 1 changed) \n -> reject st.span ("`" <> n <> "` was stored before (Vibe stores a copy, Python the object itself): changing it now would not change what was stored. Change it before storing it, or store `copy(" <> n <> ")` and say so") "changed after it was stored" go (stored <> Set.fromList (storedBy st)) rest storedBy st = case st.node of ExprStmt PyExpr {node = Call PyExpr {node = Attribute _ m} args} | m `elem` ["append", "add", "insert"] -> [n | Argument {value = PyExpr {node = NameRef n}} <- args] Assign [PyExpr {node = Attribute _ _}] PyExpr {node = NameRef n} -> [n] Assign [PyExpr {node = Subscript _ _}] PyExpr {node = NameRef n} -> [n] _ -> [] -- | Names whose objects a call may change: receivers of methods, and actuals given by name. mayChange :: (Data a) => a -> Set Text mayChange x = here <> Set.unions (gmapQ mayChange x) where here = case cast x of -- (Python's own functions change nothing) Just PyExpr {node = Call PyExpr {node = NameRef g} _} | g `elem` ["print", "len", "str", "repr", "int", "bool", "float", "abs", "min", "max", "range", "all", "any", "copy", "replace", "apl", "image", "sorted", "reversed", "sum", "ord", "chr", "round", "divmod", "enumerate", "zip", "isinstance", "format", "hex", "bin", "oct", "pow"] -> Set.empty Just PyExpr {node = Call f args} -> Set.fromList ([n | Attribute PyExpr {node = NameRef n} _ <- [f.node]] <> [n | Argument {value = PyExpr {node = NameRef n}} <- args]) -- (`del x` frees what x owns, and so changes x) _ -> case cast x of Just PyStmt {node = Del targets} -> Set.fromList [n | PyExpr {node = NameRef n} <- targets] _ -> Set.empty -- | Design D: a local bound to a path of names and fields (`b = a`, `node = g.first`) whose -- object is then changed is a view of it (an object renaming), as Python's name shares it. viewPath :: PyExpr -> Maybe [Text] viewPath e = case e.node of NameRef n -> Just [n] Attribute p f -> (<> [f]) <$> viewPath p _ -> Nothing -- | An actual of a Python generic type, by name: the class's name, and the module it comes -- from when another module declares it (imported by name, or written `m.P`). elementOf :: Map Text [Text] -> Set Text -> PyExpr -> Maybe (Text, Maybe [Text]) elementOf imported modules e = case e.node of NameRef a -> Just (a, Map.lookup a imported) Attribute PyExpr {node = NameRef m} a | Set.member m modules -> Just (a, Just [m]) _ -> Nothing -- | An assignment to a component of an element (`c[i].f = v`, `c[i].f += v`), the -- container a path and the index a literal or a name: the container, the index, and the -- assignment with something else in the element's place. elementComponent :: PyStmt -> Maybe (PyExpr, PyExpr, PyExpr -> PyStmt) elementComponent st = case st.node of Assign [t] v -> (\(c, i, r) -> (c, i, \x -> PyStmt {span = st.span, node = Assign [r x] v})) <$> split t AugAssign t op v -> (\(c, i, r) -> (c, i, \x -> PyStmt {span = st.span, node = AugAssign (r x) op v})) <$> split t _ -> Nothing where split t = case t.node of Attribute p f -> case p.node of Subscript c [i] | isJust (viewPath c), stable i -> Just (c, i, \x -> PyExpr {span = t.span, node = Attribute x f}) _ -> (\(c, i, r) -> (c, i, \x -> PyExpr {span = t.span, node = Attribute (r x) f})) <$> split p _ -> Nothing stable i = case i.node of IntLit _ -> True StrLit _ -> True NameRef _ -> True _ -> False -- | An empty container written as a value (`[]`, `{}`, `set()`, `list()`, `dict()`). emptyContainer :: PyExpr -> Bool emptyContainer e = case e.node of ListLit [] -> True DictLit [] -> True Call PyExpr {node = NameRef c} [] -> c `elem` ["set", "list", "dict"] _ -> False -- | A field's value in a constructor: an empty container is the field's own, empty (an -- empty aggregate here, which the constructor's aggregate writes `<>`). constructValue :: PyExpr -> D E.Expr constructValue v | emptyContainer v = pure E.Expr {span = v.span, node = E.EAggregate E.Aggregate {bracket = False, contents = E.PlainAggregate (E.Associations [])}} | otherwise = expr v -- | A call that may be of a procedure underneath (LN11), whose result a declaration takes -- by an assignment after it: a method, or a function of the program (not Python's own, nor -- a class's constructor). procedureLike :: PyExprNode -> Bool procedureLike = \case Attribute _ _ -> True NameRef f -> maybe False (\(c, _) -> isLower c) (Text.uncons f) && f `notElem` ["print", "len", "str", "float", "int", "abs", "min", "max", "range", "all", "any", "copy", "replace", "move", "deref", "sorted", "reversed", "sum", "apl", "image", "plain_sum", "lane_sum", "is_int", "enumerate", "list"] _ -> False -- | Whether a list stores a name back into an element of a path (`nodes[k] = n`): an -- element taken out and put back by hand, as Vibe's translation back writes a view. putsBack :: [Text] -> Text -> [PyStmt] -> Bool putsBack path n rest = not (null [() | PyStmt {node = Assign [PyExpr {node = Subscript c _}] PyExpr {node = NameRef m}} <- allStatements rest, m == n, viewPath c == Just path]) -- | The statements of a list, with those nested in them. allStatements :: (Data a) => a -> [PyStmt] allStatements x = maybe [] pure (cast x) <> concat (gmapQ allStatements x) -- | Whether a statement names a path (or a longer one through it), other than as `len`'s -- argument. mentionsPath :: (Data a) => [Text] -> a -> Bool mentionsPath path x = case cast x of Just PyExpr {node = Call PyExpr {node = NameRef "len"} [Argument {value = a}]} | viewPath a == Just path -> False Just (e :: PyExpr) | Just p <- viewPath e, path `isPrefixOf` p -> True _ -> or (gmapQ (mentionsPath path) x) -- * Python's control forms, as forms Ada has -- | A function's body (or a REPL input's statements) with the Python forms that Ada has no -- statement for written as ones it has, innermost first: a loop's `else`, `try`'s `else` and -- `finally`, a `continue` inside a `try` or a `match`, a chained assignment, a walrus in a -- condition or a comprehension's filter, and starred unpacking. Each keeps Python's meaning; -- the result type is the function's, for a `return` whose value waits while a `finally` runs. pythonForms :: Maybe PyExpr -> [PyStmt] -> D [PyStmt] pythonForms result = fmap concat . mapM one where one st = descend st >>= rewrite within = pythonForms result descend st = case st.node of If arms e -> do arms' <- forM arms \(c, b) -> (c,) <$> within b e' <- within e pure PyStmt {span = st.span, node = If arms' e'} While c b e -> (\b' e' -> PyStmt {span = st.span, node = While c b' e'}) <$> within b <*> within e For t x b e -> (\b' e' -> PyStmt {span = st.span, node = For t x b' e'}) <$> within b <*> within e Match x cs -> (\cs' -> PyStmt {span = st.span, node = 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 PyStmt {span = st.span, node = Try b' hs' e' f'} _ -> pure st rewrite st0 = do -- (a call of a function that is a procedure underneath, inside an expression, made -- first into a local of its result's type) procedures <- gets (.procedureFunctions) let callsOne x = not (null [() | PyExpr {node = Call PyExpr {node = NameRef g} _} <- universePy x, Map.member g procedures]) case st0.node of -- (in a branch of a conditional expression, which Python evaluates only when it is -- chosen: the statement for each branch, `return a if c else b` an `if`) Return (Just PyExpr {node = IfExp c a b}) | callsOne a || callsOne b -> within [PyStmt {span = st0.span, node = If [(c, [PyStmt {span = st0.span, node = Return (Just a)}])] [PyStmt {span = st0.span, node = Return (Just b)}]}] _ -> do (before, st) <- hoistProcedureCalls procedures st0 (before <>) <$> rewriteForm st rewriteForm st = case st.node of -- `for n in [1, 2, 3]`: the list made first, into a local of the type its elements -- give (a container the loop alone held would not be freed) For t src@PyExpr {node = ListLit (_ : _)} b e -> displayed st t src b e For t src@PyExpr {node = SetLit (_ : _)} b e -> displayed st t src b e -- `xs.sort(reverse=True)`: sorted, then reversed ExprStmt PyExpr {node = Call PyExpr {node = Attribute xs "sort", span = fs} [Argument {keyword = Just "reverse", value = PyExpr {node = BoolLit rev}}], span = cs} -> pure ([PyStmt {span = st.span, node = ExprStmt PyExpr {span = cs, node = Call PyExpr {span = fs, node = Attribute xs "sort"} []}}] <> [PyStmt {span = st.span, node = ExprStmt PyExpr {span = cs, node = Call PyExpr {span = fs, node = Attribute xs "reverse"} []}} | rev]) -- `d.setdefault(k, v)`: v stored at k unless k has one (then `x = d[k]`, where its -- value is taken) ExprStmt PyExpr {node = Call PyExpr {node = Attribute d "setdefault"} [Argument {keyword = Nothing, value = k}, Argument {keyword = Nothing, value = v}]} | steadyOperand k || isStrLit k -> pure [setDefault d k v] Assign [t@PyExpr {node = NameRef _}] PyExpr {node = Call PyExpr {node = Attribute d "setdefault"} [Argument {keyword = Nothing, value = k}, Argument {keyword = Nothing, value = v}]} | steadyOperand k || isStrLit k -> pure [setDefault d k v, PyStmt {span = st.span, node = Assign [t] PyExpr {span = st.span, node = Subscript d [k]}}] -- `a = b = v`: v once, then each target in turn, a copy of it (Vibe's values are -- copied where Python's objects are shared) Assign targets@(first : more@(_ : _)) v -> case first.node of NameRef _ -> pure (PyStmt {span = st.span, node = Assign [first] v} : [PyStmt {span = t.span, node = Assign [t] first} | t <- more]) _ -> do held <- freshName "Verada_Value_" let named = PyExpr {span = v.span, node = NameRef held} pure (PyStmt {span = st.span, node = Assign [named] v} : [PyStmt {span = t.span, node = Assign [t] named} | t <- targets]) -- `a, *rest = xs`: the items before and after the starred target, by position, and the -- starred one a slice of the rest Assign [PyExpr {node = TupleLit targets}] v | any isStarred targets -> unpacked st targets v For t x b e | not (null e) -> loopElse st b e \b' -> PyStmt {span = st.span, node = For t x b' []} While c b e | not (null e) -> loopElse st b e \b' -> PyStmt {span = st.span, node = While c b' []} While c b [] | hoistable c -> do (before, c') <- hoist c let (heads, rest) = span loopAnnotation b stop = PyStmt {span = c.span, node = If [(PyExpr {span = c.span, node = UnaryOp "not" c'}, [PyStmt {span = c.span, node = Break}])] []} pure [PyStmt {span = st.span, node = While PyExpr {span = c.span, node = BoolLit True} (heads <> before <> [stop] <> rest) []}] If arms e | any (hoistable . fst) arms -> walrusIf arms e -- `ys: list[T] = [e for x in xs if (y := f(x)) > 0]`: the loop that fills it, the -- walrus's name bound before each filter that names it AnnAssign t a (Just PyExpr {node = ListComp element [c], span = vs}) | any hoistable c.conditions, PyExpr {node = NameRef n} <- t -> do let append = PyStmt {span = vs, node = ExprStmt PyExpr {span = vs, node = Call PyExpr {span = vs, node = Attribute PyExpr {span = t.span, node = NameRef n} "append"} [Argument {keyword = Nothing, value = element}]}} filtered <- foldr (\k inner -> inner >>= \ss -> do (before, k') <- hoist k pure (before <> [PyStmt {span = k.span, node = If [(k', ss)] []}])) (pure [append]) c.conditions -- (over a range, the list holds at most one value for each step so far) let counted = case (c.target.node, c.source.node) of (NameRef x, Call PyExpr {node = NameRef "range"} args) | Just lo <- rangeStart [g.value | g <- args] -> let len' = PyExpr {span = vs, node = Call PyExpr {span = vs, node = NameRef "len"} [Argument {keyword = Nothing, value = PyExpr {span = t.span, node = NameRef n}}]} bound = PyExpr {span = vs, node = Compare len' [("<=", PyExpr {span = vs, node = BinOp "-" PyExpr {span = c.target.span, node = NameRef x} lo})]} in [PyStmt {span = vs, node = ExprStmt PyExpr {span = vs, node = Call PyExpr {span = vs, node = NameRef "invariant"} [Argument {keyword = Nothing, value = bound}]}}] _ -> [] rangeStart = \case [_] -> Just (intLit vs 0) [lo, _] -> Just lo _ -> Nothing pure [PyStmt {span = st.span, node = AnnAssign t a (Just PyExpr {span = vs, node = ListLit []})}, PyStmt {span = vs, node = For c.target c.source (counted <> filtered) []}] -- (a match with guards tests its subject case by case: a value that is no name is -- taken once) Match x cs | any (isJust . (.guard)) cs, Nothing <- viewPath x -> do held <- freshName "Verada_Value_" let named = PyExpr {span = x.span, node = NameRef held} pure [PyStmt {span = x.span, node = Assign [named] x}, PyStmt {span = st.span, node = Match named cs}] Try b hs e f | not (null f) -> finallyForm st b hs e f Try b hs e [] | not (null e) -> do inner <- tryElse st b hs e concat <$> mapM continuing inner _ -> continuing st displayed st t src b e = pyType src >>= \case Just ct | containerType ct -> do held <- freshName "Verada_List_" let named = PyExpr {span = src.span, node = NameRef held} pure [PyStmt {span = src.span, node = AnnAssign named (typeAnnotation src.span ct) (Just src)}, PyStmt {span = st.span, node = For t named b e}] _ -> pure [st] isStrLit x = case x.node of StrLit _ -> True _ -> False setDefault d k v = PyStmt {span = d.span, node = If [(PyExpr {span = d.span, node = Compare k [("not in", d)]}, [PyStmt {span = d.span, node = Assign [PyExpr {span = d.span, node = Subscript d [k]}] v}])] []} isStarred x = case x.node of Starred _ -> True _ -> False unpacked st targets v | Nothing <- viewPath v, not (steadyPlace v) = [] <$ reject v.span "starred unpacking takes a named list, string or array (`a, *rest = xs`): name the value first" "not named" | (before, PyExpr {node = Starred s} : after) <- break isStarred targets, not (any isStarred after) = do -- (of a str, the starred name is a list of its characters, Python's; the others -- are each a character) ofText <- (== Just PStr) <$> pyType v character <- freshName "Verada_Character_" let sp = v.span n = toInteger (length before) m = toInteger (length after) len' = PyExpr {span = sp, node = Call PyExpr {span = sp, node = NameRef "len"} [Argument {keyword = Nothing, value = v}]} fromEnd j = PyExpr {span = sp, node = BinOp "-" len' (intLit sp j)} item t k = PyExpr {span = t.span, node = Subscript v [k]} assign t x = PyStmt {span = t.span, node = Assign [t] x} wild t = t.node == NameRef "_" heads = [assign t (item t (intLit t.span i)) | (i, t) <- zip [0 ..] before, not (wild t)] sliced = item s PyExpr {span = s.span, node = Slice (if n == 0 then Nothing else Just (intLit s.span n)) (if m == 0 then Nothing else Just (fromEnd m)) Nothing} characters = PyExpr {span = s.span, node = ListComp PyExpr {span = s.span, node = NameRef character} [Comprehension {target = PyExpr {span = s.span, node = NameRef character}, source = sliced, conditions = []}]} middle | wild s = [] | ofText = [PyStmt {span = s.span, node = AnnAssign s (typeAnnotation s.span (PList PStr)) (Just characters)}] | otherwise = [assign s sliced] tails = [assign t (item t (fromEnd (m - j))) | (j, t) <- zip [0 ..] after, not (wild t)] pure (heads <> middle <> tails) | otherwise = [] <$ reject st.span "an assignment takes one starred target (`a, *rest = xs`)" "starred" -- a `continue` inside a `try` or a `match` (Ada's handlers and cases have no way back to -- the loop): the code 3 kept, the rest of what it is in skipped, then `continue` after it continuing st = case st.node of _ | isTryOrMatch st, exitsTo False 0 st -> do leave <- freshName "Verada_Leave_" pure ([declaredAs st.span leave "int" (intLit st.span 0)] <> redirect False leave Nothing [st] <> [PyStmt {span = st.span, node = If [(leaving st.span leave 3, [PyStmt {span = st.span, node = Continue}])] []}]) _ -> pure [st] isTryOrMatch st = case st.node of Try {} -> True Match {} -> True _ -> False -- `for ...: body else: e`: e when the loop ends but not by its `break` loopElse st body e rebuild | any (breaks 0) body = do broke <- freshName "Verada_Broke_" let set s = [PyStmt {span = s, node = Assign [PyExpr {span = s, node = NameRef broke}] PyExpr {span = s, node = BoolLit True}}, PyStmt {span = s, node = Break}] pure [ declaredAs st.span broke "bool" PyExpr {span = st.span, node = BoolLit False} , rebuild (atLoopLevel (\s -> case s.node of { Break -> Just (set s.span); _ -> Nothing }) body) , PyStmt {span = st.span, node = If [(PyExpr {span = st.span, node = UnaryOp "not" PyExpr {span = st.span, node = NameRef broke}}, e)] []} ] | otherwise = pure (rebuild body : e) breaks d s = case s.node of Break -> d == (0 :: Int) While _ b e -> any (breaks (d + 1)) b || any (breaks d) e For _ _ b e -> any (breaks (d + 1)) b || any (breaks d) e _ -> any (any (breaks d)) (innerBodies s) -- `try: b except ...: h else: e`: e when b ends normally, outside the handlers tryElse st b hs e | null hs = pure (b <> e) | otherwise = do done <- freshName "Verada_Done_" let named = PyExpr {span = st.span, node = NameRef done} pure [ declaredAs st.span done "bool" PyExpr {span = st.span, node = BoolLit False} , PyStmt {span = st.span, node = Try (b <> [PyStmt {span = st.span, node = Assign [named] PyExpr {span = st.span, node = BoolLit True}}]) hs [] []} , PyStmt {span = st.span, node = If [(named, e)] []} ] -- `try ... finally: f`: f on every way out. Each `return`, and each `break` and `continue` -- of the loop around, is kept as a code (and the value returned) while f runs, then -- taken; an exception runs f in a handler that raises it again. finallyForm st b hs e f = do forM_ (take 1 [s | s <- f, exitsTo True 0 s]) \s -> reject s.span "a `return`, `break` or `continue` in a `finally` would drop the exception it runs for: leave after the `try` statement instead" "leaves a finally" inner <- tryElse st b hs e leave <- freshName "Verada_Leave_" let valued = not (null [() | PyStmt {node = Return (Just _)} <- ownStatements inner]) value <- if valued then Just <$> freshName "Verada_Return_" else pure Nothing let sp = st.span codes = [k | (k, p) <- [(1, isReturn), (2, isBreak), (3, isContinue)], any (exitsBy p 0) inner] protected = redirect True leave value inner handler = ExceptClause {span = sp, exceptions = Nothing, name = Nothing, body = f <> [PyStmt {span = sp, node = Raise Nothing}]} afterwards = [ PyStmt {span = sp, node = If [(leaving sp leave k, [PyStmt {span = sp, node = taken k}])] []} | k <- codes ] taken :: Integer -> PyStmtNode taken = \case 1 -> Return (fmap (\v -> PyExpr {span = sp, node = NameRef v}) value) 2 -> Break _ -> Continue valueDecl <- case (value, result) of (Just v, Just r) -> pure [PyStmt {span = sp, node = AnnAssign PyExpr {span = sp, node = NameRef v} r Nothing}] (Just _, Nothing) -> [] <$ reject sp "a `return` with a value inside `try ... finally` is in a function with a result type" "no result type" _ -> pure [] pure ([declaredAs sp leave "int" (intLit sp 0)] <> valueDecl <> [PyStmt {span = sp, node = Try protected [handler] [] []}] <> f <> afterwards) where isReturn s = case s.node of { Return _ -> True; _ -> False } isBreak s = case s.node of { Break -> True; _ -> False } isContinue s = case s.node of { Continue -> True; _ -> False } -- an `if` whose conditions bind names (`if (n := f()) > 0:`): each such condition's -- names bound before it is tested, its later `elif`s under its `else` walrusIf arms e = case arms of [] -> pure e (c, b) : more -> do (before, c') <- hoist c rest <- if null more then pure e else walrusIf more e pure (before <> [PyStmt {span = c.span, node = If [(c', b)] rest}]) -- | The statements of a list and those nested in them, not a nested function's. ownStatements :: [PyStmt] -> [PyStmt] ownStatements = concatMap \s -> s : ownStatements (concat (innerBodies s)) -- | A loop annotation (`invariant(...)`, `decreases(...)`, `increases(...)`), which stays -- first in its loop's body. loopAnnotation :: PyStmt -> Bool loopAnnotation x = case x.node of ExprStmt PyExpr {node = Call PyExpr {node = NameRef n} _} -> n `elem` ["invariant", "decreases", "increases"] _ -> False -- | A fresh name for what the desugaring keeps (`Verada_Leave_3`). freshName :: Text -> D Text freshName prefix = do n <- gets (.counter) modify' \st -> st {counter = n + 1} pure (prefix <> Text.pack (show (n + 1))) intLit :: Span -> Integer -> PyExpr intLit s k = PyExpr {span = s, node = IntLit k} -- | `n: t = v`. declaredAs :: Span -> Text -> Text -> PyExpr -> PyStmt declaredAs s n t v = PyStmt {span = s, node = AnnAssign PyExpr {span = s, node = NameRef n} PyExpr {span = s, node = NameRef t} (Just v)} -- | `leave == k`. leaving :: Span -> Text -> Integer -> PyExpr leaving s leave k = PyExpr {span = s, node = Compare PyExpr {span = s, node = NameRef leave} [("==", intLit s k)]} -- | Each statement at a loop's own level (not in a nested loop or function) that `f` replaces. atLoopLevel :: (PyStmt -> Maybe [PyStmt]) -> [PyStmt] -> [PyStmt] atLoopLevel f = concatMap at where at s = case f s of Just r -> r Nothing -> case s.node of If arms e -> [PyStmt {span = s.span, node = If [(c, atLoopLevel f b) | (c, b) <- arms] (atLoopLevel f e)}] Match x cs -> [PyStmt {span = s.span, node = Match x [MatchCase {pattern = c.pattern, guard = c.guard, body = atLoopLevel f c.body} | c <- cs]}] Try b hs e fin -> [PyStmt {span = s.span, node = Try (atLoopLevel f b) [ExceptClause {span = h.span, exceptions = h.exceptions, name = h.name, body = atLoopLevel f h.body} | h <- hs] (atLoopLevel f e) (atLoopLevel f fin)}] While c b e -> [PyStmt {span = s.span, node = While c b (atLoopLevel f e)}] For t x b e -> [PyStmt {span = s.span, node = For t x b (atLoopLevel f e)}] _ -> [s] -- | Whether a statement leaves by an exit `redirect` takes: a `continue` of the loop around -- it (at depth 0), and with every exit, a `return` anywhere and a `break` of that loop too. exitsTo :: Bool -> Int -> PyStmt -> Bool exitsTo every = exitsBy \s -> case s.node of Return _ -> every Break -> every Continue -> True _ -> False -- | Whether a statement leaves by an exit `p` names: a `return` at any depth, a `break` or -- `continue` only at depth 0 (one in a nested loop is that loop's). exitsBy :: (PyStmt -> Bool) -> Int -> PyStmt -> Bool exitsBy p d s = case s.node of Return _ -> p s Break -> d == 0 && p s Continue -> d == 0 && p s While _ b e -> any (exitsBy p (d + 1)) b || any (exitsBy p d) e For _ _ b e -> any (exitsBy p (d + 1)) b || any (exitsBy p d) e _ -> any (any (exitsBy p d)) (innerBodies s) -- | Statements whose exits (as `exitsTo every` says) store their code in `leave` instead (1 -- for `return`, its value in `value`; 2 for `break`; 3 for `continue`), the statements after -- one run only while none was taken: within a nested loop, a `return` also leaves the loop, -- and the statements after the loop leave theirs. redirect :: Bool -> Text -> Maybe Text -> [PyStmt] -> [PyStmt] redirect every leave value = go 0 where go :: Int -> [PyStmt] -> [PyStmt] go _ [] = [] go d (s : rest) = case s.node of Return v | every -> [PyStmt {span = s.span, node = Assign [PyExpr {span = s.span, node = NameRef r}] x} | Just x <- [v], Just r <- [value]] <> [code s.span 1] <> [PyStmt {span = s.span, node = Break} | d > 0] Break | every, d == 0 -> [code s.span 2] Continue | d == 0 -> [code s.span 3] _ | not (exitsTo every d s) -> s : go d rest _ -> inner d s : guarded d s.span (go d rest) code sp k = PyStmt {span = sp, node = Assign [PyExpr {span = sp, node = NameRef leave}] (intLit sp k)} inner d s = case s.node of If arms e -> PyStmt {span = s.span, node = If [(c, go d b) | (c, b) <- arms] (go d e)} While c b e -> PyStmt {span = s.span, node = While c (go (d + 1) b) (go d e)} For t x b e -> PyStmt {span = s.span, node = For t x (go (d + 1) b) (go d e)} Match x cs -> PyStmt {span = s.span, node = Match x [MatchCase {pattern = c.pattern, guard = c.guard, body = go d c.body} | c <- cs]} Try b hs e f -> PyStmt {span = s.span, node = Try (go d b) [ExceptClause {span = h.span, exceptions = h.exceptions, name = h.name, body = go d h.body} | h <- hs] (go d e) (go d f)} _ -> s guarded d sp rest | null rest = [] | d == 0 = [PyStmt {span = sp, node = If [(leaving sp leave 0, rest)] []}] | otherwise = PyStmt {span = sp, node = If [(PyExpr {span = sp, node = Compare PyExpr {span = sp, node = NameRef leave} [("!=", intLit sp 0)]}, [PyStmt {span = sp, node = Break}])] []} : rest -- | Whether an expression binds a name (`n := e`) where it is always evaluated, which the -- statement before its test can do instead. hoistable :: PyExpr -> Bool hoistable e = case e.node of NamedExpr _ _ -> True _ -> any hoistable (evaluatedFirst e) -- | The operands an expression always evaluates (not those after `and`/`or`, a chained -- comparison's later ones, or a conditional's branches). evaluatedFirst :: PyExpr -> [PyExpr] evaluatedFirst e = case e.node of Compare a ((_, b) : _) -> [a, b] BinOp _ a b -> [a, b] UnaryOp _ a -> [a] BoolOp _ (a : _) -> [a] Call _ args -> map (.value) args Attribute p _ -> [p] Subscript p is -> p : is IfExp c _ _ -> [c] _ -> [] -- | The statements binding an expression's walrus names (where it always evaluates them), in -- the order Python evaluates them, and the expression that reads the names instead. hoist :: PyExpr -> D ([PyStmt], PyExpr) hoist e = case e.node of NamedExpr n v -> do (before, v') <- hoist v pure (before <> [PyStmt {span = e.span, node = Assign [PyExpr {span = e.span, node = NameRef n}] v'}], PyExpr {span = e.span, node = NameRef n}) Compare a ((o, b) : more) -> do (x, a') <- hoist a (y, b') <- hoist b pure (x <> y, PyExpr {span = e.span, node = Compare a' ((o, b') : more)}) BinOp o a b -> do (x, a') <- hoist a (y, b') <- hoist b pure (x <> y, PyExpr {span = e.span, node = BinOp o a' b'}) UnaryOp o a -> fmap (\a' -> PyExpr {span = e.span, node = UnaryOp o a'}) <$> hoist a BoolOp o (a : more) -> fmap (\a' -> PyExpr {span = e.span, node = BoolOp o (a' : more)}) <$> hoist a Call f args -> do hoisted <- forM args \a -> fmap (\v -> Argument {keyword = a.keyword, value = v}) <$> hoist a.value pure (concatMap fst hoisted, PyExpr {span = e.span, node = Call f (map snd hoisted)}) IfExp c a b -> fmap (\c' -> PyExpr {span = e.span, node = IfExp c' a b}) <$> hoist c _ -> pure ([], e) -- | The calls a statement makes, where Python always evaluates them, of the module's -- functions that are procedures underneath (input and output, exceptions): each made first, -- into a new local of its result's type, which the statement reads instead. A call that is -- an assignment's whole value stays (the procedure's result goes to the target). hoistProcedureCalls :: Map Text PyExpr -> PyStmt -> D ([PyStmt], PyStmt) hoistProcedureCalls procedures st = case st.node of ExprStmt e@PyExpr {node = Call _ _} | procedureCall e -> (\(b, _) -> (b, PyStmt {span = st.span, node = Pass})) <$> made e ExprStmt e@PyExpr {node = Call _ _} | not (procedureCall e) -> (\(b, e') -> (b, PyStmt {span = st.span, node = ExprStmt e'})) <$> made e Return (Just v) -> (\(b, v') -> (b, PyStmt {span = st.span, node = Return (Just v')})) <$> made v Assign ts v | not (procedureCall v) -> (\(b, v') -> (b, PyStmt {span = st.span, node = Assign ts v'})) <$> made v AnnAssign t a (Just v) | not (procedureCall v) -> (\(b, v') -> (b, PyStmt {span = st.span, node = AnnAssign t a (Just v')})) <$> made v AugAssign t o v -> (\(b, v') -> (b, PyStmt {span = st.span, node = AugAssign t o v'})) <$> made v If ((c, b) : more) e -> (\(bs, c') -> (bs, PyStmt {span = st.span, node = If ((c', b) : more) e})) <$> made c _ -> pure ([], st) where procedureCall e = case e.node of Call PyExpr {node = NameRef f} _ -> Map.member f procedures _ -> False display v = case v.node of SetLit _ -> True DictLit (_ : _) -> True ListLit (_ : _) -> True ListComp _ _ -> True SetComp _ _ -> True DictComp {} -> True _ -> False comprehensionOf v = case v.node of GeneratorExp x cs -> Just PyExpr {span = v.span, node = ListComp x cs} ListComp _ _ -> Just v _ -> Nothing hoistArgs args = do hoisted <- forM args \a -> fmap (\v -> Argument {keyword = a.keyword, value = v}) <$> made a.value pure (concatMap fst hoisted, map snd hoisted) made e = case e.node of Call f@PyExpr {node = NameRef n} args | Just r <- Map.lookup n procedures -> do (before, args') <- hoistArgs args held <- freshName "Verada_Result_" let named = PyExpr {span = e.span, node = NameRef held} pure (before <> [PyStmt {span = e.span, node = AnnAssign named r (Just PyExpr {span = e.span, node = Call f args'})}], named) -- (`min(f(x) for x in xs)`, and `max` and `sorted` of a generator or a comprehension: -- of the list it gives, made first into a local, whose filling loop says how long it -- is, which `min` and `max` need) -- (`sorted(s)` of a set: the list of its elements, already in order) Call PyExpr {node = NameRef "sorted"} [Argument {keyword = Nothing, value = v}] | steadyPlace v -> pyType v >>= \case Just (PSet et) -> do held <- freshName "Verada_List_" element <- freshName "Verada_Element_" let named = PyExpr {span = v.span, node = NameRef held} x = PyExpr {span = v.span, node = NameRef element} pure ([PyStmt {span = v.span, node = AnnAssign named (typeAnnotation v.span (PList et)) (Just PyExpr {span = v.span, node = ListComp x [Comprehension {target = x, source = v, conditions = []}]})}], named) _ -> pure ([], e) Call f@PyExpr {node = NameRef q} [Argument {keyword = Nothing, value = v}] | q `elem` ["min", "max", "sorted", "list"] , Just listed <- comprehensionOf v -> do t <- pyType listed case t of Just lt@(PList _) -> do held <- freshName "Verada_List_" let named = PyExpr {span = v.span, node = NameRef held} -- (`list(...)` of a generator is the list itself) use = if q == "list" then named else PyExpr {span = e.span, node = Call f [Argument {keyword = Nothing, value = named}]} pure ([PyStmt {span = v.span, node = AnnAssign named (typeAnnotation v.span lt) (Just listed)}], use) _ -> pure ([], e) -- (a display passed to a method of a list, a set or a dict, `d.update({"b": 2})`, `s <= -- {3}`: made first, of the object's type) Call f@PyExpr {node = Attribute recv _} args | any (display . (.value)) args -> do t <- pyType recv case t of Just ct | containerType ct -> do hoisted <- forM args \a -> if display a.value then do held <- freshName "Verada_Value_" let named = PyExpr {span = a.value.span, node = NameRef held} pure ([PyStmt {span = a.value.span, node = AnnAssign named (typeAnnotation a.value.span ct) (Just a.value)}], Argument {keyword = a.keyword, value = named}) else fmap (\v -> Argument {keyword = a.keyword, value = v}) <$> made a.value pure (concatMap fst hoisted, PyExpr {span = e.span, node = Call f (map snd hoisted)}) _ -> fmap (\args' -> PyExpr {span = e.span, node = Call f args'}) <$> hoistArgs args Call f args -> fmap (\args' -> PyExpr {span = e.span, node = Call f args'}) <$> hoistArgs args Compare a ((o, b) : more) -> do (x, a') <- made a (y, b') <- made b pure (x <> y, PyExpr {span = e.span, node = Compare a' ((o, b') : more)}) BinOp o a b -> do (x, a') <- made a (y, b') <- made b pure (x <> y, PyExpr {span = e.span, node = BinOp o a' b'}) UnaryOp o a -> fmap (\a' -> PyExpr {span = e.span, node = UnaryOp o a'}) <$> made a BoolOp o (a : more) -> fmap (\a' -> PyExpr {span = e.span, node = BoolOp o (a' : more)}) <$> made a TupleLit xs -> do hoisted <- mapM made xs pure (concatMap fst hoisted, PyExpr {span = e.span, node = TupleLit (map snd hoisted)}) FString parts -> do hoisted <- forM parts \case Left t -> pure ([], Left t) Right x -> fmap Right <$> made x pure (concatMap fst hoisted, PyExpr {span = e.span, node = FString (map snd hoisted)}) FormatField x c spec -> fmap (\x' -> PyExpr {span = e.span, node = FormatField x' c spec}) <$> made x -- (a list's slice with a step, a new list: made first into a local, which owns it) Subscript p [PyExpr {node = Slice _ _ (Just _)}] -> pyType p >>= \case Just lt@(PList _) -> do held <- freshName "Verada_List_" let named = PyExpr {span = e.span, node = NameRef held} pure ([PyStmt {span = e.span, node = AnnAssign named (typeAnnotation e.span lt) (Just e)}], named) _ -> pure ([], e) Subscript p is -> fmap (\p' -> PyExpr {span = e.span, node = Subscript p' is}) <$> made p _ -> pure ([], e) -- | A loop body without its `continue`s (Ada has none): what follows an `if` one of whose -- branches continues goes into each branch, after the branch's own statements, and a -- `continue` drops what follows it. So `if c: continue` then the rest is `if c: pass else: -- the rest`. A `continue` in a `match`, a `try` or a nested loop's body is not this loop's, -- or is left for the desugaring to reject. withoutContinue :: [PyStmt] -> [PyStmt] withoutContinue = \case [] -> [] PyStmt {node = Continue} : _ -> [] s@PyStmt {node = If arms e} : rest | any continues (concatMap snd arms <> e) -> [PyStmt {span = s.span, node = If [(c, orPass s (withoutContinue (b <> rest))) | (c, b) <- arms] (withoutContinue (e <> rest))}] s : rest -> s : withoutContinue rest where continues x = case x.node of Continue -> True If arms e -> any continues (concatMap snd arms <> e) _ -> False -- (a branch must have a statement) orPass s = \case [] -> [PyStmt {span = s.span, node = Pass}] xs -> xs -- | A statement put before each `return` of a list, and each `break` and `continue` of its -- own loop (not one nested in it). putBackBefore :: PyStmt -> [PyStmt] -> [PyStmt] putBackBefore pb = concatMap (at False) where at inLoop s = case s.node of Return _ -> [pb, s] Break | not inLoop -> [pb, s] Continue | not inLoop -> [pb, s] If arms e -> [PyStmt {span = s.span, node = If [(c, concatMap (at inLoop) b) | (c, b) <- arms] (concatMap (at inLoop) e)}] While c b e -> [PyStmt {span = s.span, node = While c (concatMap (at True) b) (concatMap (at inLoop) e)}] For t xs b e -> [PyStmt {span = s.span, node = For t xs (concatMap (at True) b) (concatMap (at inLoop) e)}] Match x cs -> [PyStmt {span = s.span, node = Match x [MatchCase {pattern = c.pattern, guard = c.guard, body = concatMap (at inLoop) c.body} | c <- cs]}] Try b hs e f -> [PyStmt {span = s.span, node = Try (concatMap (at inLoop) b) [ExceptClause {span = h.span, exceptions = h.exceptions, name = h.name, body = concatMap (at inLoop) h.body} | h <- hs] (concatMap (at inLoop) e) (concatMap (at inLoop) f)}] _ -> [s] pathText :: [Text] -> Text pathText = Text.intercalate "." -- | Names a method is called on (`b.widen(3)`): their objects may change. receivers :: (Data a) => a -> Set Text receivers x = here <> Set.unions (gmapQ receivers x) where here = case cast x of Just PyExpr {node = Call PyExpr {node = Attribute PyExpr {node = NameRef n} _} _} -> Set.singleton n _ -> Set.empty -- | The names changed in a body, with the roots of the views changed in it. throughViews :: [PyStmt] -> Set Text -> Set Text throughViews body changed = let more = Set.fromList [r | (n, r : _) <- views, Set.member n changed || Set.member n (receivers body)] in if more `Set.isSubsetOf` changed then changed else throughViews body (changed <> more) where views = [(n, path) | PyStmt {node = Assign [PyExpr {node = NameRef n}] v} <- allStmts body, Just path <- [elementPath v]] <> [(n, path) | PyStmt {node = AnnAssign PyExpr {node = NameRef n} _ (Just v)} <- allStmts body, Just path <- [elementPath v]] -- (an element's view, `n = nodes[i]`, changes the container) elementPath v = case v.node of Subscript c [_] -> viewPath c _ -> viewPath v allStmts :: (Data a) => a -> [PyStmt] allStmts x = maybe [] pure (cast x) <> concat (gmapQ allStmts x) -- | Paths a statement list assigns as a whole (`a = ...`, `a.p = ...`). assignedPaths :: PyStmt -> [[Text]] assignedPaths st = case st.node of Assign ts _ -> concatMap targetPaths ts AnnAssign t _ _ -> targetPaths t AugAssign t _ _ -> targetPaths t _ -> concatMap (concatMap assignedPaths) (innerBodies st) where targetPaths t = case t.node of TupleLit xs -> concatMap targetPaths xs _ -> maybe [] pure (viewPath t) -- | The statement lists directly inside a compound statement: its branches, bodies, -- handlers and `else` and `finally` parts (not a nested function's or class's body). innerBodies :: PyStmt -> [[PyStmt]] innerBodies st = case st.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] _ -> [] -- | The names a statement mentions (a loop annotation's, to know one Vibe wrote). invariantNames :: PyStmt -> [Text] invariantNames st = [n | PyExpr {node = NameRef n} <- universePy st] -- | The ints a loop's body only increases, by literals, outside loops of its own, with the -- most any one path through the body adds (a step's gain): a counting loop's counters. Each -- is a local int declared before the loop, not the loop's own name, and assigned nowhere -- else in the body. countersOf :: St -> Text -> [PyStmt] -> [(Text, Integer)] countersOf now t body = [ (n, gain) | n <- nub [m | (m, _) <- increments body] , n /= t , Map.lookup n now.localTypes == Just PInt , length [() | m <- concatMap assignedNames body, m == n] == length [() | (m, _) <- increments body, m == n] , let gain = pathMost n body , gain > 0 ] where increments = concatMap top top st = case st.node of AugAssign PyExpr {node = NameRef n} "+" PyExpr {node = IntLit c} | c >= 0 -> [(n, c)] While {} -> [] For {} -> [] _ -> concatMap increments (innerBodies st) -- (along one path: a sequence's increments add up, a choice takes its greatest branch) pathMost n = sum . map (stmtMost n) stmtMost n st = case st.node of AugAssign PyExpr {node = NameRef m} "+" PyExpr {node = IntLit c} | m == n -> c If arms e -> maximum (pathMost n e : [pathMost n b | (_, b) <- arms]) Match _ cs -> maximum (0 : [pathMost n c.body | c <- cs]) While {} -> 0 For {} -> 0 _ -> sum (map (pathMost n) (innerBodies st)) -- | How much a loop's body grows the list it names (a row of a list of lists): the least -- and most `append`s along a path, where nothing else changes its length (an element -- replaced keeps it); Nothing where something else might (another method, a call it is -- passed to, an append in a loop of its own). rowGrowth :: Text -> [PyStmt] -> Maybe (Integer, Integer) rowGrowth r body | r `elem` concatMap assignedNames body = Nothing | not (null [() | PyExpr {node = Call PyExpr {node = Attribute PyExpr {node = NameRef r'} m} _} <- universePy body, r' == r, m `notElem` ["append", "count", "index", "copy"]]) = Nothing | not (null [() | PyExpr {node = Call f args} <- universePy body, not (onlyReads f), PyExpr {node = NameRef r'} <- map (.value) args, r' == r]) = Nothing | not (null [() | PyStmt {node = Del ts} <- allStatements body, PyExpr {node = Subscript PyExpr {node = NameRef r'} _} <- ts, r' == r]) = Nothing | any inLoop body = Nothing | otherwise = Just (if early then 0 else least body, most body) where onlyReads f = case f.node of NameRef g -> g `elem` ["len", "print", "sum", "min", "max", "sorted", "str", "repr", "list", "any", "all", "enumerate", "zip", "reversed"] Attribute PyExpr {node = NameRef r'} _ -> r' == r _ -> False appendOf st = case st.node of ExprStmt PyExpr {node = Call PyExpr {node = Attribute PyExpr {node = NameRef r'} "append"} _} | r' == r -> True _ -> False inLoop st = case st.node of While {} -> any appendOf (allStatements st) For {} -> any appendOf (allStatements st) _ -> any inLoop (concat (innerBodies st)) early = not (null [() | PyStmt {node = n} <- allStatements body, isEarly n]) isEarly = \case Break -> True Continue -> True Return _ -> True Raise _ -> True _ -> False least = sum . map (choose minimum least) most = sum . map (choose maximum most) choose pick path st | appendOf st = 1 | otherwise = case st.node of If arms e -> pick (path e : [path b | (_, b) <- arms]) Match _ cs -> pick (0 : [path c.body | c <- cs]) _ -> sum (map path (innerBodies st)) -- | How a counting loop counts its steps: by its own name over `range(b)` or `range(a, b)` -- of a literal a (Just the steps so far), or by position over a list or a str that the body -- does not change (Nothing: the loop is made one by position); not at all otherwise. countingSteps :: St -> Text -> PyExpr -> [PyStmt] -> Maybe (Maybe PyExpr) countingSteps now t src body = case src.node of Call PyExpr {node = NameRef "range"} [Argument {keyword = Nothing}] -> Just (Just named) Call PyExpr {node = NameRef "range"} [Argument {keyword = Nothing, value = PyExpr {node = IntLit a}}, Argument {keyword = Nothing}] -> Just (Just PyExpr {span = src.span, node = BinOp "-" named (intLit src.span a)}) StrLit _ | unchanged body t -> Just Nothing _ | Just (root : _) <- viewPath src , Just ty <- Types.typeOf now.moduleTypes {names = now.localTypes} src , case ty of { PList _ -> True; PStr -> True; _ -> False } , all (unchanged body) [t, root] -> Just Nothing _ -> Nothing where named = PyExpr {span = src.span, node = NameRef t} unchanged b n = n `notElem` concatMap changedThrough b && n `notElem` concatMap assignedNames b && not (Set.member n (receivers b)) && not (Set.member n (mayChange b)) -- | A counting loop with what it states: each counter's value before it, then the loop with -- the counters' bounds first in its body (after the loop's own annotations). countingLoop :: [(Text, Integer)] -> PyExpr -> PyExpr -> PyExpr -> [PyStmt] -> [PyStmt] -> [PyStmt] countingLoop counters steps target src body els = [PyStmt {span = at, node = Assign [nm (entry n)] (nm n)} | (n, _) <- counters] <> [PyStmt {span = at, node = For target src (heads <> concat [bounds n c | (n, c) <- counters] <> rest) els}] where at = src.span nm x = PyExpr {span = at, node = NameRef x} entry n = "Verada_Entry_" <> n (heads, rest) = span loopAnnotation body invariant e = PyStmt {span = at, node = ExprStmt PyExpr {span = at, node = Call (nm "invariant") [Argument {keyword = Nothing, value = e}]}} -- (the gain so far, divided by a step's most, is at most the steps: a quotient, which -- no count of steps makes overflow, where a product could) gained n = PyExpr {span = at, node = BinOp "-" (nm n) (nm (entry n))} bounds n c = [ invariant PyExpr {span = at, node = Compare (nm (entry n)) [("<=", nm n)]} , invariant PyExpr {span = at, node = Compare (if c == 1 then gained n else PyExpr {span = at, node = BinOp "//" (gained n) (intLit at c)}) [("<=", steps)]} ] -- | Names a statement list assigns as a whole (parameters may not be). assignedNames :: PyStmt -> [Text] assignedNames st = case st.node of Assign ts _ -> concatMap targetNames ts AnnAssign t _ _ -> targetNames t AugAssign t _ _ -> targetNames t -- (a nested function's `nonlocal` names, which it assigns) FunctionStmt f -> [n | PyStmt {node = Nonlocal ns} <- allStatements f.body, (n, _) <- ns] _ -> concatMap (concatMap assignedNames) (innerBodies st) where targetNames t = case t.node of NameRef n -> [n] TupleLit xs -> concatMap targetNames xs _ -> [] -- | Names whose components a statement list assigns (`p.x = ...`, `a[i] = ...`): a -- parameter so changed is `in out`, as a mutable argument is in Python. componentAssigned :: PyStmt -> [Text] componentAssigned st = case st.node of Assign ts _ -> concatMap root ts -- Python's methods that change their object ExprStmt PyExpr {node = Call PyExpr {node = Attribute p m} _} | m `elem` mutators -> base p AugAssign t _ _ -> root t _ -> concatMap (concatMap componentAssigned) (innerBodies st) where root t = case t.node of Attribute p _ -> base p Subscript p _ -> base p _ -> [] mutators = ["append", "clear", "extend", "insert", "pop", "remove", "sort", "reverse", "add", "discard", "update"] base p = case p.node of NameRef n -> [n] Attribute q _ -> base q Subscript q _ -> base q _ -> [] -- * Statements -- | A statement list, given the names already declared around it. A plain assignment to a -- name not declared yet declares it, in a block over the rest of the list (a constant when -- the rest never assigns it again); a name that is also used after the list must be -- declared before it, with a type (B0402). statements :: Set Text -> [PyStmt] -> D [S.Stmt] statements declared ss0 = sharing ss0 >> go declared ss0 where go _ [] = pure [] go scope (st : rest) = bindsTypes st >> get >>= \now -> case st.node of -- `global x`: the module's x, which the rest assigns (not a local of its own) Global names -> do own <- gets (.moduleVariables) forM_ [(n, sp) | (n, sp) <- names, not (Set.member n own)] \(n, sp) -> reject sp ("`global` names a variable of this module, and `" <> n <> "` is not one: another module's variables are changed through its functions") "not a variable of the module" go (scope <> Set.fromList (map fst names)) rest -- `nonlocal x`: the enclosing function's x, which the rest assigns (Ada's nested -- subprogram assigns it in place) Nonlocal names -> do outer <- gets (.enclosing) forM_ [(n, sp) | (n, sp) <- names, not (Set.member n outer)] \(n, sp) -> reject sp ("`nonlocal` names a local of a function this one is nested in, and `" <> n <> "` is not one") "not an enclosing local" go (scope <> Set.fromList (map fst names)) rest -- a nested `def` (with those right after it, which may call each other): Ada's nested -- subprograms, declared in a block over the rest, seeing the names around them FunctionStmt _ -> do let (defs, after) = span isDef (st : rest) fs = [f | PyStmt {node = FunctionStmt f} <- defs] names = Set.fromList (map (.name) fs) outer <- gets (\s' -> (s'.enclosing, s'.nestedFunctions)) modify' \s' -> s' {enclosing = fst outer <> scope, nestedFunctions = snd outer <> names} items <- concat <$> mapM (\f -> if isTask f then taskItems f else pure <$> functionDecl Public f) fs modify' \s' -> s' {enclosing = fst outer} body <- go (scope <> names) after modify' \s' -> s' {nestedFunctions = snd outer} let decls = [d | Item {node = ItemDecl d} <- items] pure [S.Stmt {span = st.span, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just decls, statements = if null body then [S.Stmt {span = st.span, node = S.SNull}] else body, handlers = [], endLabel = Nothing}}] -- a counting loop, `for ch in s: if ...: n += 1`: an int the body only increases, by -- literals, by at most C each step, is between its value before the loop and that plus -- C for each step so far, which the loop states (a Python programmer has no step count -- to write it with); over a list or a str, the loop is by position, the element bound -- from it, so that the steps are counted (D188) For target@PyExpr {node = NameRef t} src b els | not (any (Text.isPrefixOf "Verada_Entry_") (concatMap invariantNames (fst (span loopAnnotation b)))) , counted@(_ : _) <- countersOf now t b , Just how <- countingSteps now t src b -> case how of Just steps -> go scope (countingLoop counted steps target src b els <> rest) Nothing -> do k <- freshName "Verada_Step_" let at = src.span position = PyExpr {span = at, node = NameRef k} over = PyExpr {span = at, node = Call PyExpr {span = at, node = NameRef "range"} [Argument {keyword = Nothing, value = PyExpr {span = at, node = Call PyExpr {span = at, node = NameRef "len"} [Argument {keyword = Nothing, value = src}]}}]} bind = PyStmt {span = target.span, node = Assign [target] PyExpr {span = at, node = Subscript src [position]}} (heads, body) = span loopAnnotation b go scope (countingLoop counted position position over (heads <> (bind : body)) els <> rest) -- `for row in grid` over a list of lists: each row by its position, `row = grid[k]` -- (a copy where the body only reads it, a row taken out and put back where it changes -- it, D188); the body changes rows, not how many there are, which the loop says For target@PyExpr {node = NameRef rowName} src b els | Just _ <- viewPath src , Just (PList (PList _)) <- Types.typeOf now.moduleTypes {names = now.localTypes} src -> do k <- freshName "Verada_Row_" let at = src.span name' x = PyExpr {span = at, node = NameRef x} pyCall f xs = PyExpr {span = at, node = Call (name' f) [Argument {keyword = Nothing, value = x} | x <- xs]} count = k <> "_Count" rows = pyCall "len" [src] (heads, body) = span loopAnnotation b kept = PyStmt {span = at, node = ExprStmt (pyCall "invariant" [PyExpr {span = at, node = Compare rows [("==", name' count)]}])} bind = PyStmt {span = target.span, node = Assign [target] PyExpr {span = at, node = Subscript src [name' k]}} counted = PyStmt {span = at, node = Assign [name' count] rows} looped grown = PyStmt {span = st.span, node = For (name' k) (pyCall "range" [name' count]) (heads <> (kept : grown <> (bind : body))) els} -- (a body that grows its row by appends: the rows before this one grown by what -- a step appends, the others as they were at the loop's start, which the loop -- states from a ghost copy of the lengths then, so that a row's element after the -- loop proves; Python has no words for it) case rowGrowth rowName body of Just (lo, hi) | hi > 0 -> do snap <- freshName "Verada_Lengths_" grid <- expr src j <- freshName "Verada_Row_At_" let sp = at snapDecl = D.Decl {span = sp, node = D.DObject D.ObjectDecl {names = [ident sp snap], aliased = False, constant = True, subtype = T.InferredType, initial = Just (form sp (E.FormMethod (ident sp "Lengths") []) [grid]), aspects = [E.AspectSpec {span = sp, mark = ident sp "Ghost", classWide = False, value = Nothing}]}} lenAt = pyCall "len" [PyExpr {span = sp, node = Subscript src [name' j]}] was = PyExpr {span = sp, node = Subscript (name' snap) [PyExpr {span = sp, node = BinOp "+" (name' j) (intLit sp 1)}]} before = PyExpr {span = sp, node = Compare (name' j) [("<", name' k)]} plus n = PyExpr {span = sp, node = BinOp "+" was PyExpr {span = sp, node = IfExp before (intLit sp n) (intLit sp 0)}} each | lo == hi = PyExpr {span = sp, node = Compare lenAt [("==", plus hi)]} | otherwise = PyExpr {span = sp, node = Compare (plus lo) [("<=", lenAt), ("<=", plus hi)]} allRows = pyCall "all" [PyExpr {span = sp, node = GeneratorExp each [Comprehension {target = name' j, source = pyCall "range" [name' count], conditions = []}]}] grown = [PyStmt {span = sp, node = ExprStmt (pyCall "invariant" [allRows])}] inner <- go scope [counted, looped grown] more <- go scope rest pure (S.Stmt {span = st.span, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just [snapDecl], statements = inner, handlers = [], endLabel = Nothing}} : more) _ -> go scope (counted : looped [] : rest) -- `grid[i][j] = x` of a list of lists: the row's element replaced Assign [PyExpr {node = Subscript PyExpr {node = Subscript grid [i]} [j], span = ts}] v | not (isSlice i) && not (isSlice j) , Just (PList (PList _)) <- Types.typeOf now.moduleTypes {names = now.localTypes} grid -> do gv <- expr grid ri <- fromOne i rj <- fromOne j x <- expr v more <- go scope rest pure (S.Stmt {span = st.span, node = S.SCall (form ts (E.FormMethod (ident ts "Replace_Element") []) [gv, ri, rj, x])} : more) Assign [PyExpr {node = NameRef n, span = ns}] v | not (Set.member n scope) -> do refs <- gets (.refFields) -- (a list, a dict, a set or a tuple made here has the type Python infers for it, -- as if annotated: `sq = [x * x for x in xs]` is `sq: list[int] = ...`) inferred <- if madeHere v then pyType v else pure Nothing procedures <- gets (.procedureFunctions) let annotation = case (inferred, v.node) of (Just t, _) | containerType t -> Just (typeAnnotation ns t) -- (the result of a function that is a procedure underneath, of its type) (_, Call PyExpr {node = NameRef g} _) | Just r <- Map.lookup g procedures -> Just r _ -> Nothing declareLocal refs scope st ns n annotation (Just v) rest AnnAssign PyExpr {node = NameRef n, span = ns} a v | not (Set.member n scope) -> gets (.refFields) >>= \refs -> declareLocal refs scope st ns n (Just a) v rest Assign [PyExpr {node = TupleLit targets}] PyExpr {node = TupleLit values} | length targets == length values -> do -- `a, b = b, a`: the values first, then the targets n <- gets (.counter) modify' \s -> s {counter = n + length values} let temps = [ident x.span ("Verada_Value_" <> Text.pack (show k)) | (k, x) <- zip [n + 1 ..] values] vs <- mapM expr values ts <- mapM expr targets -- (a name not yet declared is declared by it, `a, b = 1, 2`, as Python binds it: -- a constant unless the rest assigns it again; the rest is in the block) let fresh = [(x, t) | x@PyExpr {node = NameRef t} <- targets, not (Set.member t scope), t /= "_"] isFresh tgt = case tgt.node of NameRef t -> any ((== t) . snd) fresh _ -> False reassigned t = t `elem` concatMap assignedNames rest decls = [D.Decl {span = v.span, node = D.DObject D.ObjectDecl {names = [t], aliased = False, constant = True, subtype = T.InferredType, initial = Just v, aspects = []}} | (t, v) <- zip temps vs] binding = [D.Decl {span = x.span, node = D.DObject D.ObjectDecl {names = [ident x.span y], aliased = False, constant = not (reassigned y), subtype = T.InferredType, initial = Just E.Expr {span = t.span, node = E.ENameRef t}, aspects = []}} | (x@PyExpr {node = NameRef y}, t) <- zip targets temps, isFresh x] assigns = [S.Stmt {span = st.span, node = S.SAssign S.Assignment {target = tgt, value = E.Expr {span = t.span, node = E.ENameRef t}}} | (tgt, t, x) <- zip3 ts temps targets, not (isFresh x), not (isUnderscore x)] isUnderscore x = case x.node of NameRef "_" -> True _ -> False if null fresh then do more <- go scope rest pure (S.Stmt {span = st.span, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just decls, statements = assigns, handlers = [], endLabel = Nothing}} : more) else do more <- go (Set.union scope (Set.fromList (map snd fresh))) rest pure [S.Stmt {span = st.span, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just (decls <> binding), statements = case assigns <> more of { [] -> [S.Stmt {span = st.span, node = S.SNull}]; ss' -> ss' }, handlers = [], endLabel = Nothing}}] -- `q, r = div_mod(a, b)`: the tuple once, then each target its item Assign [PyExpr {node = TupleLit targets}] v | all isName targets -> do n <- gets (.counter) modify' \s -> s {counter = n + 1} value <- expr v let temp = ident v.span ("Verada_Value_" <> Text.pack (show (n + 1))) -- (each item at its target's place: forms are told apart by their places) item sp k = form sp E.FormItem [E.Expr {span = v.span, node = E.ENameRef temp}, E.Expr {span = sp, node = E.EInteger k}] names = [(x.span, t) | x@PyExpr {node = NameRef t} <- targets] fresh = [(sp, t, k) | ((sp, t), k) <- zip names [0 ..], not (Set.member t scope)] existing = [(sp, t, k) | ((sp, t), k) <- zip names [0 ..], Set.member t scope] reassigned t = t `elem` concatMap assignedNames rest decls = D.Decl {span = v.span, node = D.DObject D.ObjectDecl {names = [temp], aliased = False, constant = True, subtype = T.InferredType, initial = Just value, aspects = []}} : [D.Decl {span = sp, node = D.DObject D.ObjectDecl {names = [ident sp t], aliased = False, constant = not (reassigned t), subtype = T.InferredType, initial = Just (item sp k), aspects = []}} | (sp, t, k) <- fresh] stores = [S.Stmt {span = st.span, node = S.SAssign S.Assignment {target = nameE sp t, value = item sp k}} | (sp, t, k) <- existing] more <- go (Set.union scope (Set.fromList [t | (_, t, _) <- fresh])) rest pure [S.Stmt {span = st.span, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just decls, statements = case stores <> more of { [] -> [S.Stmt {span = st.span, node = S.SNull}]; ss -> ss }, handlers = [], endLabel = Nothing}}] -- `g.nodes[i].visited = True`: a component of an element (a list's or a dict's, which -- are not variables in Ada) changed through a copy of the element, put back _ | Just (container, index, rebuild) <- elementComponent st -> do k <- gets (.counter) modify' \s' -> s' {counter = k + 1} let copyName = "Verada_Element_" <> Text.pack (show (k + 1)) named sp = PyExpr {span = sp, node = NameRef copyName} element sp = PyExpr {span = sp, node = Subscript container [index]} taken = PyStmt {span = st.span, node = Assign [named index.span] PyExpr {span = index.span, node = Call PyExpr {span = index.span, node = NameRef "copy"} [Argument {keyword = Nothing, value = element container.span}]}} changed = rebuild (named container.span) -- (at the statement: forms are told apart by their places, and this one stores) putBack = PyStmt {span = st.span, node = Assign [element st.span] (named st.span)} go scope (taken : changed : putBack : rest) _ -> do here <- statement scope st more <- go scope rest pure (here <> more) isName x = case x.node of NameRef _ -> True _ -> False immutable a = case a.node of NameRef t -> t `elem` ["int", "float", "bool", "str"] _ -> False isDef x = case x.node of FunctionStmt _ -> True _ -> False declareLocal refs scope st ns n annotation value rest -- design D: a name bound to a path and then changed is a view of it, as in Python -- (not of a reference, which the name copies, EU2) | Just v <- value , Just path <- viewPath v -- (an `int`, a `float`, a `bool` or a `str` is a value, never changed through a name) , not (maybe False immutable annotation) , maybe True (`Set.notMember` refs) (listToMaybe (reverse path)) -- (one passed to a call may be changed by it; unless it is bound again, then a copy) , n `elem` concatMap changedThrough rest || Set.member n (receivers rest) || (Set.member n (mayChange rest) && n `notElem` concatMap assignedNames rest) = do -- (a view cannot be bound again, and must not outlive its object: Python's name -- would keep the old one) let rebound = [(ns, "`" <> n <> "` names the object of `" <> pathText path <> "` (it is changed through it, as Python shares it), and so is not bound again; use a new name", "view bound again") | n `elem` concatMap assignedNames rest] outlived = [(v.span, "`" <> n <> "` names the object of `" <> pathText path <> "`, which is replaced later (`" <> pathText q <> " = ...`): Python's `" <> n <> "` would keep the old object. Write `" <> n <> " = copy(" <> pathText path <> ")`, or change it through `" <> pathText path <> "`", "view outlived") | q <- take 1 [p | p <- concatMap assignedPaths rest, p `isPrefixOf` path]] conflicts = rebound <> outlived subtype <- traverse (\a -> annotated a <$> typeExpr a) annotation renamed <- expr v binding <- if n `elem` concatMap changedThrough rest then do forM_ conflicts \(sp, message, why) -> reject sp message why pure D.ObjectRenaming {name = ident ns n, subtype, renamed, aspects = [], viewConflicts = Nothing} else pure D.ObjectRenaming {name = ident ns n, subtype, renamed, aspects = [], viewConflicts = Just conflicts} body <- go (Set.insert n scope) rest let decl = D.Decl {span = ns, node = D.DObjectRenaming binding} pure [S.Stmt {span = st.span, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just [decl], statements = if null body then [S.Stmt {span = st.span, node = S.SNull}] else body, handlers = [], endLabel = Nothing}}] -- design D for an element (`n = nodes[i]`, of a list or a dict): the element taken -- out and put back where the view ends (and before each `return`, `break` and -- `continue` that leaves it), so the changes reach it as Python's shared object does | Just v@PyExpr {node = Subscript container [index]} <- value -- (a slice is a new list or string, Python's, never a view of the old one) , not (isSlice index) , Just cpath <- viewPath container , not (putsBack cpath n rest) , n `elem` concatMap changedThrough rest || Set.member n (receivers rest) || (Set.member n (mayChange rest) && n `notElem` concatMap assignedNames rest) = do -- (a row of a list of lists: moved out into the name and back, Take and Put_Back, -- D188) rowType <- pyType container <&> \case Just (PList r@(PList _)) -> Just r _ -> Nothing when (n `elem` concatMap assignedNames rest) (reject ns ("`" <> n <> "` names the element `" <> pathText cpath <> "[...]` (it is changed through it, as Python shares it), and so is not bound again; use a new name") "view bound again") when (any (mentionsPath cpath) rest) (reject v.span ("`" <> n <> "` names an element of `" <> pathText cpath <> "`, which is used again while `" <> n <> "` is: Vibe puts the element back where `" <> n <> "`'s statements end (Python changes it at once), so change it through `" <> n <> "` alone, or write `" <> n <> " = copy(...)` and store it back yourself") "element view") when (not (null [() | PyStmt {node = Raise _} <- allStatements rest])) (reject v.span ("`" <> n <> "` names an element of `" <> pathText cpath <> "`, and a `raise` would leave before it is put back: change the element before raising, or write `" <> n <> " = copy(...)`") "element view") k <- gets (.counter) modify' \s' -> s' {counter = k + 1} -- (the index fixed when the view is made: itself when a literal or a name the view's -- statements do not assign) let indexName = "Verada_Index_" <> Text.pack (show (k + 1)) fixed = case index.node of IntLit _ -> True StrLit _ -> True NameRef i -> i `notElem` concatMap assignedNames rest _ -> False at sp = if fixed then index else PyExpr {span = sp, node = NameRef indexName} indexStmts = [PyStmt {span = index.span, node = Assign [at index.span] index} | not fixed] element = PyExpr {span = v.span, node = Subscript container [at index.span]} copied = PyExpr {span = v.span, node = Call PyExpr {span = v.span, node = NameRef "copy"} [Argument {keyword = Nothing, value = element}]} bindStmt = PyStmt {span = st.span, node = maybe (Assign [PyExpr {span = ns, node = NameRef n}] copied) (\a -> AnnAssign PyExpr {span = ns, node = NameRef n} a (Just copied)) annotation} -- (at the name: forms are told apart by their places, and this one stores) -- (a row's position from 1, Nested_Vectors') rowAt sp = PyExpr {span = sp, node = BinOp "+" (at sp) (intLit sp 1)} rowCall sp m = PyStmt {span = sp, node = ExprStmt PyExpr {span = sp, node = Call PyExpr {span = sp, node = Attribute container m} [Argument {keyword = Nothing, value = rowAt sp}, Argument {keyword = Nothing, value = PyExpr {span = ns, node = NameRef n}}]}} (bound, putBack) = case rowType of Just r -> ( [PyStmt {span = st.span, node = AnnAssign PyExpr {span = ns, node = NameRef n} (typeAnnotation ns r) (Just PyExpr {span = v.span, node = ListLit []})}, rowCall v.span "Take"] , rowCall ns "Put_Back" ) Nothing -> ( [bindStmt] , PyStmt {span = st.span, node = Assign [PyExpr {span = ns, node = Subscript container [at index.span]}] PyExpr {span = ns, node = NameRef n}} ) ends = case reverse rest of PyStmt {node = Return _} : _ -> [] _ -> [putBack] go scope (indexStmts <> bound <> putBackBefore putBack rest <> ends) | otherwise = do -- (a name bound to another place's value, an element, and then changed: Python would -- share it) -- (one put back by hand, `nodes[k] = n`, is a copy meant) let elementPutBack v = case v.node of Subscript c [_] | Just cpath <- viewPath c -> putsBack cpath n rest _ -> False case value of Just v | isPlace v, n `elem` concatMap changedThrough rest, not (elementPutBack v), maybe True (`Set.notMember` refs) (listToMaybe . reverse =<< viewPath v) -> reject v.span ("`" <> n <> "` is a copy of this value in Vibe, where Python would share it: changing `" <> n <> "` would not change the original. Write `" <> n <> " = copy(...)` if a copy is meant, or change the original itself") "shared in Python" _ -> pure () classesNow <- gets (.classes) -- (`s = Stack()`, a class's own default value: an object initialised by default, as a -- limited class's must be, EU7) let defaulted = case value of Just PyExpr {node = Call PyExpr {node = NameRef c} []} | Map.member c classesNow || maybe False (isUpper . fst) (Text.uncons c) -> Just c _ -> Nothing subtype <- case (annotation, value) of (Just a, _) -> annotated a <$> typeExpr a (Nothing, Just v) | Just c <- defaulted -> pure (indication v.span (nameE v.span c)) -- (a float of literals alone is Python's float, a double: Ada would make it a Float) (Nothing, Just v) | floatLiteral v -> pure (indication v.span (nameE v.span "Long_Float")) _ -> pure T.InferredType let isList = case annotation of Just PyExpr {node = Subscript PyExpr {node = NameRef c} _} -> c `elem` ["list", "dict", "set"] _ -> False -- (an object a method is called on, or that is passed to a call, may be changed by -- it, as Python's objects may) reassigned = n `elem` concatMap assignedNames rest || Set.member n (throughViews rest (Set.fromList (concatMap componentAssigned rest))) || Set.member n (mayChange rest) -- a list, dict or set is made empty and filled: it is limited, and changed by its -- methods procedures <- gets (.procedureFunctions) let calleeIn ps callee = case callee of NameRef g -> Map.member g ps _ -> False (initial, filling) <- case (isList, value) of _ | isJust defaulted -> pure (Nothing, []) (True, Just v) -> listFilling scope ns n v (False, Just PyExpr {node = ListLit [], span = vs}) -> (Nothing, []) <$ reject vs ("give the empty list its type: `" <> n <> ": list[int] = []`") "no element type" -- `b: Box[int] = Box(value=3)` (or `m.Box`): a value of the instance's class (False, Just v@PyExpr {node = Call c args}) | Just a@PyExpr {node = Subscript c' _} <- annotation, Just cn <- classPath c, Just cn == classPath c', all (isJust . (.keyword)) args -> do ty <- typeExpr a vs <- mapM (constructValue . (.value)) args pure (Just (form v.span (E.FormConstruct [ident x.value.span (fromMaybe "" x.keyword) | x <- args]) (ty : vs)), []) -- `x: T = o.m(...)`: declared, then assigned (a method that changes its object is a -- procedure underneath, LN11) (False, Just v@PyExpr {node = Call PyExpr {node = callee} _}) | isJust annotation, procedureLike callee || calleeIn procedures callee -> do value' <- expr v pure (Nothing, [S.Stmt {span = v.span, node = S.SAssign S.Assignment {target = nameE ns n, value = value'}}]) _ -> (,[]) <$> traverse expr value let constant = isJust initial && not reassigned && not isList body <- go (Set.insert n scope) rest -- (the declaration at its name, the block at the statement: a comment before the -- statement goes with one of them) -- (the value a `return` keeps while a `finally` runs is assigned before it is read, on -- the paths that read it, which proof shows: flow analysis cannot) let relaxed = [E.AspectSpec {span = ns, mark = ident ns "Relaxed_Initialization", classWide = False, value = Nothing} | "Verada_Return_" `Text.isPrefixOf` n, isNothing value] decl = D.Decl {span = ns, node = D.DObject D.ObjectDecl {names = [ident ns n], aliased = False, constant, subtype, initial, aspects = relaxed}} statements' = filling <> body pure [S.Stmt {span = st.span, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just [decl], statements = if null statements' then [S.Stmt {span = st.span, node = S.SNull}] else statements', handlers = [], endLabel = Nothing}}] -- `xs: list[T] = [a, b]` appends each element, `= [e for x in s if c]` each value the -- loop gives; another value (a function's list) initialises it listFilling scope ns n v = case v.node of -- `[x] * k` (and `k * [x]`): x appended k times, as `[x for _ in range(k)]`; of a -- list of lists Python's rows would be one list, shared, which Vibe does not make BinOp "*" l r | Just (x, k) <- repeated l r -> do nested <- pyType PyExpr {span = ns, node = NameRef n} <&> \case Just (PList (PList _)) -> True _ -> False if nested then (Nothing, []) <$ reject v.span "`[row] * k` makes a list whose rows are one list, shared (a change of one is a change of all): write `[[...] for _ in range(k)]`, a row of its own for each" "shared rows" else if not (once x) then (Nothing, []) <$ reject x.span "`[x] * k` computes x once, in Python: name it first, `v = ...`, and write `[v] * k`" "computed once" else do counter <- freshName "Verada_Count_" listFilling scope ns n PyExpr {span = v.span, node = ListComp x [Comprehension {target = PyExpr {span = v.span, node = NameRef counter}, source = PyExpr {span = k.span, node = Call PyExpr {span = k.span, node = NameRef "range"} [Argument {keyword = Nothing, value = k}]}, conditions = []}]} ListLit xs -> do -- (a starred element, `[*xs, 4]`: each of its elements appended in turn) added <- forM xs \x -> case x.node of Starred source -> do element <- freshName "Verada_Element_" iteratorFor PyExpr {span = x.span, node = NameRef element} source >>= \case Just it -> pure [S.Stmt {span = x.span, node = S.SLoop S.LoopStmt {label = Nothing, scheme = S.ForLoop it, statements = [appendTo ns n (nameE x.span element)], endLabel = Nothing}}] Nothing -> pure [] _ -> rowAppended scope ns n x pure (Nothing, concat added) -- `{k: v}` includes each pair, `{a, b}` (and `set()`) each value DictLit kvs -> do pairs <- forM kvs \(k, x) -> (,) <$> expr k <*> expr x pure (Nothing, [S.Stmt {span = k.span, node = S.SAssign S.Assignment {target = form k.span E.FormItem [nameE ns n, k], value = x}} | (k, x) <- pairs]) SetLit xs -> do vs <- mapM expr xs pure (Nothing, [S.Stmt {span = x.span, node = S.SCall (form x.span (E.FormMethod (ident x.span "add") []) [nameE ns n, x])} | x <- vs]) Call PyExpr {node = NameRef c} [] | c `elem` ["set", "dict", "list"] -> pure (Nothing, []) -- `[e for x in xs for y in ys if c]`, `{k: v for ...}`, `{e for ...}`: the loops -- (one for each `for`, nested in order, each with its `if`s), adding each value ListComp element cs -> do -- (rows each `[x] * k`, of a list of lists: the loop says each row so far has k -- elements, which a later `grid[i][j]` needs) nested <- pyType PyExpr {span = ns, node = NameRef n} <&> \case Just (PList (PList _)) -> True _ -> False rowsOf <- case element.node of BinOp "*" l r | nested , Just (_, k) <- repeated l r , steadyOperand k -> do j <- freshName "Verada_Row_At_" let at = element.span nm x = PyExpr {span = at, node = NameRef x} lenOf x = PyExpr {span = at, node = Call (nm "len") [Argument {keyword = Nothing, value = x}]} each = PyExpr {span = at, node = Compare (lenOf PyExpr {span = at, node = Subscript (nm n) [nm j]}) [("==", k)]} over = PyExpr {span = at, node = Call (nm "range") [Argument {keyword = Nothing, value = lenOf (nm n)}]} Just <$> expr PyExpr {span = at, node = Call (nm "all") [Argument {keyword = Nothing, value = PyExpr {span = at, node = GeneratorExp each [Comprehension {target = nm j, source = over, conditions = []}]}}]} _ -> pure Nothing comprehensionFilling' rowsOf ns n True v.span cs \_ -> rowAppended scope ns n element DictComp key value cs -> comprehensionFilling ns n False v.span cs \sp -> do k <- expr key x <- expr value pure [S.Stmt {span = sp, node = S.SAssign S.Assignment {target = form key.span E.FormItem [nameE ns n, k], value = x}}] SetComp element cs -> comprehensionFilling ns n False v.span cs \_ -> do x <- expr element pure [S.Stmt {span = x.span, node = S.SCall (form x.span (E.FormMethod (ident x.span "add") []) [nameE ns n, x])}] -- `ys: list[T] = xs.copy()`: a copy made into the new list (it is limited) Call PyExpr {node = Attribute src "copy"} [] -> do from <- expr src pure (Nothing, [S.Stmt {span = v.span, node = S.SCall (form v.span (E.FormMethod (ident v.span "Copy") []) [from, nameE ns n])}]) _ -> do _ <- pure scope (\x -> (Just x, [])) <$> expr v appendTo ns n x = S.Stmt {span = x.span, node = S.SCall (form x.span (E.FormMethod (ident x.span "Append") []) [nameE ns n, x])} -- (x appended to n; to a list of lists, a row that is not a display made first into a -- local of the rows' type, `[[0] * 3 for _ in range(2)]`, D188) rowAppended scope ns n x = pyType PyExpr {span = ns, node = NameRef n} >>= \case Just (PList r@(PList _)) | not (isListLit x) -> do row <- freshName "Verada_Row_" let named = PyExpr {span = x.span, node = NameRef row} statements scope [ PyStmt {span = x.span, node = AnnAssign named (typeAnnotation x.span r) (Just x)} , PyStmt {span = x.span, node = ExprStmt PyExpr {span = x.span, node = Call PyExpr {span = x.span, node = Attribute PyExpr {span = ns, node = NameRef n} "append"} [Argument {keyword = Nothing, value = named}]}} ] _ -> (\e -> [appendTo ns n e]) <$> expr x repeated l r = case (l.node, r.node) of (ListLit [x], _) | notStarred x -> Just (x, r) (_, ListLit [x]) | notStarred x -> Just (x, l) _ -> Nothing notStarred x = case x.node of Starred _ -> False _ -> True -- (a value the same each time it is computed: Python computes it once) once x = case x.node of StrLit _ -> True BoolLit _ -> True ListLit _ -> True _ -> steadyOperand x isListLit x = case x.node of ListLit _ -> True _ -> False -- (one `for` over a range, or over a named container by position: the container holds -- at most one value for each step so far, which bounds its length, so that each addition -- is proved to fit; exactly one for a list without a filter) comprehensionFilling = comprehensionFilling' Nothing comprehensionFilling' rowsOf ns n isList sp cs adding = case cs of -- (over a range with a step: the stepped loop, which counts its steps) [c] | NameRef x <- c.target.node , Call PyExpr {node = NameRef "range"} [Argument {keyword = Nothing, value = a}, Argument {keyword = Nothing, value = b}, Argument {keyword = Nothing, value = by}] <- c.source.node -> do conditions <- mapM expr c.conditions inner <- adding sp looped <- steppedFor sp c.target.span x c.source.span a b by (\(_, counter) -> [bound conditions counter]) (orNullAt sp (guard conditions inner)) pure (Nothing, looped) [c] | NameRef x <- c.target.node , Call PyExpr {node = NameRef "range"} args <- c.source.node -> rangeDomain c.source.span args >>= \case Just d@(E.InRange (E.DiscreteBounds r)) -> do conditions <- mapM expr c.conditions inner <- adding sp let steps = binary sp E.OpSub (nameE c.target.span x) (paren r.low) pure (Nothing, [counting d (ident c.target.span x) (bound conditions steps) [] (guard conditions inner)]) _ -> pure (Nothing, []) | NameRef x <- c.target.node , isPlace c.source -> do k <- gets (.counter) modify' \st -> st {counter = k + 1} source <- expr c.source conditions <- mapM expr c.conditions inner <- adding sp let position = ident c.source.span ("Verada_Position_" <> Text.pack (show (k + 1))) at' = E.Expr {span = c.source.span, node = E.ENameRef position} lastPosition = binary sp E.OpSub (form c.source.span E.FormLength [source]) E.Expr {span = sp, node = E.EInteger 1} domain = E.InRange (E.DiscreteBounds E.RangeExpr {span = sp, low = E.Expr {span = sp, node = E.EInteger 0}, high = lastPosition}) element = D.Decl {span = c.target.span, node = D.DObject D.ObjectDecl {names = [ident c.target.span x], aliased = False, constant = True, subtype = T.InferredType, initial = Just (form c.target.span (E.FormMethod (ident c.target.span "Verada_Element_At") []) [source, at']), aspects = []}} pure (Nothing, [counting domain position (bound conditions at') [element] (guard conditions inner)]) _ -> do body <- comprehensionLoops sp cs adding pure (Nothing, body) where bound conditions steps = S.Stmt {span = sp, node = S.SPragma E.Pragma {span = sp, name = ident sp "Loop_Invariant", arguments = [E.Argument {span = sp, formal = Nothing, value = E.ArgExpr (maybe id (\rows c -> binary sp E.OpAndThen c (paren rows)) rowsOf (binary sp (if isList && null conditions then E.OpEq else E.OpLe) (form sp E.FormLength [nameE ns n]) steps)), reference = Nothing}]}} orNullAt at = \case [] -> [S.Stmt {span = at, node = S.SNull}] ss -> ss guard conditions inner = case conditions of [] -> inner k : ks -> [S.Stmt {span = sp, node = S.SIf S.IfStmt {condition = foldl (binary sp E.OpAndThen) k ks, thenPart = if null inner then [S.Stmt {span = sp, node = S.SNull}] else inner, elsifs = [], elsePart = Nothing}}] counting domain parameter invariant decls body = let inner = if null decls then body else [S.Stmt {span = sp, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just decls, statements = if null body then [S.Stmt {span = sp, node = S.SNull}] else body, handlers = [], endLabel = Nothing}}] in S.Stmt {span = sp, node = S.SLoop S.LoopStmt {label = Nothing, scheme = S.ForLoop E.Iterator {parameter, subtype = Nothing, reverse = False, domain, filter = Nothing, whileCondition = Nothing, alongside = []}, statements = invariant : inner, endLabel = Nothing}} -- | A comprehension's loops: for each clause in order a `for` over its source (as a loop's -- `for` takes it: ranges, containers, `enumerate`, `zip`, a dict's `items()`), its `if`s -- around what is inside, and innermost what each value adds. comprehensionLoops :: Span -> [Comprehension] -> (Span -> D [S.Stmt]) -> D [S.Stmt] comprehensionLoops sp cs adding = case cs of [] -> adding sp c : rest -> iteratorFor c.target c.source >>= \case Nothing -> pure [] Just it -> do inner <- comprehensionLoops sp rest adding conditions <- mapM expr c.conditions let guarded = case conditions of [] -> inner k : ks -> [S.Stmt {span = sp, node = S.SIf S.IfStmt {condition = foldl (binary sp E.OpAndThen) k ks, thenPart = orNull inner, elsifs = [], elsePart = Nothing}}] pure [S.Stmt {span = sp, node = S.SLoop S.LoopStmt {label = Nothing, scheme = S.ForLoop it, statements = orNull guarded, endLabel = Nothing}}] where orNull = \case [] -> [S.Stmt {span = sp, node = S.SNull}] ss -> ss statement :: Set Text -> PyStmt -> D [S.Stmt] statement scope st = case st.node of Pass -> one S.SNull Break -> one (S.SExit S.ExitStmt {loopName = Nothing, condition = Nothing}) -- (a loop's own `continue`s are its body's structure, `withoutContinue`; one left is outside -- any loop) Continue -> [] <$ reject st.span "`continue` is taken inside a loop" "not in a loop" Return v -> do nested <- gets (.nestedFunctions) case v of Just PyExpr {node = NameRef n, span = sp} | Set.member n nested -> reject sp ("`" <> n <> "` is a nested function, and Vibe has no closures that outlive the function they are in: call it here, or define it at the module's level and give it what it reads as parameters") "closure escapes" _ -> pure () value <- traverse expr v one (S.SReturn value) -- (`assert c, message`: the message is Ada's second argument, as `pragma Assert (C, M)`) Assert c m -> do v <- expr c message <- traverse messageOf m one (pragma "Assert" (v : maybe [] pure message)) Assign [t] v -> do target <- expr t value <- expr v one (S.SAssign S.Assignment {target, value}) AnnAssign t _ (Just v) -> do target <- expr t value <- expr v one (S.SAssign S.Assignment {target, value}) AugAssign t o v -> do target <- expr t value <- binaryOp st.span o t v one (S.SAssign S.Assignment {target, value}) If arms e -> case arms of (c, b) : elifs -> do condition <- expr c thenPart <- statements scope b elifParts <- forM elifs \(c', b') -> do cond <- expr c' ss <- statements scope b' pure S.ElsifPart {span = c'.span, condition = cond, statements = ss} elsePart <- if null e then pure Nothing else Just <$> statements scope e one (S.SIf S.IfStmt {condition, thenPart = orNull thenPart, elsifs = [S.ElsifPart {span = p.span, condition = p.condition, statements = orNull p.statements} | p <- elifParts], elsePart = orNull <$> elsePart}) [] -> pure [] While PyExpr {node = BoolLit True} b _ -> loop S.Forever b While c b _ -> do condition <- expr c loop (S.WhileLoop condition) b -- `for i in range(a, b, s)`: a count of steps, i each step's value (Python's values: from -- a while below b, or above it for a negative step) For PyExpr {node = NameRef i, span = isp} PyExpr {node = Call PyExpr {node = NameRef "range"} [Argument {keyword = Nothing, value = a}, Argument {keyword = Nothing, value = b'}, Argument {keyword = Nothing, value = by}], span = rs} b _ -> steppedLoop isp i rs a b' by b -- `for a, b in pairs` over a list of tuples (not `zip`, `enumerate` or `d.items()`): each -- tuple in turn, unpacked For target@PyExpr {node = TupleLit _} src b els | not (pairedSource src) -> do element <- freshName "Verada_Item_" let (heads, rest) = span isLoopPragma b unpack = PyStmt {span = target.span, node = Assign [target] PyExpr {span = target.span, node = NameRef element}} statement scope PyStmt {span = st.span, node = For PyExpr {span = target.span, node = NameRef element} src (heads <> (unpack : rest)) els} For target src b _ -> plainFor target src b ExprStmt e -> callStatement e -- a match on classes (a union's dataclasses): a membership test for each, binding the -- fields its pattern names -- `del p`: frees what p owns (the `Free` of its access type) Del targets -> do never <- gets (.neverNull) fmap concat . forM targets $ \t -> case t.node of _ | Just n <- ownerName t, Set.member n never -> [] <$ reject t.span ("`" <> n <> "` is an `Owned[T]`, never null, and `del` leaves an owner null: declare it `Owned[T] | None` to free what it owns with `del`") "never null" _ | Just _ <- ownerName t -> do p <- expr t one (S.SCall (call st.span ["Free"] [p])) -- `del xs[i]`, `del d[k]`: the element taken out of the list or the dict Subscript c [i] -> do container <- expr c index <- expr i one (S.SCall (form t.span (E.FormMethod (ident t.span "Delete") []) [container, index])) _ -> [] <$ reject t.span "`del` frees what an owner (`Owned[T] | None`) holds: name the owner, `del p` or `del node.next`" "not an owner" -- `raise E`, `raise E()`, `raise E("why")`, and a bare `raise` again in a handler Raise v -> case v of Nothing -> one (S.SRaise S.RaiseStmt {exception = Nothing, message = Nothing}) Just PyExpr {node = Call e []} -> raising e Nothing Just PyExpr {node = Call e [Argument {keyword = Nothing, value = m}]} -> raising e (Just m) Just e -> raising e Nothing -- `try:` with `except` clauses: a block with handlers (`except Exception` and a bare -- `except` take any) -- (an `else` and a `finally` are written as other statements first, `pythonForms`) Try body clauses _ _ -> do ss <- statements scope body handlers <- forM clauses \c -> do choices <- case c.exceptions of Nothing -> pure [E.ChoiceOthers c.span] Just PyExpr {node = NameRef "Exception", span = sp} -> pure [E.ChoiceOthers sp] Just PyExpr {node = TupleLit es} -> concat <$> mapM handled es Just e -> handled e hs <- statements scope c.body when (isJust c.name) (modify' \state -> state {bindsOccurrences = True}) pure S.Handler {span = c.span, occurrence = ident c.span <$> c.name, choices, statements = orNull hs} one (S.SBlock S.BlockStmt {label = Nothing, declarations = Nothing, statements = orNull ss, handlers, endLabel = Nothing}) Match subject@PyExpr {node = NameRef _} cases | any isClassPattern cases -> do selector <- expr subject arms <- forM cases \c -> do body <- statements scope c.body guarding <- traverse expr c.guard case c.pattern.node of NameRef "_" -> pure (guarding, body) Call PyExpr {node = NameRef cls, span = cs} args -> do fieldsOf <- gets (Map.findWithDefault [] cls . (.fieldNames)) let named = [(k, v) | Argument {keyword = Just k, value = v} <- args] <> zip fieldsOf [v | Argument {keyword = Nothing, value = v} <- args] view = E.Expr {span = cs, node = E.EApply E.Apply {prefix = nameE cs cls, arguments = [E.Argument {span = selector.span, formal = Nothing, value = E.ArgExpr selector, reference = Nothing}], bracketed = Nothing}} field f = E.Expr {span = cs, node = E.ESelected E.Selected {prefix = view, selector = E.SelectIdentifier (ident cs f)}} kinds <- gets (.classes) binds <- fmap catMaybes . forM named $ \(f, v) -> case v.node of NameRef "_" -> pure Nothing NameRef x -> pure (Just (Left D.Decl {span = v.span, node = D.DObject D.ObjectDecl {names = [ident v.span x], aliased = False, constant = True, subtype = T.InferredType, initial = Just (field f), aspects = []}})) -- (a value in a class pattern, `Point(x=0)`: the field must equal it, Python's -- value pattern) _ | valuePattern v -> do x <- expr v comparison v.span "==" (field f) x <&> Just . Right _ -> Nothing <$ reject v.span "a class pattern takes a name to bind (`Circle(r=r)`) or a literal value to match (`Circle(r=0)`) for each field: bind a name and test it in the case's guard (`case Circle(r=r) if r > 0:`)" "neither a name nor a literal" let -- (a plain dataclass, not tagged: its one class always matches) tagged = Map.lookup cls kinds /= Just RecordClass isClass = if tagged then E.Expr {span = cs, node = E.EMembership E.Membership {negated = False, operand = selector, choices = [E.MemberExpr (attribute cs (nameE cs cls) "Class")]}} else nameE cs "True" valueTests = [t | Right t <- binds] -- (a guard reads the fields its pattern binds: each read where it is tested) bound = [(n, v) | Left D.Decl {node = D.DObject D.ObjectDecl {names = [n], initial = Just v}} <- binds] matched = foldl (\a b -> binary cs E.OpAndThen a (paren b)) isClass valueTests test = case guarding of Just g -> binary cs E.OpAndThen matched (paren (foldr (\(n, v) -> substituteName n v) g bound)) Nothing -> matched decls = [d | Left d <- binds] inner = if null decls then body else [S.Stmt {span = c.pattern.span, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just decls, statements = orNull body, handlers = [], endLabel = Nothing}}] pure (Just test, inner) _ -> (Nothing, []) <$ reject c.pattern.span "a match on classes takes `C(field=name)` and `_` patterns" "pattern" let tests = [(t, b) | (Just t, b) <- arms] others = [b | (Nothing, b) <- arms] case tests of (t, b) : rest -> one (S.SIf S.IfStmt {condition = t, thenPart = orNull b, elsifs = [S.ElsifPart {span = t.span, condition = t', statements = orNull b'} | (t', b') <- rest], elsePart = orNull <$> listToMaybe others}) [] -> pure (concat others) -- with a guard (`case p if c:`): each case's test in turn, its pattern's and then its -- guard's, up to one that always matches Match subject cases | any (isJust . (.guard)) cases -> do selector <- expr subject arms <- forM cases \c -> do choices <- patternChoices c.pattern guarding0 <- traverse expr c.guard ss0 <- statements scope c.body -- (a capture pattern, `case k if k < 0:`, binds the subject: the guard reads it, and -- the body has it as a constant) let guarding = case capture c.pattern of Just (k, ks) -> substituteName (ident ks k) selector <$> guarding0 Nothing -> guarding0 ss = captured selector c.pattern ss0 member = case [x | E.ChoiceExpr x <- choices] of xs | length xs == length choices -> Just E.Expr {span = c.pattern.span, node = E.EMembership E.Membership {negated = False, operand = selector, choices = map E.MemberExpr xs}} _ -> Nothing test = case (member, guarding) of (Just m, Just g) -> Just (binary c.pattern.span E.OpAndThen m (paren g)) (Just m, Nothing) -> Just m (Nothing, g) -> g pure (test, ss) let (tested, later) = span (isJust . fst) arms case ([(t, b) | (Just t, b) <- tested], listToMaybe [b | (Nothing, b) <- later]) of ((t, b) : more, fallback) -> one (S.SIf S.IfStmt {condition = t, thenPart = orNull b, elsifs = [S.ElsifPart {span = t'.span, condition = t', statements = orNull b'} | (t', b') <- more], elsePart = orNull <$> fallback}) ([], fallback) -> pure (fromMaybe [] fallback) Match subject cases -> do selector <- expr subject alternatives <- forM cases \c -> do choices <- patternChoices c.pattern ss <- captured selector c.pattern <$> statements scope c.body pure S.CaseAlternative {span = c.pattern.span, choices, statements = orNull ss} one (S.SCase S.CaseStmt {selector, alternatives}) -- (`async def`, `async with`: why Vibe excludes it, vibe-syntax section 8) ExcludedStmt reason _ -> [] <$ reject st.span reason "not in Vibe" _ -> [] <$ reject st.span "Vibe does not take this statement" "statement" where one n = pure [S.Stmt {span = st.span, node = n}] plainFor target src b = do -- (`for _ in ...`: a name Ada can spell) let named = case target.node of NameRef "_" -> PyExpr {span = target.span, node = NameRef "Verada_Unused"} _ -> target iteratorFor named src >>= \case Just it -> loop (S.ForLoop it) b Nothing -> pure [] -- (a name, or a field of one: what may be an owner) ownerName t = case t.node of NameRef n -> Just n Attribute p f | isJust (ownerName p) -> Just f _ -> Nothing orNull = \case [] -> [S.Stmt {span = st.span, node = S.SNull}] ss -> ss steppedLoop isp i rs a stop by b = do let (heads, rest) = span isLoopPragma b prag <- concat <$> mapM (statement scope) heads body <- statements (Set.insert i scope) (withoutContinue rest) steppedFor st.span isp i rs a stop by (const prag) (orNull body) loop scheme b = do let (heads, rest) = span isLoopPragma b prag <- concat <$> mapM (statement scope) heads body <- statements scope (withoutContinue rest) one (S.SLoop S.LoopStmt {label = Nothing, scheme, statements = orNull (prag <> body), endLabel = Nothing}) -- (an exception handled, with those that derive from it, Python's hierarchy) handled e = case e.node of NameRef n -> do parents <- gets (.exceptionParents) let builtinParents = Map.map fst builtinExceptions allParents = Map.union parents builtinParents below x = [d | (d, p) <- Map.toList allParents, p == x] family = go [n] [n] where go seen [] = seen go seen (x : xs) = let new = [d | d <- below x, d `notElem` seen] in go (seen <> new) (xs <> new) mapM (\x -> E.ChoiceExpr <$> exceptionName PyExpr {span = e.span, node = NameRef x}) (nub family) _ -> pure . E.ChoiceExpr <$> expr e pairedSource x = case x.node of Call PyExpr {node = NameRef f} _ -> f `elem` ["zip", "enumerate"] Call PyExpr {node = Attribute _ "items"} [] -> True _ -> False isLoopPragma x = case x.node of ExprStmt PyExpr {node = Call PyExpr {node = NameRef n} _} -> n `elem` ["invariant", "decreases", "increases"] _ -> False raising e m = do name <- exceptionName e kinds <- gets (.classes) -- (Python's str of a KeyError is its key's repr, `'zero'`) let keyError = e.node == NameRef "KeyError" && not (Map.member "KeyError" kinds) shown = if keyError then (\x -> PyExpr {span = x.span, node = Call PyExpr {span = x.span, node = NameRef "repr"} [Argument {keyword = Nothing, value = x}]}) <$> m else m message <- traverse messageOf shown one (S.SRaise S.RaiseStmt {exception = Just name, message}) isClassPattern c = case c.pattern.node of Call PyExpr {node = NameRef _} _ -> True _ -> False patternChoices p = case p.node of NameRef "_" -> pure [E.ChoiceOthers p.span] -- (a bare name is a capture pattern, Python's: it matches anything) NameRef _ -> pure [E.ChoiceOthers p.span] BinOp "|" a b -> (<>) <$> patternChoices a <*> patternChoices b _ -> pure . E.ChoiceExpr <$> expr p -- (a literal, a negative number, or a dotted name such as an `Enum` member) valuePattern v = case v.node of IntLit _ -> True FloatLit _ _ -> True StrLit _ -> True BoolLit _ -> True UnaryOp "-" PyExpr {node = IntLit _} -> True UnaryOp "-" PyExpr {node = FloatLit _ _} -> True Attribute _ _ -> True _ -> False capture p = case p.node of NameRef k | k /= "_" -> Just (k, p.span) _ -> Nothing -- (the body of a case whose pattern captures the subject, in a block with the name) captured selector p ss = case capture p of Just (k, ks) -> [S.Stmt {span = p.span, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just [D.Decl {span = ks, node = D.DObject D.ObjectDecl {names = [ident ks k], aliased = False, constant = True, subtype = T.InferredType, initial = Just selector, aspects = []}}], statements = orNull ss, handlers = [], endLabel = Nothing}}] Nothing -> ss callStatement e = case e.node of StrLit _ -> pure [] ExcludedExpr _ _ -> [] <$ expr e Call PyExpr {node = NameRef "print"} args -> printStatement e.span args -- `xs.pop()`, `xs.pop(i)` and `d.pop(k)` whose value is not used: the element deleted Call PyExpr {node = Attribute p "pop", span = ps} args | all (isNothing . (.keyword)) args, length args <= 1 -> do container <- expr p vs <- mapM (expr . (.value)) args one (S.SCall (form e.span (E.FormMethod (ident ps (if null args then "Delete_Last" else "Delete")) []) (container : vs))) -- `sleep(seconds)`: a delay; `stop()`: the program ends (its tasks never do) Call PyExpr {node = NameRef "sleep"} [a] -> do v <- expr a.value one (S.SDelay S.DelayStmt {until = False, value = v}) Call PyExpr {node = NameRef "stop"} [] -> do modify' \st' -> st' {generics = Set.insert ["Verada", "Tasking"] st'.generics} one (S.SCall (dottedE e.span ["Verada", "Tasking", "Stop"])) Call PyExpr {node = NameRef n} [a] | Just p <- lookup n [("invariant", "Loop_Invariant"), ("assume", "Assume")] -> do v <- expr a.value one (pragma p [v]) Call PyExpr {node = NameRef n} [a] | n `elem` ["decreases", "increases"] -> do v <- expr a.value let direction = if n == "decreases" then "Decreases" else "Increases" one (S.SPragma E.Pragma {span = st.span, name = ident st.span "Loop_Variant", arguments = [E.Argument {span = a.value.span, formal = Just (ident a.value.span direction), value = E.ArgExpr v, reference = Nothing}]}) Call {} -> do c <- expr e one (S.SCall c) _ -> [] <$ reject e.span "an expression on its own does nothing: Vibe takes calls here" "not a call" pragma n args = S.SPragma E.Pragma {span = st.span, name = ident st.span n, arguments = [E.Argument {span = a.span, formal = Nothing, value = E.ArgExpr a, reference = Nothing} | a <- args]} -- | `for i in range(a, b, s)`, its statements given: a count of steps, i each step's value -- (Python's values: from a while below b, or above it for a negative step). The count, -- `(stop - start + step - 1) / step` for a positive step, is none when the range is empty; -- the start and the step are kept, as Python's range keeps them. The loop's own pragmas -- come first, given what stands for i there and the count of steps taken so far. steppedFor :: Span -> Span -> Text -> Span -> PyExpr -> PyExpr -> PyExpr -> ((E.Expr, E.Expr) -> [S.Stmt]) -> [S.Stmt] -> D [S.Stmt] steppedFor sp isp i rs a stop by pragmas body = do let literal x = case x.node of IntLit n -> Just n UnaryOp "-" PyExpr {node = IntLit n} -> Just (negate n) _ -> Nothing step = literal by when (step == Just 0) (reject by.span "`range`'s step is not 0" "zero step") k <- freshName "Verada_Step_" startName <- freshName "Verada_Start_" byName <- freshName "Verada_By_" lo <- expr a hi <- expr stop stepValue <- expr by let int n = E.Expr {span = rs, node = E.EInteger n} bin o x y = binary rs o (paren x) (paren y) kept n v = if isJust (literal (if n == startName then a else by)) then Nothing else Just (n, v) held = catMaybes [kept startName lo, kept byName stepValue] start = maybe lo (const (nameE rs startName)) (lookup startName held) stepE = maybe stepValue (const (nameE rs byName)) (lookup byName held) upward s = bin E.OpDiv (bin E.OpAdd (bin E.OpSub hi start) (bin E.OpSub s (int 1))) s downward s = bin E.OpDiv (bin E.OpAdd (bin E.OpSub start hi) (bin E.OpSub s (int 1))) s count = case step of Just n | n > 0 -> upward (int n) Just n -> downward (int (negate n)) Nothing -> E.Expr {span = rs, node = E.EParen E.Expr {span = rs, node = E.EIf E.IfExpr {condition = bin E.OpGt stepE (int 0), thenValue = upward stepE, elsifs = [], elseValue = Just (downward E.Expr {span = rs, node = E.EUnary E.Unary {op = E.OpMinus, operand = paren stepE}})}}} counter = nameE rs k value = bin E.OpAdd start (bin E.OpMul counter stepE) decl = D.Decl {span = isp, node = D.DObject D.ObjectDecl {names = [ident isp i], aliased = False, constant = True, subtype = T.InferredType, initial = Just value, aspects = []}} inner = S.Stmt {span = sp, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just [decl], statements = body, handlers = [], endLabel = Nothing}} iterator = E.Iterator {parameter = ident rs k, subtype = Nothing, reverse = False, domain = E.InRange (E.DiscreteBounds E.RangeExpr {span = rs, low = int 0, high = binary rs E.OpSub (paren count) (int 1)}), filter = Nothing, whileCondition = Nothing, alongside = []} prag = substituteName (ident isp i) value (pragmas (value, counter)) looped = S.Stmt {span = sp, node = S.SLoop S.LoopStmt {label = Nothing, scheme = S.ForLoop iterator, statements = prag <> [inner], endLabel = Nothing}} -- (of `int`: an untyped constant would be a named number in Vada, which is static) decls = [D.Decl {span = rs, node = D.DObject D.ObjectDecl {names = [ident rs n], aliased = False, constant = True, subtype = indication rs (nameE rs "Integer"), initial = Just v, aspects = []}} | (n, v) <- held] pure if null decls then [looped] else [S.Stmt {span = sp, node = S.SBlock S.BlockStmt {label = Nothing, declarations = Just decls, statements = [looped], handlers = [], endLabel = Nothing}}] -- | `range(n)`, `range(a, b)`, an array's `m.indices(k)` (its dimension k's, from 0), an -- array, or any of them `reversed(...)`. iterationOf :: PyExpr -> D (Maybe (E.IterationDomain, Bool)) iterationOf src = case src.node of -- `for c in Color` of an `Enum` class: its members, in order NameRef c -> gets (Map.member c . (.enums)) >>= \case True -> pure (Just (E.InRange (E.DiscreteSubtype E.SubtypeIndication {span = src.span, notNull = False, mark = nameE src.span c, constraint = Nothing}), False)) False -> do a <- expr src pure (Just (E.OfContainer a, False)) Call PyExpr {node = NameRef "range"} args -> fmap (,False) <$> rangeDomain src.span args Call PyExpr {node = NameRef "reversed"} [Argument {keyword = Nothing, value = inner}] -> fmap (fmap not) <$> iterationOf inner -- a dict's `d.keys()` are its keys, as `d` is iterated; `d.values()` its values in the same -- order Call PyExpr {node = Attribute d "keys"} [] -> iterationOf d Call PyExpr {node = Attribute d "values", span = vs} [] -> do x <- expr d pure (Just (E.OfContainer (form vs (E.FormMethod (ident vs "Value_Model") []) [x]), False)) Call PyExpr {node = Attribute p "indices"} [Argument {keyword = Nothing, value = PyExpr {node = IntLit k}}] | k >= 0 -> do prefix <- expr p let dimension = E.Expr {span = src.span, node = E.EAttribute E.AttributeRef {prefix, designator = ident src.span "Range", arguments = [E.Expr {span = src.span, node = E.EInteger (k + 1)}]}} pure (Just (E.InRange (E.DiscreteSubtype E.SubtypeIndication {span = src.span, notNull = False, mark = dimension, constraint = Nothing}), False)) -- (a display, `for n in [1, 2, 3]`: of the type its elements give) _ | isDisplay src.node -> pyType src >>= \case Just t@(PList _) -> qualified t Just t@(PSet _) -> qualified t _ -> do a <- expr src pure (Just (E.OfContainer a, False)) _ -> do a <- expr src pure (Just (E.OfContainer a, False)) where isDisplay = \case ListLit (_ : _) -> True SetLit (_ : _) -> True _ -> False qualified t = do a <- expr src mark <- typeExpr (typeAnnotation src.span t) pure (Just (E.OfContainer E.Expr {span = src.span, node = E.EQualified E.Qualified {mark, operand = a}}, False)) -- | What a `for` (a loop's or a generator's) iterates, with Python's iterator builtins that -- are Verada's pipelines (stream-combinators.md 8): `zip(a, b)` walks sources in step, -- `enumerate(a)` counts from 0 in step with `a`, `takewhile(lambda y: p, s)` stops at the -- first element that fails `p`. Nothing (reported) for other targets. iteratorFor :: PyExpr -> PyExpr -> D (Maybe E.Iterator) iteratorFor target source = case (target.node, source.node) of (_, Call PyExpr {node = NameRef "takewhile"} [Argument {value = PyExpr {node = Lambda [y] p}}, Argument {value = inner}]) -> iteratorFor target inner >>= \case Just it -> do condition <- expr p let continuing = substituteName (ident p.span y) E.Expr {span = target.span, node = E.ENameRef it.parameter} condition pure (Just (rebuilt it it.alongside (Just (maybe continuing (\w -> binary p.span E.OpAndThen w continuing) it.whileCondition)))) Nothing -> pure Nothing (TupleLit names, Call PyExpr {node = NameRef "zip"} args) | length names == length args, Just named <- mapM nameOf names -> do domains <- mapM (iterationOf . (.value)) args -- (the sources go in step from the first: one walked backwards leads, the others -- following it forwards, which pairs the same elements; two cannot) case sequence domains of Just ds -> case [k | (k, (_, True)) <- zip [0 :: Int ..] ds] of backwards@(_ : _ : _) -> Nothing <$ reject source.span "`zip` walks at most one of its sources `reversed`" (Text.pack (show (length backwards)) <> " reversed") leading -> do let k = case leading of { [j] -> j; _ -> 0 } sources = zip named ds case splitAt k sources of (before, (n0, (d0, rev)) : after) -> pure (Just (rebuilt (plain n0 d0 rev) [E.Lockstep {parameter = n, domain = d} | (n, (d, _)) <- before <> after] Nothing)) _ -> pure Nothing _ -> pure Nothing -- `for k, v in d.items()`: the keys, and in step the values (TupleLit [k, v], Call PyExpr {node = Attribute d "items", span = is} []) | Just key <- nameOf k, Just value <- nameOf v -> do x <- expr d pure (Just (rebuilt (plain key (E.OfContainer x) False) [E.Lockstep {parameter = value, domain = E.OfContainer (form is (E.FormMethod (ident is "Value_Model") []) [x])}] Nothing)) (TupleLit [i, x], Call PyExpr {node = NameRef "enumerate"} (Argument {keyword = Nothing, value = a} : start)) | Just counter <- nameOf i , Just element <- nameOf x , length start <= 1 , all (\b -> b.keyword `elem` [Nothing, Just "start"]) start -> iterationOf a >>= \case Just (d, rev) -> do let s = source.span integerLast = E.Expr {span = s, node = E.EAttribute E.AttributeRef {prefix = nameE s "Integer", designator = ident s "Last", arguments = []}} -- (counting from `start`, 0 unless given) low <- case start of [b] -> expr b.value _ -> pure E.Expr {span = s, node = E.EInteger 0} pure (Just (rebuilt (plain element d rev) [E.Lockstep {parameter = counter, domain = E.InRange (E.DiscreteBounds E.RangeExpr {span = s, low, high = integerLast})}] Nothing)) Nothing -> pure Nothing -- (`(x for x in xs if c)`, as Vibe writes a filter that `takewhile` comes after) (NameRef n, GeneratorExp PyExpr {node = NameRef n'} [c]) | n == n', NameRef n'' <- c.target.node, n'' == n -> iteratorFor target c.source >>= \case Just it -> do kept <- mapM expr c.conditions let conjoined = foldl1 (binary source.span E.OpAndThen) <$> nonEmptyList (maybe [] pure it.filter <> kept) pure (Just E.Iterator {parameter = it.parameter, subtype = it.subtype, reverse = it.reverse, domain = it.domain, filter = conjoined, whileCondition = it.whileCondition, alongside = it.alongside}) Nothing -> pure Nothing -- `range(a, b, s)` with a literal step: the values from a to b, walked backwards for a -- negative step, those a whole number of steps from a (Python's; a, read again at each -- value, is a name or a number) (NameRef n, Call PyExpr {node = NameRef "range"} [Argument {keyword = Nothing, value = a}, Argument {keyword = Nothing, value = b}, Argument {keyword = Nothing, value = by}]) | Just step <- literalInt by, step /= 0, steady a -> do lo <- expr a hi <- expr b let s = source.span int k = E.Expr {span = s, node = E.EInteger k} p = ident target.span n this = E.Expr {span = target.span, node = E.ENameRef p} bounds l h = E.InRange (E.DiscreteBounds E.RangeExpr {span = s, low = l, high = h}) (domain, rev, from) | step > 0 = (bounds lo (binary s E.OpSub (paren hi) (int 1)), False, binary s E.OpSub this (paren lo)) | otherwise = (bounds (binary s E.OpAdd (paren hi) (int 1)) lo, True, binary s E.OpSub (paren lo) this) onStep = binary s E.OpEq (binary s E.OpMod (paren from) (int (abs step))) (int 0) pure (Just E.Iterator {parameter = p, subtype = Nothing, reverse = rev, domain, filter = if abs step == 1 then Nothing else Just onStep, whileCondition = Nothing, alongside = []}) (NameRef _, Call PyExpr {node = NameRef "range"} [_, _, by]) | Nothing <- literalInt by.value -> Nothing <$ reject source.span "here `range` takes a step that is a number, such as `range(a, b, 2)`: declare the list with its comprehension, or write the loop, for a step that is computed" "step" (NameRef _, Call PyExpr {node = NameRef "range"} [Argument {value = a}, _, _]) | not (steady a) -> Nothing <$ reject a.span "here `range` with a step takes a start that is a name or a number: name the start first" "start" (NameRef n, _) -> fmap (\(d, rev) -> plain (ident target.span n) d rev) <$> iterationOf source _ -> Nothing <$ reject target.span "a `for` takes one name, or a tuple of names over `zip(...)` or `enumerate(...)`" "target" where literalInt x = case x.node of IntLit k -> Just k UnaryOp "-" PyExpr {node = IntLit k} -> Just (negate k) _ -> Nothing steady x = case x.node of NameRef _ -> True _ -> isJust (literalInt x) nameOf e = case e.node of NameRef n -> Just (ident e.span n) _ -> Nothing nonEmptyList xs = if null xs then Nothing else Just xs plain parameter domain rev = E.Iterator {parameter, subtype = Nothing, reverse = rev, domain, filter = Nothing, whileCondition = Nothing, alongside = []} rebuilt it alongside whileCondition = E.Iterator {parameter = it.parameter, subtype = it.subtype, reverse = it.reverse, domain = it.domain, filter = it.filter, whileCondition, alongside} rangeDomain :: Span -> [Argument] -> D (Maybe E.IterationDomain) rangeDomain s args = case [a.value | a <- args] of [n] -> do hi <- upperOf n pure (Just (bounds (E.Expr {span = n.span, node = E.EInteger 0}) hi)) [a, b] -> do lo <- expr a hi <- upperOf b pure (Just (bounds lo hi)) _ -> Nothing <$ reject s "Vibe does not take `range` with a step: loop over `range(n)` and compute each value from the loop variable" "step" where bounds lo hi = E.InRange (E.DiscreteBounds E.RangeExpr {span = s, low = lo, high = hi}) -- Python's ranges are half-open: `range(a, n + 1)` is `a .. n` upperOf b = case b.node of BinOp "+" x PyExpr {node = IntLit 1} -> expr x _ -> do v <- expr b pure (binary b.span E.OpSub v E.Expr {span = b.span, node = E.EInteger 1}) -- | @print(a, b)@: Python's images, separated by spaces, then a new line. printStatement :: Span -> [Argument] -> D [S.Stmt] printStatement s args = do modify' \st -> st {usesPrint = True, usesText = True} images <- forM args \a -> case (a.keyword, a.value.node) of (Just k, StrLit _) | k `elem` ["end", "sep"] -> pure Nothing (Just _, _) -> Nothing <$ reject a.value.span "`print` takes the keyword arguments `sep=` and `end=`, each with a string literal (for another separator, build the line with an f-string or `str.join`)" "keyword" (_, StrLit t) -> pure (Just [E.Expr {span = a.value.span, node = E.EString t}]) -- (an f-string printed is its pieces, each put in turn: the same text, without joining -- them first, which could make a string longer than any index allows) (_, FString fparts) -> Just <$> fstringPieces a.value.span fparts -- (a literal template's `format`, as the f-string it means) (_, Call PyExpr {node = Attribute PyExpr {node = StrLit template, span = ts} "format"} fargs) | all (isNothing . (.keyword)) fargs , Right fparts <- formatFields ts template (map (.value) fargs) -> Just <$> fstringPieces a.value.span fparts -- (a printf-style template, as the f-string it means) (_, BinOp "%" PyExpr {node = StrLit template} b) | Right fparts <- percentFields template (case b.node of { TupleLit vs -> vs; _ -> [b] }) -> Just <$> fstringPieces a.value.span fparts _ -> do wholeRows a.value v <- expr a.value pure (Just [imageOf a.value.span v]) -- (`sep=` is written between the values, as Python's ` ` is by default) let separator = case [t | Argument {keyword = Just "sep", value = PyExpr {node = StrLit t}} <- args] of t : _ -> t [] -> " " parts = filter (/= E.Expr {span = s, node = E.EString ""}) (concat (joinWith [E.Expr {span = s, node = E.EString separator}] (catMaybes images))) -- (each piece as Python prints it: an image as Text_IO writes a String, a string's code -- points as UTF-8) -- (a piece of text is a call, an image a text at its own place: pieces can share one) asText i p = case p.node of E.EString t -> textPiece s i t _ -> form p.span E.FormText [p] puts = [S.Stmt {span = s, node = S.SCall (call s ["Verada", "Vibe", "Write"] [asText i p])} | (i, p) <- zip [0 ..] parts] -- (`end=""` ends no line, and another `end=` is written instead of the line's end) ending = case [(v.span, t) | Argument {keyword = Just "end", value = v@PyExpr {node = StrLit t}} <- args] of [] -> [S.Stmt {span = s, node = S.SCall (dottedE s ["Ada", "Text_IO", "New_Line"])}] (sp, t) : _ | Text.null t -> [] | otherwise -> [S.Stmt {span = s, node = S.SCall (call s ["Ada", "Text_IO", "Put"] [E.Expr {span = sp, node = E.EString t}])}] pure (puts <> ending) where joinWith sep = \case [] -> [] [x] -> [x] x : xs -> x : sep : joinWith sep xs -- | A value made where it is written (a display, a comprehension, a copy, a slice): Python -- infers its type from its parts. madeHere :: PyExpr -> Bool madeHere v = case v.node of TupleLit _ -> True ListLit (_ : _) -> True SetLit _ -> True DictLit (_ : _) -> True ListComp {} -> True SetComp {} -> True DictComp {} -> True Subscript _ [i] -> isSlice i Call PyExpr {node = Attribute _ m} _ -> m `elem` ["copy", "split", "rsplit", "splitlines", "union", "intersection", "difference", "symmetric_difference"] Call PyExpr {node = NameRef f} [_] -> f `elem` ["sorted", "list", "set", "divmod"] Call PyExpr {node = NameRef "divmod"} [_, _] -> True _ -> False -- | A list's, a set's, a dict's or a tuple's type. containerType :: PyType -> Bool containerType = \case PList _ -> True PSet _ -> True PDict _ _ -> True PTuple _ -> True _ -> False -- | An exception by name: one of Python's built-in exceptions (unless the module declares -- its own of the name) is Verada.Vibe's, or Ada's. exceptionName :: PyExpr -> D E.Expr exceptionName e = case e.node of NameRef n | Just (_, path) <- Map.lookup n builtinExceptions -> do kinds <- gets (.classes) if Map.member n kinds then pure (nameE e.span n) else do when (take 2 path == ["Verada", "Vibe"]) (modify' \st -> st {generics = Set.insert ["Verada", "Vibe"] st.generics}) when (take 2 path == ["Ada", "Assertions"]) (needs ["Ada", "Assertions"]) pure (dottedE e.span path) _ -> expr e -- | Python's `template.format(args)` as the f-string it means: each `{}`, `{n}`, `{:spec}` -- and `{!r}` field the argument it names (by position, numbered in turn), `{{` and `}}` a -- brace. formatFields :: Span -> Text -> [PyExpr] -> Either Text [Either Text PyExpr] formatFields s template values = go 0 (Text.unpack template) [] where go :: Int -> String -> String -> Either Text [Either Text PyExpr] go k cs acc = case cs of [] -> Right (literal acc) '{' : '{' : rest -> go k rest ('{' : acc) '}' : '}' : rest -> go k rest ('}' : acc) '{' : rest -> case break (== '}') rest of (field, '}' : after) -> do let (name, conversionAndSpec) = break (`elem` ("!:" :: String)) field (conversion, spec) = case conversionAndSpec of '!' : c : more -> (Just c, case more of { ':' : sp -> Just (Text.pack sp); _ -> Nothing }) ':' : sp -> (Nothing, Just (Text.pack sp)) _ -> (Nothing, Nothing) (index, k') <- case name of "" -> Right (k, k + 1) _ | all isDigit name -> Right (read name, k) _ -> Left "a `str.format` field names an argument by position (`{}` or `{0}`): Vibe takes the template's arguments by position; use an f-string for names" v <- maybe (Left ("`str.format` has no argument " <> Text.pack (show index) <> " for this template")) Right (listToMaybe (drop index values)) let field' = case (conversion, spec) of (Nothing, Nothing) -> v -- (at a place of its own, after the value: forms are told apart by their -- places, and a template may name a value twice) _ -> PyExpr {span = Span {file = v.span.file, start = v.span.end, end = v.span.end - 1 - k}, node = FormatField v conversion spec} rest' <- go k' after [] Right (literal acc <> (Right field' : rest')) _ -> Left "a `str.format` template's `{` has no `}`" '}' : _ -> Left "a `str.format` template's `}` stands alone: write `}}` for a brace" c : rest -> go k rest (c : acc) literal acc = [Left (Text.pack (reverse acc)) | not (null acc)] _ = s -- | A literal's text, to compare literals by (empty for anything else). literalKey :: PyExpr -> Text literalKey x = case x.node of IntLit k -> Text.pack (show k) UnaryOp "-" PyExpr {node = IntLit k} -> Text.pack (show (negate k)) StrLit t -> "'" <> t _ -> "" -- | A set's methods that are its operators. setOperators :: [(Text, Text)] setOperators = [("issubset", "<="), ("issuperset", ">="), ("union", "|"), ("intersection", "&"), ("difference", "-"), ("symmetric_difference", "^"), ("isdisjoint", "isdisjoint")] -- | An operand Vibe may read twice: a name, a field of one, a number. steadyOperand :: PyExpr -> Bool steadyOperand x = case x.node of IntLit _ -> True FloatLit _ _ -> True UnaryOp "-" y -> steadyOperand y _ -> steadyPlace x -- | The first of a list, if any (for a list known not to be empty, a default otherwise). head' :: [Maybe a] -> Maybe a head' = \case x : _ -> x [] -> Nothing -- | A list's type. isListType :: PyType -> Bool isListType = \case PList _ -> True _ -> False -- | A value Vibe may read more than once (a name, a field of one, a literal). steadyPlace :: PyExpr -> Bool steadyPlace x = case x.node of NameRef _ -> True Attribute q _ -> steadyPlace q StrLit _ -> True _ -> False -- | Python's `xs[a:b:k]` of a list or a str: a comprehension over the positions the slice -- takes (Python's `slice.indices`: a bound counted from the end when negative, kept within -- the sequence), each the element there; a str's joined. steppedSlice :: Span -> PyExpr -> Maybe PyExpr -> Maybe PyExpr -> PyExpr -> Span -> D E.Expr steppedSlice s p lo hi by ss = do t <- pyType p let stepOf = case by.node of IntLit k -> Just k UnaryOp "-" PyExpr {node = IntLit k} -> Just (negate k) _ -> Nothing case (stepOf, t) of (Nothing, _) -> nameE s "Integer" <$ reject by.span "a slice's step is a number written in it (`xs[::2]`, `s[::-1]`); for a step known only when the program runs, loop over `range(a, b, step)` and take each element" "not a number" (Just 0, _) -> nameE s "Integer" <$ reject by.span "a slice's step is not 0 (Python raises ValueError)" "zero step" (_, Nothing) -> nameE s "Integer" <$ reject p.span "a slice with a step makes a new list or str, and the annotations here do not say which this is: give the sequence its type (`xs: list[int] = ...`)" "unknown type" (_, Just t') | not (t' == PStr || isListType t') -> nameE s "Integer" <$ reject p.span "a slice with a step takes a list or a str" "neither" (_, _) | not (steadyPlace p) -> nameE s "Integer" <$ reject p.span "a slice with a step reads the sequence at each position: name it first, `ys = ...`, then `ys[::2]`" "not named" (Just k, Just t') -> do modify' \st -> st {generics = Set.insert ["Verada", "Vibe"] st.generics} prefix <- expr p position <- freshName "Verada_Position_" let int n = E.Expr {span = ss, node = E.EInteger n} len = form ss E.FormLength [prefix] bound f b = do v <- expr b pure (call b.span ["Verada", "Vibe", f] [v, len]) this = nameE ss position (domain, rev, from) <- if k > 0 then do l <- maybe (pure (int 0)) (bound "Slice_Bound") lo h <- maybe (pure len) (bound "Slice_Bound") hi pure (E.DiscreteBounds E.RangeExpr {span = ss, low = l, high = binary ss E.OpSub (paren h) (int 1)}, False, binary ss E.OpSub this (paren l)) else do l <- maybe (pure (binary ss E.OpSub len (int 1))) (bound "Slice_Bound_Down") lo h <- maybe (pure (paren E.Expr {span = ss, node = E.EUnary E.Unary {op = E.OpMinus, operand = int 1}})) (bound "Slice_Bound_Down") hi pure (E.DiscreteBounds E.RangeExpr {span = ss, low = binary ss E.OpAdd (paren h) (int 1), high = l}, True, binary ss E.OpSub (paren l) this) let onStep = binary ss E.OpEq (binary ss E.OpMod (paren from) (int (abs k))) (int 0) iterator = E.Iterator {parameter = ident ss position, subtype = Nothing, reverse = rev, domain = E.InRange domain, filter = if abs k == 1 then Nothing else Just onStep, whileCondition = Nothing, alongside = []} element = form s E.FormItem [prefix, this] aggregate = E.Expr {span = s, node = E.EAggregate E.Aggregate {bracket = True, contents = E.PlainAggregate (E.Associations [E.IteratedAssocNode E.IteratedAssoc {span = s, iterator, value = element}])}} case t' of -- (a str's characters, joined: Python's str) PStr -> do needs ["Verada", "Strings", "Text_Lists"] empty <- expr PyExpr {span = ss, node = StrLit ""} pure (form s (E.FormMethod (ident s "join") []) [empty, aggregate]) _ -> do mark <- typeExpr (typeAnnotation s t') pure E.Expr {span = s, node = E.EQualified E.Qualified {mark, operand = aggregate}} -- | Every expression inside a node. universePy :: (Data a) => a -> [PyExpr] universePy x = maybe [] pure (cast x) <> concat (gmapQ universePy x) -- | Whether an expression is a list of lists (`list[list[T]]`), by the annotations. nestedList :: PyExpr -> D Bool nestedList x = pyType x <&> \case Just (PList (PList _)) -> True _ -> False -- | A position from 0, Python's, as the position from 1 a nested list's operations take. fromOne :: PyExpr -> D E.Expr fromOne i = do v <- expr i pure (binary i.span E.OpAdd (paren v) E.Expr {span = i.span, node = E.EInteger 1}) -- | Whether a subscript is a slice (`a:b`), which makes a new list or string. isSlice :: PyExpr -> Bool isSlice i = case i.node of Slice {} -> True _ -> False -- | A form whose meaning depends on its operands' types, which Sema resolves. form :: Span -> E.SurfaceFormKind -> [E.Expr] -> E.Expr form s kind operands = E.Expr {span = s, node = E.ESurfaceForm E.SurfaceForm {kind, operands}} -- | Python's text for a value (one that is already text, from `str()`, stays as it is). -- | A Python string as a value: a text where a text is wanted (Sema decides, T30). -- | An exception's or an assertion's message, Ada's String in UTF-8 (as `str` of an -- exception reads it back): an ASCII literal as it is, any other value its `str`, a text, as -- Verada.Vibe.Message makes it a String. messageOf :: PyExpr -> D E.Expr messageOf x = case x.node of StrLit t | Text.all isAscii t -> expr x _ -> do modify' \st -> st {usesPrint = True} wholeRows x t <- expr x >>= pythonString x.span . imageOf x.span pure (call x.span ["Verada", "Vibe", "Message"] [t]) pythonString :: Span -> E.Expr -> D E.Expr pythonString s v = do modify' \st -> st {usesText = True} pure (form s E.FormText [v]) -- | An f-string's string: its text and its fields' images, each a text (an image of a text -- is the text, D171), joined. fstring :: Span -> [Either Text PyExpr] -> D E.Expr fstring s parts = do -- (images come from Verada.Vibe) modify' \st -> st {usesPrint = True} pieces <- forM (numbered parts) \case Left (i, t) -> do modify' \st -> st {usesText = True} pure (textPiece s i t) Right x@PyExpr {node = FormatField {}} -> formatted x >>= pythonString x.span Right x -> wholeRows x >> expr x >>= pythonString x.span . imageOf x.span pure case pieces of [] -> E.Expr {span = s, node = E.EString ""} p : ps -> paren (foldl (binary s E.OpConcat) p ps) -- | Each piece of text with its position among the pieces. numbered :: [Either Text a] -> [Either (Int, Text) a] numbered ps = [either (Left . (i,)) Right p | (i, p) <- zip [0 ..] ps] -- | The @i@th piece of text in what @s@ spans, as a text: an explicit call, at places of no -- width that are its own (the analysis knows an expression by its place, and the pieces, the -- call and its string, are each of their own type). textPiece :: Span -> Int -> Text -> E.Expr textPiece s i t = call at ["Verada", "Strings", "Texts", if Text.any (\c -> ord c > 255) t then "To_Text_Of" else "To_Text"] [E.Expr {span = at {start = at.start + 1, end = at.start + 1}, node = E.EString t}] where at = s {start = s.start + 2 * i, end = s.start + 2 * i} -- | An f-string's text and its fields' images, apart. fstringPieces :: Span -> [Either Text PyExpr] -> D [E.Expr] fstringPieces s parts = do modify' \st -> st {usesPrint = True} forM [p | p <- parts, either (not . Text.null) (const True) p] \case Left t -> pure E.Expr {span = s, node = E.EString t} Right x@PyExpr {node = FormatField {}} -> formatted x Right x -> wholeRows x >> imageOf x.span <$> expr x -- | An f-string's field with a conversion or a format spec: Python's `format(v, spec)` of -- the value, or of its repr (`!r`) or str (`!s`); the spec read here, as Python reads it, and -- given to Verada.Vibe.Formatting as its record (whose preconditions say which specs each -- type takes, where Python raises ValueError). formatted :: PyExpr -> D E.Expr formatted x = case x.node of FormatField v conversion spec -> do needs ["Verada", "Vibe", "Formatting"] value0 <- expr v -- (a number written out is an int's or a float's, which the spec's function needs) let value = case v.node of IntLit _ -> call v.span ["Integer"] [value0] FloatLit _ _ -> call v.span ["Long_Float"] [value0] _ -> value0 converted = case conversion of Just 'r' -> reprOf x.span value Just _ -> imageOf x.span value Nothing -> value case spec of Nothing -> pure converted -- (a conversion's result is a str, which the spec formats) -- (the str at a place of its own: forms are told apart by their places) Just t | isJust conversion -> pythonString Span {file = v.span.file, start = v.span.start, end = v.span.start} converted >>= \c -> formatWith x.span c t Just t -> formatWith x.span converted t _ -> expr x -- | Python's `template % values` of a literal template (printf's style): the f-string it -- means, each conversion the value's format (`%5.2f` is `{v:5.2f}`, `%s` its str, `%r` its -- repr), `%%` a percent sign. percentFields :: Text -> [PyExpr] -> Either Text [Either Text PyExpr] percentFields template values = go (Text.unpack template) values [] where go :: String -> [PyExpr] -> String -> Either Text [Either Text PyExpr] go cs vs acc = case cs of [] | null vs -> Right (literal acc) [] -> Left "the template has fewer conversions than values (Python's TypeError)" '%' : '%' : rest -> go rest vs ('%' : acc) '%' : rest -> do let (flags, r1) = span (`elem` ("-+ 0#" :: String)) rest (width, r2) = span isDigit r1 (precision, r3) = case r2 of '.' : more -> let (p, r) = span isDigit more in (Just p, r) _ -> (Nothing, r2) (kind, r4) <- case r3 of k : r | k `elem` ("diouxXeEfFgGcsra" :: String) -> Right (k, r) _ -> Left "a `%` conversion Vibe reads is `%d`, `%i`, `%f`, `%e`, `%g`, `%x`, `%o`, `%c`, `%s`, `%r` or `%%`, with flags, a width and a precision" (v, more) <- case vs of x : xs -> Right (x, xs) [] -> Left "the template has more conversions than values (Python's TypeError)" let align | '-' `elem` flags = "<" | otherwise = if kind `elem` ("sra" :: String) && not (null width) then ">" else "" sign = [c | c <- "+ ", c `elem` flags, not (kind `elem` ("srac" :: String))] zero = if '0' `elem` flags && '-' `notElem` flags && not (kind `elem` ("srac" :: String)) then "0" else "" alternate = ['#' | '#' `elem` flags] typed = case kind of 'i' -> "d" 'u' -> "d" k | k `elem` ("sra" :: String) -> "" k -> [k] spec = align <> take 1 sign <> alternate <> zero <> width <> maybe "" ('.' :) (if kind `elem` ("sra" :: String) then precision else precision) <> typed conversion = case kind of 's' -> Just 's' 'r' -> Just 'r' 'a' -> Just 'r' _ -> Nothing -- (at a place of its own, after the value: forms are told apart by their places) at = Span {file = v.span.file, start = v.span.end, end = v.span.end} field = case (conversion, spec) of (Just c, "") -> PyExpr {span = at, node = FormatField v (Just c) Nothing} (c, sp) -> PyExpr {span = at, node = FormatField v c (Just (Text.pack sp))} rest' <- go r4 more [] Right (literal acc <> (Right field : rest')) c : rest -> go rest vs (c : acc) literal acc = [Left (Text.pack (reverse acc)) | not (null acc)] -- | Python's repr of a value: a str's with its quotes and escapes, another's its str (Sema -- tells them apart). reprOf :: Span -> E.Expr -> E.Expr reprOf s v = form s (E.FormMethod (ident s "Verada_Repr") []) [v] -- | Python's `format(value, spec)` of a literal spec. formatWith :: Span -> E.Expr -> Text -> D E.Expr formatWith s value t = case formatSpec t of Right fields -> do needs ["Verada", "Vibe", "Formatting"] pure (formatCall s s value fields) Left why -> value <$ reject s ("this format spec is not one Python reads: " <> why) "format spec" -- | A list of lists is printed by its rows, whose images Vibe has (D188): a whole one is -- refused, with the loop that prints it. wholeRows :: PyExpr -> D () wholeRows x = pyType x >>= \case Just (PList (PList _)) -> reject x.span "Vibe makes no str of a list of lists: print its rows, `for row in grid: print(row)`, or build the text from them (Python's shows them in one pair of brackets, `[[1, 2], [3, 4]]`)" "list of lists" _ -> pure () imageOf :: Span -> E.Expr -> E.Expr imageOf s v = case v.node of E.ESurfaceForm E.SurfaceForm {kind = E.FormImage} -> v -- (a Python string's image is the string) E.ESurfaceForm E.SurfaceForm {kind = E.FormText, operands = [x]} -> x _ -> form s E.FormImage [v] call :: Span -> [Text] -> [E.Expr] -> E.Expr call s path args = E.Expr {span = s, node = E.EApply E.Apply {prefix = dottedE s path, arguments = [E.Argument {span = a.span, formal = Nothing, value = E.ArgExpr a, reference = Nothing} | a <- args], bracketed = Nothing}} -- * Expressions binary :: Span -> E.BinaryOp -> E.Expr -> E.Expr -> E.Expr binary s o l r = E.Expr {span = s, node = E.EBinary E.Binary {op = o, left = l, right = r}} paren :: E.Expr -> E.Expr paren e = E.Expr {span = e.span, node = E.EParen e} binaryOp :: Span -> Text -> PyExpr -> PyExpr -> D E.Expr binaryOp s o a b = do l0 <- expr a r0 <- expr b ta <- fmap numeric <$> pyType a tb <- fmap numeric <$> pyType b -- (an `int` meeting a `float` is converted, as Python converts it) let mixed = isJust ta && isJust tb && ta /= tb && all (`elem` [Just PInt, Just PFloat]) [ta, tb] l = if mixed && ta == Just PInt then toFloat l0 else l0 -- (a float's power with an int exponent is Verada.Vibe.Floats.Power's, below) r = if mixed && tb == Just PInt && o /= "**" then toFloat r0 else r0 floats = PFloat `elem` catMaybes [ta, tb] floatCall f args' = do needs ["Verada", "Vibe", "Floats"] pure (call s ["Verada", "Vibe", "Floats", f] args') case o of -- Python's float floor division and modulo, and a float power (Verada.Vibe.Floats) "//" | floats -> floatCall "Floor_Divide" [l, r] "%" | floats -> floatCall "Modulo" [l, r] -- (a float base with an int exponent too: CPython converts the exponent and takes the -- C library's pow, which repeated squaring, Ada's `**`, can differ from in the last digit) "**" | tb == Just PFloat || ta == Just PFloat -> floatCall "Power" [toFloat l, toFloat r] -- Sema resolves the Integer overload even when the operand type comes from another -- module or an indexed component. Booleans, modular types and sets retain their operators. _ | Just op <- lookup o [("&", E.OpAnd), ("|", E.OpOr), ("^", E.OpXor)] -> do needs bitwiseUnit pure (binary s op (wrap l) (wrap r)) -- Python's floor division, exactly: (A - A mod B) / B "//" -> pure (binary s E.OpDiv (paren (binary s E.OpSub l (paren (binary s E.OpMod l r)))) r) -- Python's true division: a `float`, of whole numbers too (`7 / 2` is 3.5) "/" -> pure (binary s E.OpDiv (toFloat l) (toFloat r)) -- Python's shifts of an `int`: `x << n` is x * 2 ** n, `x >> n` its floor division by -- 2 ** n (a negative count is a precondition's failure, Python's ValueError) _ | Just f <- lookup o [("<<", "Shift_Left"), (">>", "Shift_Right")] -> do needs ["Verada", "Vibe", "Integers"] pure (call s ["Verada", "Vibe", "Integers", f] [l, r]) _ -> case lookup o table of Just op -> pure (binary s op (wrap l) (wrap r)) Nothing -> nameE s "Integer" <$ reject s ("Vibe does not take the operator `" <> o <> "`") "operator" where numeric t = case t of PNamed n | n `elem` ["Natural", "Positive", "Integer"] -> PInt _ -> t -- (a float already, a literal or a conversion, is not converted again) toFloat x | alreadyFloat x = x toFloat x = E.Expr {span = x.span, node = E.EApply E.Apply {prefix = nameE x.span "Long_Float", arguments = [E.Argument {span = x.span, formal = Nothing, value = E.ArgExpr x, reference = Nothing}], bracketed = Nothing}} table = [("+", E.OpAdd), ("-", E.OpSub), ("*", E.OpMul), ("%", E.OpMod), ("**", E.OpPow)] alreadyFloat x = case x.node of E.EReal _ -> True E.EApply E.Apply {prefix = E.Expr {node = E.ENameRef n}} -> n.text == "Long_Float" _ -> False -- the operands keep Python's grouping wrap e = case e.node of E.EBinary _ -> paren e E.EIf _ -> paren e _ -> e expr :: PyExpr -> D E.Expr expr e = case e.node of -- (Python's built-in exceptions, where the module declares none of the name) NameRef n | Map.member n builtinExceptions -> exceptionName e NameRef n -> pure (nameE e.span n) IntLit v -> pure E.Expr {span = e.span, node = E.EInteger v} FloatLit v _ -> pure E.Expr {span = e.span, node = E.EReal v} -- a Python string: a text where one is wanted (T30) StrLit t -> pythonString e.span E.Expr {span = e.span, node = E.EString t} FString parts -> fstring e.span parts >>= pythonString e.span BoolLit b -> pure (nameE e.span (if b then "True" else "False")) NoneLit -> pure E.Expr {span = e.span, node = E.ENull} Attribute PyExpr {node = NameRef m} "T" -> pure E.Expr {span = e.span, node = E.ECodeString E.CodeString {language = "apl", code = "⍉ " <> m, codeSpan = e.span}} -- (`x.__dict__`, `x.__class__`: an object's own machinery, reflection, D174) Attribute _ n | n `elem` ["__dict__", "__class__", "__slots__", "__module__", "__name__", "__qualname__", "__bases__", "__mro__"] -> nameE e.span "Integer" <$ reject e.span ("`" <> n <> "` is Python's machinery of an object or a class, reflection, which Vibe's static types do not have (D174): name the fields themselves, or give the class a method") "reflection" Attribute p n -> do member <- isEnumMember p n props <- gets (.properties) -- (`m.first` of a module `m` is its `first`, not a bound) ofModule <- case p.node of NameRef m -> gets (Set.member m . (.modules)) _ -> pure False case () of -- `Colour.RED`: a member of an `Enum` class, `Colour'(RED)` _ | member -> do mark <- expr p operand <- case p.node of Attribute PyExpr {node = NameRef m} _ -> pure (dottedE e.span [m, n]) _ -> pure (nameE e.span n) pure E.Expr {span = e.span, node = E.EQualified E.Qualified {mark, operand}} _ | n `elem` ["first", "last"], not ofModule -> do prefix <- expr p pure (attribute e.span prefix (if n == "first" then "First" else "Last")) -- `x.value` and `x.name`: a field of a record, or an `Enum` member's value or name, -- as x's type says (Sema) -- `b.double` of a property: its method's call _ | not ofModule, Set.member n props -> do prefix <- expr p pure (form e.span (E.FormMethod (ident e.span n) []) [prefix]) _ | n `elem` ["value", "name"], not ofModule -> do prefix <- expr p pure (form e.span (E.FormField (ident e.span n)) [prefix]) _ -> do prefix <- expr p pure E.Expr {span = e.span, node = E.ESelected E.Selected {prefix, selector = E.SelectIdentifier (ident e.span n)}} -- `Color["RED"]`: the member of an `Enum` class of that name Subscript p@PyExpr {node = NameRef c} [k] -> gets (Map.lookup c . (.enums)) >>= \case Just members -> case k.node of StrLit n | n `elem` members -> expr PyExpr {span = e.span, node = Attribute p n} StrLit _ -> nameE e.span "Integer" <$ reject k.span ("`" <> c <> "` has no member of this name (Python's KeyError): its members are " <> Text.intercalate ", " members) "no such member" _ -> expr PyExpr {span = e.span, node = Call PyExpr {span = p.span, node = NameRef ("Verada_" <> c <> "_Of_Name")} [Argument {keyword = Nothing, value = k}]} Nothing -> subscripted e _ -> subscripted e -- | The rest of 'expr': subscripts, calls and operators. subscripted :: PyExpr -> D E.Expr subscripted e = case e.node of -- `grid[i][j]` and `grid[i]` of a list of lists: the element, and a copy of the row -- (Verada.Containers.Unbounded.Nested_Vectors, positions from 1, D188) Subscript inner@PyExpr {node = Subscript g [i]} [j] | not (isSlice i), not (isSlice j) -> nestedList g >>= \case True -> do grid <- expr g ri <- fromOne i rj <- fromOne j pure (form e.span (E.FormMethod (ident e.span "Element") []) [grid, ri, rj]) False -> plainSubscript inner Subscript g [i] | not (isSlice i) -> nestedList g >>= \case True -> do grid <- expr g ri <- fromOne i pure (form e.span (E.FormMethod (ident e.span "Row_Copy") []) [grid, ri]) False -> plainSubscript e _ -> plainSubscript e where plainSubscript _ = subscriptedPlain e -- | The rest of 'expr': subscripts of a sequence, calls and operators. subscriptedPlain :: PyExpr -> D E.Expr subscriptedPlain e = case e.node of -- `a[-1]` counts from the end in Python: of a list or a str, its position `len(a) - 1`; of -- a tuple, its last item (a dict's key -1 is a key) Subscript p [i@PyExpr {node = UnaryOp "-" PyExpr {node = IntLit k}}] -> pyType p >>= \case Just (PTuple ts) | k >= 1, k <= toInteger (length ts) -> do prefix <- expr p pure (form e.span E.FormItem [prefix, E.Expr {span = i.span, node = E.EInteger (toInteger (length ts) - k)}]) Just t | t == PStr || isListType t, steadyPlace p -> do prefix <- expr p let len = form i.span E.FormLength [prefix] pure (form e.span E.FormItem [prefix, paren (binary i.span E.OpSub len E.Expr {span = i.span, node = E.EInteger k})]) Just t | t == PStr || isListType t -> nameE e.span "Integer" <$ reject p.span "a negative index counts from the end, so Vibe reads the sequence twice (its length, then its element): name it first, `ys = ...`, then `ys[-1]`" "not named" Just (PDict _ _) -> do prefix <- expr p index <- expr i pure (form e.span E.FormItem [prefix, index]) _ -> nameE e.span "Integer" <$ reject i.span "a negative index counts from the end of a list or a str, and the annotations here do not say which this is: give the sequence its type (`xs: list[int] = ...`), or write `xs[len(xs) - 1]`" "from the end" -- `m.shape[k]`: the length of an array's dimension k (from 0), as NumPy's Subscript PyExpr {node = Attribute p "shape"} [PyExpr {node = IntLit k}] | k >= 0 -> do prefix <- expr p pure E.Expr {span = e.span, node = E.EAttribute E.AttributeRef {prefix, designator = ident e.span "Length", arguments = [E.Expr {span = e.span, node = E.EInteger (k + 1)}]}} -- `xs[a:b]`: Python's slice, its bounds counted from the end when negative and kept within -- the length (`Verada.Vibe.Slice_Bound`), a missing one the start or the end -- `xs[a:b:k]`: the elements at positions a, a + k, ... before b (from the end for a negative -- k), as Python's slice gives them, a new list or str Subscript p [PyExpr {node = Slice lo hi (Just by), span = ss}] -> steppedSlice e.span p lo hi by ss Subscript p [PyExpr {node = Slice lo hi Nothing, span = ss}] -> do prefix <- expr p modify' \st -> st {generics = Set.insert ["Verada", "Vibe"] st.generics} let len = form ss E.FormLength [prefix] bound b = do v <- expr b pure (call b.span ["Verada", "Vibe", "Slice_Bound"] [v, len]) from <- maybe (pure E.Expr {span = ss, node = E.EInteger 0}) bound lo to <- maybe (pure len) bound hi pure (form e.span E.FormSlice [prefix, from, to]) -- one index: by position in a sequence or list, by value in an array with an index type, -- as the type says (Sema) Subscript p [i] -> do prefix <- expr p index <- expr i pure (form e.span E.FormItem [prefix, index]) -- several: a multidimensional array's, by position in each dimension when its bounds are -- the value's (`rank=`), as Sema finds Subscript p is -> do prefix <- expr p indices <- mapM expr is pure (form e.span E.FormItem (prefix : indices)) Call f args -> callExpr e.span f args -- (`a @ b`, Python's matrix product, and `m.T`, NumPy's transpose, on named arrays: the -- APL they mean, apl-variant.md 8.4) BinOp "@" PyExpr {node = NameRef a} PyExpr {node = NameRef b} -> pure E.Expr {span = e.span, node = E.ECodeString E.CodeString {language = "apl", code = a <> " +.× " <> b, codeSpan = e.span}} BinOp "@" _ _ -> E.Expr {span = e.span, node = E.EInteger 0} <$ reject e.span "`@` takes two named arrays in Vibe: name the operands first" "not named" -- `"%d items" % (n,)`: printf's style, of a literal template, as the f-string it means BinOp "%" PyExpr {node = StrLit template, span = ts} b -> do let values = case b.node of TupleLit vs -> vs _ -> [b] case percentFields template values of Right parts -> expr PyExpr {span = e.span, node = FString parts} Left why -> nameE e.span "Integer" <$ reject ts why "% format" BinOp o a b -> binaryOp e.span o a b -- Python's `~x` of an `int`: -x - 1, written so that it does not overflow UnaryOp "~" x -> do v <- expr x pure (paren (binary e.span E.OpSub E.Expr {span = e.span, node = E.EParen E.Expr {span = e.span, node = E.EUnary E.Unary {op = E.OpMinus, operand = E.Expr {span = e.span, node = E.EInteger 1}}}} (paren' v))) UnaryOp o x -> do v <- expr x let op = case o of "-" -> E.OpMinus "+" -> E.OpPlus _ -> E.OpNot pure E.Expr {span = e.span, node = E.EUnary E.Unary {op, operand = paren' v}} BoolOp o xs -> do vs <- mapM expr xs let op = if o == "and" then E.OpAndThen else E.OpOrElse pure case vs of v : more -> foldl (\l r -> binary e.span op (paren' l) (paren' r)) v more [] -> nameE e.span "True" -- `x in range(a, b)`: a membership of the range's values Compare first [(o, PyExpr {node = Call PyExpr {node = NameRef "range"} args})] | o `elem` ["in", "not in"] -> do operand <- expr first domain <- rangeDomain e.span args pure case domain of Just (E.InRange (E.DiscreteBounds r)) -> E.Expr {span = e.span, node = E.EMembership E.Membership {negated = o == "not in", operand, choices = [E.MemberRange r]}} _ -> operand Compare first rest -> do -- (an `int` compared with a `float` is converted, as Python compares them) types <- mapM pyType (first : map snd rest) let numericType t = case t of Just (PNamed n) | n `elem` ["Natural", "Positive", "Integer"] -> Just PInt _ -> t mixed = Just PFloat `elem` map numericType types && Just PInt `elem` map numericType types && all (`elem` [Just PInt, Just PFloat]) (map numericType types) converted t x = if mixed && numericType t == Just PInt then E.Expr {span = x.span, node = E.EApply E.Apply {prefix = nameE x.span "Long_Float", arguments = [E.Argument {span = x.span, formal = Nothing, value = E.ArgExpr x, reference = Nothing}], bracketed = Nothing}} else x l <- converted (head' types) <$> expr first rs <- mapM (\((o, r), t) -> (o,) . converted t <$> expr r) (zip rest (drop 1 types)) let operands = l : map snd rs pairs = zip3 operands (map fst rs) (map snd rs) parts <- mapM (\(a, o, b) -> comparison e.span o a b) pairs pure case parts of p : more -> foldl (\x y -> binary e.span E.OpAndThen (paren' x) (paren' y)) p more [] -> l IfExp c a b -> do condition <- expr c thenValue <- expr a elseValue <- expr b pure E.Expr {span = e.span, node = E.EParen E.Expr {span = e.span, node = E.EIf E.IfExpr {condition, thenValue, elsifs = [], elseValue = Just elseValue}}} -- a tuple: an aggregate of the tuple type the context gives TupleLit xs -> do vs <- mapM expr xs pure E.Expr {span = e.span, node = E.EAggregate E.Aggregate {bracket = False, contents = E.PlainAggregate (E.Associations (map E.PositionalAssoc vs))}} ListLit xs -> do vs <- mapM expr xs pure E.Expr {span = e.span, node = E.EAggregate E.Aggregate {bracket = True, contents = E.PlainAggregate (E.Associations (map E.PositionalAssoc vs))}} ListComp v [c] -> comprehensionAggregate e.span v c ListComp _ _ -> nameE e.span "Integer" <$ reject e.span "a comprehension with several `for`s builds a list: declare it, `ys: list[int] = [x * y for x in xs for y in zs]`, and use the list" "several `for`s" DictComp {} -> nameE e.span "Integer" <$ reject e.span "a dict comprehension builds a dict: declare it, `d: dict[str, int] = {k: len(k) for k in ks}`, and use the dict" "dict comprehension" SetComp {} -> nameE e.span "Integer" <$ reject e.span "a set comprehension builds a set: declare it, `s: set[int] = {x % 7 for x in xs}`, and use the set" "set comprehension" FormatField {} -> formatted e GeneratorExp _ _ -> nameE e.span "True" <$ reject e.span "a generator expression is taken here only inside `all()` or `any()`" "generator" ExcludedExpr reason _ -> nameE e.span "Integer" <$ reject e.span reason "not in Vibe" -- (a lambda outside an iterator stage is a function value, which may be stored or -- returned: a closure that escapes, D174) Lambda _ _ -> nameE e.span "Integer" <$ reject e.span "a lambda is taken only as an iterator stage's condition (`takewhile(lambda x: x < 5, xs)`): a function value that is stored, passed or returned is a closure that may escape, which Vibe does not have (D174). Define a function with `def` and call it, or a generic function with a `Protocol` bound" "lambda" -- (a walrus where its value is always taken is bound by the statement before, `hoist`) NamedExpr n _ -> nameE e.span n <$ reject e.span ("`" <> n <> " := ...` is taken in an `if`'s or a `while`'s condition and a comprehension's filter, where it is always evaluated: bind `" <> n <> "` on a line of its own here") "walrus" Starred _ -> nameE e.span "Integer" <$ reject e.span "a starred name is taken among an assignment's targets (`a, *rest = xs`) and in a list display a local is bound to (`ys = [*xs, 4]`); `f(*xs)` is not in Vibe, whose functions take a fixed list of parameters" "starred" _ -> nameE e.span "Integer" <$ reject e.span "Vibe does not take this expression" "expression" where paren' x = case x.node of E.EBinary _ -> paren x _ -> x comparison :: Span -> Text -> E.Expr -> E.Expr -> D E.Expr comparison s o a b = case lookup o table of Just op -> pure (binary s op a b) Nothing -> case (o, b.node) of ("in", _) -> membership False ("not in", _) -> membership True ("is", E.ENull) -> pure (binary s E.OpEq a b) ("is not", E.ENull) -> pure (binary s E.OpNe a b) _ -> a <$ reject s ("Vibe does not take the comparison `" <> o <> "` here: `is` and `is not` compare with `None`; compare values with `==` and `!=`") "comparison" where table = [("<", E.OpLt), ("<=", E.OpLe), (">", E.OpGt), (">=", E.OpGe), ("==", E.OpEq), ("!=", E.OpNe)] -- `x in (A, B)`: one of the choices; `x in xs`, an element of an array or container membership negated = case b.node of E.EAggregate E.Aggregate {contents = E.PlainAggregate (E.Associations xs)} -> pure E.Expr {span = s, node = E.EMembership E.Membership {negated, operand = a, choices = [E.MemberExpr x | E.PositionalAssoc x <- xs]}} _ -> let contained = form s E.FormContains [b, a] in pure if negated then E.Expr {span = s, node = E.EUnary E.Unary {op = E.OpNot, operand = paren contained}} else contained callExpr :: Span -> PyExpr -> [Argument] -> D E.Expr callExpr s f args = do classes <- gets (.classes) modules <- gets (.modules) importedNames <- gets (.importedFrom) protectedObjs <- gets (.protectedObjects) own <- gets (\st -> Set.union (Map.keysSet st.moduleTypes.results) st.moduleTypes.classNames) enumClasses <- gets (.enums) procedureParams <- gets (\st -> Map.fromList [(g, ps) | (g, ps) <- Map.toList st.functionParameters, Map.member g st.procedureFunctions]) case (f.node, args) of -- Python's builtins that Vibe excludes by design (D174), each refused with why (NameRef q, _) | Just why <- lookup q excludedBuiltins, not (Set.member q own), not (Map.member q importedNames) -> do mapM_ (expr . (.value)) args nameE s "Integer" <$ reject f.span why "not in Vibe" -- `Color(3)`: the member of an `Enum` class whose value it is (a literal, here) (NameRef c, [Argument {keyword = Nothing, value = v}]) | Just members <- Map.lookup c enumClasses -> do written <- gets (Map.lookup c . (.enumValues)) case (v.node, written) of (_, Just vals) | Just n <- lookup (literalKey v) [(literalKey x, m) | (m, x) <- vals] -> expr PyExpr {span = s, node = Attribute f n} _ | literalKey v /= "" -> nameE s "Integer" <$ reject v.span ("`" <> c <> "` has no member of this value (Python's ValueError): its members are " <> Text.intercalate ", " members) "no such member" _ -> callExpr s PyExpr {span = f.span, node = NameRef ("Verada_" <> c <> "_Of_Value")} args -- (a function that is a procedure underneath, called with fewer arguments than it has -- parameters: with its defaults, so that its `out` result, last, is not taken for a -- defaulted one) (NameRef g, _) | Just ps <- Map.lookup g procedureParams , length args < length ps , all (isNothing . (.keyword)) args , Just defaults <- mapM snd (drop (length args) ps) -> callExpr s f (args <> [Argument {keyword = Nothing, value = d} | d <- defaults]) -- Named actuals need the same completion. Append only omitted defaults, keeping -- supplied expressions in their written order. Malformed actual lists stay intact -- for normal duplicate/unknown/missing-argument diagnostics. (NameRef g, _) | Just ps <- Map.lookup g procedureParams , length args < length ps , let (positional, named) = span (isNothing . (.keyword)) args , not (null named) , all (isJust . (.keyword)) named , let supplied = map fst (take (length positional) ps) <> mapMaybe (.keyword) named , length supplied == length (nub supplied) , all (`elem` map fst ps) supplied , Just defaults <- mapM (\(n, d) -> (n,) <$> d) [(n, d) | (n, d) <- ps, n `notElem` supplied] -> callExpr s f (args <> [Argument {keyword = Just n, value = d} | (n, d) <- defaults]) (NameRef "max", [a, b]) -> choose E.OpGe a.value b.value (NameRef "min", [a, b]) -> choose E.OpLe a.value b.value -- `min(f(x) for x in xs)` and the others of a generator, or of a comprehension: of the -- list it gives (Python's `min` of none raises ValueError: the list's `min` requires one) (NameRef q, [Argument {keyword = Nothing, value = v}]) | q `elem` ["min", "max", "sorted", "list"] , not (Set.member q own) , Just listed <- asList v -> do t <- pyType listed case t of Just lt@(PList _) -> do x <- expr listed mark <- typeExpr (typeAnnotation s lt) let qualified = E.Expr {span = s, node = E.EQualified E.Qualified {mark, operand = x}} pure if q == "list" then qualified else form s (E.FormMethod (ident f.span q) []) [qualified] _ -> nameE s "Integer" <$ reject v.span ("`" <> q <> "` of a generator takes the list it gives, and the annotations here do not say its elements' type: declare the list first, `ys: list[int] = [...]`, then `" <> q <> "(ys)`") "element type unknown" -- `sep.join(f(x) for x in xs)`: of the list of texts it gives (Attribute _ "join", [Argument {keyword = Nothing, value = PyExpr {node = GeneratorExp e cs, span = vs}}]) -> callExpr s f [Argument {keyword = Nothing, value = PyExpr {span = vs, node = ListComp e cs}}] -- `min(xs)`, `max(xs)`, `sorted(xs)` and `reversed(xs)` of one list: its operations (by -- the order of its elements, Python's `<`, for the first three) (NameRef q, [Argument {keyword = Nothing, value = v}]) | q `elem` ["min", "max", "sorted", "reversed"] , not (isGenerator v) -> do t <- pyType v case t of -- (`sorted(s)` of a set: its elements in order, an ordered set's own, as a list) Just (PSet _) | q == "sorted" -> do element <- freshName "Verada_Element_" let named = PyExpr {span = v.span, node = NameRef element} callExpr s f [Argument {keyword = Nothing, value = PyExpr {span = v.span, node = ListComp named [Comprehension {target = named, source = v, conditions = []}]}}] _ -> do x <- expr v pure (form s (E.FormMethod (ident f.span q) []) [x]) -- `list(reversed(xs))`: the reversed list (NameRef "list", [Argument {keyword = Nothing, value = v@PyExpr {node = Call PyExpr {node = NameRef "reversed"} [_]}}]) -> expr v -- `all(xs)` and `any(xs)` of a list of `bool`: whether all (or any) of its elements are -- true (NameRef q, [Argument {keyword = Nothing, value = v}]) | q `elem` ["all", "any"] , not (isGenerator v) -> let item = PyExpr {span = v.span, node = NameRef "Verada_Item"} in quantified s (q == "all") item Comprehension {target = item, source = v, conditions = []} -- `sum(xs, start)`: the sum after start, as Python adds them (NameRef "sum", [a, Argument {value = start}]) | a.keyword == Nothing -> do total <- callExpr s f [a] from <- expr start pure (paren (binary s E.OpAdd (paren from) (paren total))) -- `round(x)` of a float: the nearest int, a half to the even one; of an int, itself; -- `round(x, n)`: x at n digits (Verada.Vibe.Floats) (NameRef "round", [Argument {keyword = Nothing, value = v}]) | not (Set.member "round" own) -> do t <- pyType v x <- expr v if t == Just PInt then pure x else do needs ["Verada", "Vibe", "Floats"] pure (call s ["Verada", "Vibe", "Floats", "Round"] [x]) (NameRef "round", [Argument {keyword = Nothing, value = v}, Argument {value = n}]) | not (Set.member "round" own) -> do t <- pyType v x <- expr v k <- expr n if t == Just PInt then nameE s "Integer" <$ reject s "`round(x, n)` of an int is an int rounded at n digits: Vibe takes it of a float (`round(float(x), n)`), or write the arithmetic" "an int" else do needs ["Verada", "Vibe", "Floats"] pure (call s ["Verada", "Vibe", "Floats", "Round_Digits"] [x, k]) -- `divmod(a, b)`: the tuple `(a // b, a % b)` (of names or numbers, read twice) (NameRef "divmod", [Argument {keyword = Nothing, value = a}, Argument {keyword = Nothing, value = b}]) | not (Set.member "divmod" own) -> if steadyOperand a && steadyOperand b then do let pair = PyExpr {span = s, node = TupleLit [PyExpr {span = s, node = BinOp "//" a b}, PyExpr {span = s, node = BinOp "%" a b}]} v <- expr pair -- (of the tuple type its operands give, where nothing else says which) pyType pair >>= \case Just t@(PTuple _) -> do mark <- typeExpr (typeAnnotation s t) pure E.Expr {span = s, node = E.EQualified E.Qualified {mark, operand = v}} _ -> pure v else nameE s "Integer" <$ reject s "`divmod` reads its operands twice in Vibe: name them first (`q, r = divmod(a, b)` of names or numbers)" "not named" (NameRef "abs", [a]) -> do v <- expr a.value pure E.Expr {span = s, node = E.EUnary E.Unary {op = E.OpAbs, operand = v}} -- `Owned(Node(...))`: a new object on the heap, owned by what takes it (NameRef r, [Argument {keyword = Nothing, value = v}]) | r `elem` ["Owned", "Ref"] -> do x <- expr v let allocated = E.Expr {span = s, node = E.EAllocator (E.AllocateQualified x)} -- (an enclave's `Ref(C(...))` of a class of its own: of C's access type, where nothing -- else says which, EU2) pure case v.node of Call PyExpr {node = NameRef c} _ | r == "Ref", Map.member c classes -> E.Expr {span = s, node = E.EQualified E.Qualified {mark = nameE s ("Owned_" <> c), operand = allocated}} _ -> allocated -- `copy(x)`: a copy, which is what Vibe makes of a value anyway (design C asks for it) (NameRef "copy", [Argument {keyword = Nothing, value = v}]) -> expr v -- `replace(x, f=v)`: Python's `dataclasses.replace`, a copy of the dataclass value x -- with the fields given changed, Ada's delta aggregate `(X with delta F => V)` (NameRef "replace", Argument {keyword = Nothing, value = b} : changes@(_ : _)) | not (Map.member "replace" importedNames) , all (isJust . (.keyword)) changes -> do base <- expr b assocs <- forM changes \a -> do v <- expr a.value pure (E.NamedAssocNode E.NamedAssoc {span = a.value.span, choices = [E.ChoiceExpr (nameE a.value.span (fromMaybe "" a.keyword))], value = E.AssocExpr v}) pure E.Expr {span = s, node = E.EAggregate E.Aggregate {bracket = False, contents = E.DeltaAggregateContents E.DeltaAggregate {base, associations = assocs}}} -- `move(x)`: Verada moves an owner where it is assigned (NameRef "move", [Argument {keyword = Nothing, value = v}]) -> expr v (NameRef "deref", [Argument {keyword = Nothing, value = v}]) -> (\x -> E.Expr {span = s, node = E.EDereference x}) <$> expr v -- `float(n)`: Python's float, a double (NameRef "float", [Argument {keyword = Nothing, value = v}]) -> do x <- expr v pure E.Expr {span = s, node = E.EApply E.Apply {prefix = nameE f.span "Long_Float", arguments = [E.Argument {span = x.span, formal = Nothing, value = E.ArgExpr x, reference = Nothing}], bracketed = Nothing}} -- `int(x)`: an integer's value, or a float truncated as Python truncates it -- `int("42")` of a literal: its value, as Python reads it (or Python's ValueError) (NameRef "int", [Argument {keyword = Nothing, value = PyExpr {node = StrLit t}}]) -> case pythonInt t of Just k | k >= -(2 ^ (63 :: Int)), k < 2 ^ (63 :: Int) -> pure E.Expr {span = s, node = E.EInteger k} Just _ -> E.Expr {span = s, node = E.EInteger 0} <$ reject s "this number is beyond Vibe's `int`, whose values are 64-bit" "too large" Nothing -> E.Expr {span = s, node = E.EInteger 0} <$ reject s ("Python's `int()` does not read " <> Text.pack (show t) <> " (it raises ValueError): write the digits, with an optional sign and spaces around") "not an integer" -- `is_int(s)` (`verada`'s): whether `int(s)` reads the text, its precondition (NameRef "is_int", [Argument {keyword = Nothing, value = v}]) -> do needs ["Verada", "Vibe", "Formatting"] x <- expr v pure (call s ["Verada", "Vibe", "Formatting", "Is_Integer_Text"] [x]) (NameRef "int", [Argument {keyword = Nothing, value = v}]) -> do -- (of a str: its value, by Verada.Vibe.Formatting) needs ["Verada", "Vibe", "Formatting"] x <- expr v pure (form s E.FormInt [x]) -- `div(a, b)` and `rem(a, b)` (`verada`'s): Ada's integer division, which truncates -- toward zero (Python's `//` floors), and its remainder, which takes a's sign (NameRef o, [Argument {keyword = Nothing, value = a}, Argument {keyword = Nothing, value = b}]) | Just op <- lookup o [("div", E.OpDiv), ("rem", E.OpRem)] -> do l <- expr a r <- expr b pure (paren (binary s op (paren l) (paren r))) -- `len(Color)` of an `Enum` class: how many members it has (NameRef "len", [Argument {keyword = Nothing, value = PyExpr {node = NameRef c}}]) | Just members <- Map.lookup c enumClasses -> pure E.Expr {span = s, node = E.EInteger (toInteger (length members))} -- `len(grid[i])` of a list of lists: the row's length (NameRef "len", [Argument {keyword = Nothing, value = PyExpr {node = Subscript g [i]}}]) | not (isSlice i) -> nestedList g >>= \case True -> do grid <- expr g ri <- fromOne i pure (form s (E.FormMethod (ident f.span "Row_Length") []) [grid, ri]) False -> lenOf (NameRef "len", [_]) -> lenOf -- `m.first_index(k)`, `m.last_index(k)`: the bounds of an array's dimension k (from 0) (Attribute p m, [Argument {keyword = Nothing, value = PyExpr {node = IntLit k}}]) | Just bound <- lookup m [("first_index", "First"), ("last_index", "Last")] , k >= 0 -> do prefix <- expr p pure E.Expr {span = s, node = E.EAttribute E.AttributeRef {prefix, designator = ident f.span bound, arguments = [E.Expr {span = s, node = E.EInteger (k + 1)}]}} -- `image(x)`: Ada's image, `X'Image` (a number's with its leading blank) (NameRef "image", [Argument {keyword = Nothing, value = v}]) -> do x <- expr v -- (a Python string: a text where one is wanted) pythonString s (attribute s x "Image") -- `repr(x)`: Python's repr; `format(x, spec)` of a literal spec, as an f-string's field (NameRef "repr", [Argument {keyword = Nothing, value = v}]) -> do needs ["Verada", "Vibe", "Formatting"] modify' \st -> st {usesPrint = True} wholeRows v x <- expr v pythonString s (reprOf s x) (NameRef "format", [Argument {keyword = Nothing, value = v}, Argument {keyword = Nothing, value = PyExpr {node = StrLit t}}]) -> do x <- expr v formatWith s x t >>= pythonString s (NameRef "str", [a]) -> do modify' \st -> st {usesPrint = True} wholeRows a.value v <- expr a.value pythonString s (imageOf s v) -- (the name of the exception a `with` statement's body raised, for `__exit__`: Vibe's -- own, which no program writes, Verada.Vibe.With) (NameRef "Verada_Exception_Name", [Argument {keyword = Nothing, value = PyExpr {node = NameRef o, span = os}}]) | "Verada_Exception_" `Text.isPrefixOf` o -> do modify' \st -> st {bindsOccurrences = True} pythonString s (call s ["Ada", "Exceptions", "Exception_Name"] [nameE os o]) -- `super().m(args)` in a method: the parent's m, on self as the parent (a view -- conversion, so the parent's own operation is called, as Python's `super()` does) (Attribute PyExpr {node = Call PyExpr {node = NameRef "super", span = sp} []} m, _) -> do parent <- gets (.parentClass) case parent of Nothing -> nameE s "Integer" <$ reject sp "`super()` is taken in a method of a class derived from another, for the parent's operation" "no parent" Just p -> do vs <- mapM (expr . (.value)) args let object = E.Expr {span = sp, node = E.EApply E.Apply {prefix = nameE sp p, arguments = [E.Argument {span = sp, formal = Nothing, value = E.ArgExpr (nameE sp "self"), reference = Nothing}], bracketed = Nothing}} named = [ident a.value.span k | a@Argument {keyword = Just k} <- args] pure (form s (E.FormMethod (ident f.span m) named) (object : vs)) -- `Point(1, 2)`: a dataclass's fields by position, in their order (its parent's first) (NameRef c, _ : _) | Map.lookup c classes `elem` [Just RecordClass, Just TaggedClass] , any (isNothing . (.keyword)) args -> do fields <- gets (Map.findWithDefault [] c . (.fieldNames)) let (positional, named) = span (isNothing . (.keyword)) args forM_ (take 1 [a | a <- named, isNothing a.keyword]) \a -> reject a.value.span "an argument by position comes before those by name, as in Python" "after one by name" if length positional > length fields then nameE s "Integer" <$ reject s ("`" <> c <> "` has " <> Text.pack (show (length fields)) <> " fields, and this gives " <> Text.pack (show (length positional)) <> " by position") "too many" else callExpr s f ([Argument {keyword = Just k, value = a.value} | (k, a) <- zip fields positional] <> named) -- `buffer.put(x)` of a protected object: its operation, by name (Attribute p@PyExpr {node = NameRef o} m, _) | Set.member o protectedObjs -> do prefix <- expr p vs <- mapM (expr . (.value)) args pure E.Expr {span = s, node = E.EApply E.Apply {prefix = E.Expr {span = f.span, node = E.ESelected E.Selected {prefix, selector = E.SelectIdentifier (ident f.span m)}}, arguments = [E.Argument {span = v.span, formal = Nothing, value = E.ArgExpr v, reference = Nothing} | v <- vs], bracketed = Nothing}} -- `x.m(args)`, where `x` is not an imported module: an operation of x's type -- `s.ljust(w)`, `s.rjust(w)`, `s.center(w)` of a str: padded with spaces, Python's fill (Attribute p m, [w]) | m `elem` ["ljust", "rjust", "center"], isNothing w.keyword -> do t <- pyType p if t == Just PStr then callExpr s f [w, Argument {keyword = Nothing, value = PyExpr {span = f.span, node = StrLit " "}}] else method p m -- `"{}-{}".format(a, b)` of a literal: the f-string it means (Attribute PyExpr {node = StrLit template, span = ts} "format", _) | all (isNothing . (.keyword)) args -> case formatFields ts template (map (.value) args) of Right parts -> expr PyExpr {span = s, node = FString parts} Left why -> nameE s "Integer" <$ reject ts why "format" -- `ord(c)` and `chr(n)`: a character's code point, and the character at one (NameRef q, [Argument {keyword = Nothing, value = v}]) | Just op <- lookup q [("ord", "Ord"), ("chr", "Chr")], not (Set.member q own) -> do modify' \st -> st {usesText = True} needs ["Verada", "Strings", "Text_Operations"] x <- expr v let result = call s ["Verada", "Strings", "Text_Operations", op] [x] if q == "chr" then pythonString s result else pure result -- a set's methods by name: its operators (`s.issubset(t)` is `s <= t`) (Attribute p m, [Argument {keyword = Nothing, value = o}]) | Just op <- lookup m setOperators -> do t <- pyType p case t of Just (PSet _) -> case op of "isdisjoint" -> expr PyExpr {span = s, node = Compare PyExpr {span = s, node = Call PyExpr {span = s, node = NameRef "len"} [Argument {keyword = Nothing, value = PyExpr {span = s, node = BinOp "&" p o}}]} [("==", PyExpr {span = s, node = IntLit 0})]} _ | op `elem` ["<=", ">="] -> expr PyExpr {span = s, node = Compare p [(op, o)]} _ -> expr PyExpr {span = s, node = BinOp op p o} _ -> method p m -- `grid[i].append(x)` of a list of lists: x at the end of the row (Attribute PyExpr {node = Subscript g [i]} "append", [Argument {keyword = Nothing, value = x}]) | not (isSlice i) -> nestedList g >>= \case True -> do grid <- expr g ri <- fromOne i v <- expr x pure (form s (E.FormMethod (ident f.span "Append") []) [grid, ri, v]) False -> method PyExpr {span = f.span, node = Subscript g [i]} "append" (Attribute p m, _) | not (throughModule modules classes p) -> method p m (NameRef q, [a]) | q `elem` ["all", "any"], GeneratorExp p [c] <- a.value.node -> quantified s (q == "all") p c -- `sum(f(x) for x in xs if c)` and `sum(xs)`: a reduction (T25b), from 0 (NameRef "sum", [a]) | GeneratorExp v [c] <- a.value.node -> summed E.ConsumeCompensatedSum s v c -- `sum([f(x) for x in xs if c])` is the generator's sum, and `sum([a, b, c])` the sum of -- the list's values (the list is never kept, so it needs no type of its own) (NameRef "sum", [a]) | ListComp v [c] <- a.value.node, isNothing a.keyword -> summed E.ConsumeCompensatedSum s v c (NameRef "sum", [a]) | ListLit xs <- a.value.node, isNothing a.keyword -> summedValues E.ConsumeCompensatedSum s xs (NameRef "sum", [a]) | isNothing a.keyword -> summed E.ConsumeCompensatedSum s PyExpr {span = a.value.span, node = NameRef "Verada_Item"} Comprehension {target = PyExpr {span = a.value.span, node = NameRef "Verada_Item"}, source = a.value, conditions = []} -- `apl("...")` or `apl(r"...")` (apl-variant.md 5.4): APL text, read as in the other -- syntaxes; the string as written (raw where it holds APL's `\`), so its spans are the -- file's (NameRef "apl", [Argument {keyword = Nothing, value = PyExpr {node = StrLit t, span = ts}}]) | Text.length t > 0 , Just opening <- lookup (ts.end - ts.start - ByteString.length (encodeUtf8 t)) [(2, 1), (3, 2)] -> pure E.Expr {span = s, node = E.ECodeString E.CodeString {language = "apl", code = t, codeSpan = ts {start = ts.start + opening, end = ts.end - 1}}} (NameRef "apl", _) -> do reject s "`apl` takes one string written plainly, or raw (`r\"...\"`): no escapes or triple quotes" "not plain APL text" pure E.Expr {span = s, node = E.EInteger 0} -- `accumulate(xs)` (itertools'): the running sums, one for each element, Verada's scan -- (apl-variant.md 8.4) (NameRef "accumulate", [a]) | isNothing a.keyword -> do v <- expr a.value pure E.Expr {span = s, node = E.EPipeline (pipelineOver v (E.ConsumeScan E.Expr {span = s, node = E.EString "+"} E.Expr {span = s, node = E.EInteger 0}))} -- (`verada`'s lane sum, AP21) -- `plain_sum(xs)`: Ada's sum of floats, left to right from 0.0, rounding at each step -- (Python's `sum` of floats is compensated) (NameRef "plain_sum", [a]) | GeneratorExp v [c] <- a.value.node -> summed plainSum s v c (NameRef "plain_sum", [a]) | isNothing a.keyword -> summed plainSum s PyExpr {span = a.value.span, node = NameRef "Verada_Item"} Comprehension {target = PyExpr {span = a.value.span, node = NameRef "Verada_Item"}, source = a.value, conditions = []} (NameRef "lane_sum", [a]) | GeneratorExp v [c] <- a.value.node -> summed E.ConsumeLaneSum s v c (NameRef "lane_sum", [a]) | isNothing a.keyword -> summed E.ConsumeLaneSum s PyExpr {span = a.value.span, node = NameRef "Verada_Item"} Comprehension {target = PyExpr {span = a.value.span, node = NameRef "Verada_Item"}, source = a.value, conditions = []} -- an array class applied to a list, or a record class to its fields: an aggregate (NameRef c, [Argument {keyword = Nothing, value = PyExpr {node = ListLit xs}}]) | Map.lookup c classes == Just ArrayClass -> do vs <- mapM expr xs pure (qualify c E.Expr {span = s, node = E.EAggregate E.Aggregate {bracket = False, contents = E.PlainAggregate (E.Associations (map E.PositionalAssoc vs))}}) -- (`Row([v for x in xs if c])`: the array of the comprehension's values) (NameRef c, [Argument {keyword = Nothing, value = PyExpr {node = ListComp v [cl], span = ls}}]) | Map.lookup c classes == Just ArrayClass -> qualify c <$> comprehensionAggregate ls v cl (NameRef c, _) | Map.lookup c classes `elem` [Just RecordClass, Just TaggedClass], all (isJust . (.keyword)) args -> do assocs <- forM args \a -> do -- (an empty container for a field is the field's own, empty: `<>`) v <- if emptyContainer a.value then pure E.AssocBox else E.AssocExpr <$> expr a.value pure (E.NamedAssocNode E.NamedAssoc {span = a.value.span, choices = [E.ChoiceExpr (nameE a.value.span (maybe "" id a.keyword))], value = v}) -- (the fields not given take their defaults, as a dataclass's do) fields <- gets (Map.findWithDefault [] c . (.fieldNames)) let given = [k | Argument {keyword = Just k} <- args] defaulted = [E.NamedAssocNode E.NamedAssoc {span = s, choices = [E.ChoiceOthers s], value = E.AssocBox} | any (`notElem` given) fields] pure (qualify c E.Expr {span = s, node = E.EAggregate E.Aggregate {bracket = False, contents = E.PlainAggregate (E.Associations (assocs <> defaulted))}}) -- `C([...])` of a class the module does not declare (another module's array class, or -- one named through its module, `m.C`): an aggregate of it, or a call, as Sema finds C -- to be (_, [Argument {keyword = Nothing, value = PyExpr {node = ListLit xs}}]) | Just c <- otherClass modules f , not (Map.member c classes) , Just (h, _) <- Text.uncons c , isUpper h -> do prefix <- expr f vs <- mapM expr xs pure (form s (E.FormConstruct []) [prefix, E.Expr {span = s, node = E.EAggregate E.Aggregate {bracket = False, contents = E.PlainAggregate (E.Associations (map E.PositionalAssoc vs))}}]) -- `C(a, b)` of a class another module declares (imported by name, or `m.C(a, b)`): a -- record's values in its fields' order, or a call, as Sema finds C to be (_, _ : _ : _) | Just c <- otherClass modules f , not (Map.member c classes) , Just (h, _) <- Text.uncons c , isUpper h , all (isNothing . (.keyword)) args , case f.node of NameRef n -> Map.member n importedNames _ -> True -> do prefix <- expr f vs <- mapM (constructValue . (.value)) args pure (form s (E.FormConstruct []) (prefix : vs)) -- `C(f=v)` of a name the module does not declare (or `m.C(f=v)`): a value of a record -- type, or a call, as Sema finds C to be (_, _ : _) | Just c <- otherClass modules f, all (isJust . (.keyword)) args, not (Map.member c classes) -> do prefix <- expr f vs <- mapM (constructValue . (.value)) args pure (form s (E.FormConstruct [ident a.value.span (fromMaybe "" a.keyword) | a <- args]) (prefix : vs)) _ -> do prefix <- expr f arguments <- forM args \a -> do v <- expr a.value pure E.Argument {span = a.value.span, formal = ident a.value.span <$> a.keyword, value = E.ArgExpr v, reference = Nothing} pure E.Expr {span = s, node = E.EApply E.Apply {prefix, arguments, bracketed = Nothing}} where lenOf = case args of [a] -> do v <- expr a.value pure (form s E.FormLength [v]) _ -> pure (nameE s "Integer") -- (a generator or a comprehension, as the comprehension) asList v = case v.node of GeneratorExp e cs -> Just PyExpr {span = v.span, node = ListComp e cs} ListComp _ _ -> Just v _ -> Nothing method p m = do -- (`s.split()` gives a list of texts, whose package the unit then names) when (m `elem` ["split", "rsplit", "splitlines"]) (needs ["Verada", "Strings", "Text_Lists"]) object <- expr p vs <- mapM (expr . (.value)) args -- (by name after those by position, as Python requires) let named = [ident a.value.span k | a@Argument {keyword = Just k} <- args] forM_ (take 1 [a | a <- dropWhile (isNothing . (.keyword)) args, isNothing a.keyword]) \a -> reject a.value.span "an argument by position comes before those by name, as in Python" "after one by name" -- (a context manager's own operations are called by their names too, D176) let operation = fromMaybe m (lookup m [("__enter__", "Verada_Enter"), ("__exit__", "Verada_Exit")]) pure (form s (E.FormMethod (ident f.span operation) named) (object : vs)) isGenerator v = case v.node of GeneratorExp _ _ -> True _ -> False qualify c v = E.Expr {span = s, node = E.EQualified E.Qualified {mark = nameE s c, operand = v}} -- `max(a, b)`: whichever is not less, as an expression any ordered type has choose op a b = do l <- expr a r <- expr b pure E.Expr {span = s, node = E.EParen E.Expr {span = s, node = E.EIf E.IfExpr {condition = binary s op l r, thenValue = l, elsifs = [], elseValue = Just r}}} -- | Python's special methods Vibe takes, with the operation each is (the operator Ada calls, -- or the operation a Vibe form calls: `len(x)` a `Length`, `x[k]` a `Value`, `k in x` a -- `Contains`, `str(x)` and `repr(x)` Vibe's own). specialMethods :: [(Text, Text)] specialMethods = [ ("__str__", "Verada_Str"), ("__repr__", "Verada_Repr") , ("__eq__", "="), ("__lt__", "<"), ("__le__", "<="), ("__gt__", ">"), ("__ge__", ">=") , ("__add__", "+"), ("__sub__", "-"), ("__mul__", "*"), ("__truediv__", "/"), ("__neg__", "-"), ("__abs__", "abs") , ("__len__", "Length"), ("__getitem__", "Value"), ("__setitem__", "Include"), ("__contains__", "Contains") ] -- | Whether Vibe shows a class's repr: each of its fields' types has one (Python's own types, -- the module's classes whose fields do, its `Enum`s), so that a dataclass's repr can be made. reprShown :: Text -> D Bool reprShown c0 = do st <- get let env = st.moduleTypes go seen c | Set.member c seen = True | Map.member c st.enums = True -- (a dataclass the module has declared so far; not another class, a `RangeInt`'s) | not (Map.member c st.fieldNames) = False | otherwise = case Map.lookup c env.fieldTypes of Nothing -> False Just _ -> -- (its fields with its parents', which it has too) let own = Map.findWithDefault [] c st.fieldNames fs = Map.unions (Map.elems env.fieldTypes) in all (\f -> maybe False (shownType (Set.insert c seen)) (Map.lookup f fs)) own shownType seen = \case PInt -> True PFloat -> True PBool -> True PStr -> True -- (a collection's elements by Python's own types: a class's repr in one is not -- found by its name inside its own module) PList t -> plain t PSet t -> plain t PDict k v -> plain k && plain v PTuple ts -> all plain ts PNamed n -> n `elem` ["Natural", "Positive"] || go seen n plain = \case PTuple ts -> all plain ts t -> t `elem` [PInt, PFloat, PBool, PStr] pure (go Set.empty c0) -- | Python's built-in exceptions Vibe names, each with its parent in Python's hierarchy -- (`Exception` at the top) and the exception it is: Verada.Vibe's, or Ada's for those Ada -- raises (a failed `assert`, memory). builtinExceptions :: Map Text (Text, [Text]) builtinExceptions = Map.fromList ( [ ("AssertionError", ("Exception", ["Ada", "Assertions", "Assertion_Error"])) , ("MemoryError", ("Exception", ["Storage_Error"])) ] <> [(n, (parent, ["Verada", "Vibe", n])) | (n, parent) <- hierarchy] ) where hierarchy = [ ("ArithmeticError", "Exception"), ("ZeroDivisionError", "ArithmeticError"), ("OverflowError", "ArithmeticError"), ("FloatingPointError", "ArithmeticError") , ("LookupError", "Exception"), ("IndexError", "LookupError"), ("KeyError", "LookupError") , ("ValueError", "Exception"), ("UnicodeError", "ValueError"), ("TypeError", "Exception"), ("AttributeError", "Exception"), ("NameError", "Exception"), ("EOFError", "Exception") , ("RuntimeError", "Exception"), ("NotImplementedError", "RuntimeError"), ("RecursionError", "RuntimeError"), ("StopIteration", "Exception") , ("OSError", "Exception"), ("PermissionError", "OSError"), ("FileNotFoundError", "OSError"), ("TimeoutError", "OSError") ] -- | Python's builtins that Vibe leaves out by design (D174: evaluation of code, reflection, -- dynamic typing, identity), with the reason and the Vibe way. excludedBuiltins :: [(Text, Text)] excludedBuiltins = [(q, evaluation) | q <- ["eval", "exec", "compile", "__import__"]] <> [(q, reflection q) | q <- ["getattr", "setattr", "hasattr", "delattr", "vars", "dir", "globals", "locals"]] <> [ ("isinstance", "`isinstance` tests a value's class when the program runs, and Vibe's types are static (D174): `match` on a union or a class-wide value (`match s: case Circle(r=r): ...`), or give each class the method that differs") , ("issubclass", "`issubclass` asks about classes when the program runs, and Vibe's types are static (D174): the class hierarchy is fixed where the classes are declared") , ("type", "`type(x)` gives a value's class when the program runs, and Vibe's types are static (D174): `match` on a union or a class-wide value; for the class's name in text, give the class a method or `__str__`") , ("id", "`id(x)` is an object's identity, and Vibe's values have none (D174): compare values with `==`, and an owner with `is None`") , ("open", "Vibe's files are Verada's: import `ada.text_io` and use its `File_Type`, `Open`, `Get_Line` and `Put_Line`") ] where evaluation = "evaluating text as code when the program runs is not in Vibe (D174): no proof can see code that is not written down; write the operation as an ordinary typed function" reflection q = "`" <> q <> "` names a field or a scope by a string when the program runs, reflection, which Vibe's static types cannot check (D174): name the field itself (`p.x`), or keep the values in a `dict`" -- | The value Python's `int()` reads from a text: spaces around, a sign, and decimal digits -- with single underscores between them. pythonInt :: Text -> Maybe Integer pythonInt t0 = do let t = Text.strip t0 (negative, digits) <- case Text.uncons t of Just ('-', r) -> Just (True, r) Just ('+', r) -> Just (False, r) _ -> Just (False, t) let groups = Text.splitOn "_" digits if not (null groups) && all (\g -> not (Text.null g) && Text.all isAsciiDigit g) groups then let v = foldl (\a c -> 10 * a + toInteger (ord c - ord '0')) 0 (Text.unpack (Text.concat groups)) in Just (if negative then negate v else v) else Nothing where isAsciiDigit c = c >= '0' && c <= '9' -- | A class's name as a call names it: `C`, or `m.C` through an imported module. otherClass :: Set Text -> PyExpr -> Maybe Text otherClass modules f = case f.node of NameRef c -> Just c -- (a class: a module's function called by name stays a call) Attribute PyExpr {node = NameRef m} c | Set.member m modules, maybe False (isUpper . fst) (Text.uncons c) -> Just c _ -> Nothing -- | Whether a name is through an imported module or a class (`algorithms.gcd`, -- `Colour.of`), rather than an object whose method is called. throughModule :: Set Text -> Map Text ClassKind -> PyExpr -> Bool throughModule modules classes p = case p.node of NameRef n -> Set.member n modules || Map.member n classes Attribute q _ -> throughModule modules classes q _ -> False -- | @all(p for x in xs)@ and @any(...)@: quantified expressions. quantified :: Span -> Bool -> PyExpr -> Comprehension -> D E.Expr quantified s universal p c = generatorIterator s c >>= \case -- (over sources in step, or until a `takewhile` stops: a pipeline, which Vada writes as -- the reduction of the predicate by `and` or `or`) Just it | not (null it.alongside) || isJust it.whileCondition -> do predicate <- expr p let quantifier = if universal then E.ForAll else E.ForSome fn b = E.StageFn {binder = it.parameter, body = b} stages = [E.StageFilter (fn f) | Just f <- [it.filter]] <> [E.StageTakeWhile (fn w) | Just w <- [it.whileCondition]] pure E.Expr {span = s, node = E.EPipeline E.Pipeline {source = E.PipeSource {domain = it.domain, reverse = it.reverse, subtype = Nothing, alongside = it.alongside}, stages, consumer = E.ConsumeQuantified quantifier (fn predicate), piped = False}} Just it -> do predicate <- expr p pure E.Expr {span = s, node = E.EParen E.Expr {span = s, node = E.EQuantified E.Quantified {quantifier = if universal then E.ForAll else E.ForSome, iterator = it, predicate}}} Nothing -> pure (nameE s "True") -- | Python's `sum` of a generator (or of an iterable, its items): `[for x of xs [when c] => -- v]'Reduce ("+", 0)`, a value sequence's reduction, which Sema types and lowering proves -- with its generated bound (T25b). plainSum :: E.PipeConsumer plainSum = E.ConsumeReduce (E.Expr {span = noSpan, node = E.EString "+"}) (E.Expr {span = noSpan, node = E.EReal 0}) where noSpan = Span {file = FileId 0, start = 0, end = 0} summed :: E.PipeConsumer -> Span -> PyExpr -> Comprehension -> D E.Expr summed consumer s v c = generatorIterator s c >>= \case Just it -> do value <- expr v let sequence' = E.Expr {span = s, node = E.EAggregate E.Aggregate {bracket = True, contents = E.PlainAggregate (E.Associations [E.IteratedAssocNode E.IteratedAssoc {span = s, iterator = it, value}])}} -- (Python's `sum` of floats is compensated, D144: of integers, the plain sum) pure E.Expr {span = s, node = E.EPipeline (pipelineOver sequence' consumer)} Nothing -> pure (nameE s "0") -- | Python's `sum` of a list's values, `sum([a, b, c])`: the reduction of the value at each -- position, `[for K in 0 .. 2 => (if K = 0 then a elsif K = 1 then b else c)]`, each -- evaluated once and added in order, as Python's `sum` adds them (0 for none). summedValues :: E.PipeConsumer -> Span -> [PyExpr] -> D E.Expr summedValues consumer s xs = case mapM numberOf xs of -- (numbers written out: the sum Python computes, here, as CPython adds them) Just ns | Just total <- pythonSum ns -> pure total _ -> do vs <- mapM expr xs k <- freshName "Verada_Position_" let int n = E.Expr {span = s, node = E.EInteger n} at n = binary s E.OpEq (nameE s k) (int n) case reverse vs of [] -> pure (int 0) final : earlier -> let chosen = case reverse earlier of [] -> final first : others -> paren E.Expr {span = s, node = E.EIf E.IfExpr {condition = at 0, thenValue = first, elsifs = [E.ElsifValue {condition = at n, value = v} | (n, v) <- zip [1 ..] others], elseValue = Just final}} iterator = E.Iterator {parameter = ident s k, subtype = Nothing, reverse = False, domain = E.InRange (E.DiscreteBounds E.RangeExpr {span = s, low = int 0, high = int (toInteger (length vs) - 1)}), filter = Nothing, whileCondition = Nothing, alongside = []} sequence' = E.Expr {span = s, node = E.EAggregate E.Aggregate {bracket = True, contents = E.PlainAggregate (E.Associations [E.IteratedAssocNode E.IteratedAssoc {span = s, iterator, value = chosen}])}} in pure E.Expr {span = s, node = E.EPipeline (pipelineOver sequence' consumer)} where numberOf x = case x.node of IntLit n -> Just (Left n) FloatLit r _ -> Just (Right (fromRational r :: Double)) UnaryOp "-" y -> either (Left . negate) (Right . negate) <$> numberOf y _ -> Nothing -- (CPython's: whole numbers exactly up to the first float, then each added to a -- compensated sum of floats, its correction added at the end when it is finite and not -- zero; a sum that is not a finite float is left to the program) pythonSum ns = case go 0 ns of Left n -> Just (E.Expr {span = s, node = E.EInteger n}) Right d | isNaN d || isInfinite d -> Nothing Right d -> Just (E.Expr {span = s, node = E.EReal (toRational d)}) go :: Integer -> [Either Integer Double] -> Either Integer Double go acc = \case [] -> Left acc Left n : rest -> go (acc + n) rest rest@(Right _ : _) -> Right (compensated (fromInteger acc, 0) rest) compensated (hi, lo) = \case [] -> if lo /= 0 && not (isNaN lo || isInfinite lo) then hi + lo else hi n : rest -> let x = either fromInteger id n t = hi + x lo' = if abs hi >= abs x then lo + ((hi - t) + x) else lo + ((x - t) + hi) in compensated (t, lo') rest -- | A generator's iteration, its `if` conditions its filter. Python's `takewhile` comes -- before a generator's `if`, and Vada's `when C while D` filters first: the `if` keeps the -- elements the `while` stops at. generatorIterator :: Span -> Comprehension -> D (Maybe E.Iterator) generatorIterator s c = iteratorFor c.target c.source >>= \case Just it -> do filters <- mapM expr c.conditions case (it.whileCondition, filters) of -- (the `if` after `takewhile`: an element `takewhile` stops at passes the filter, so -- that the `while` still sees it, `when not W or else C`) (Just w, _ : _) -> let unless' = paren E.Expr {span = s, node = E.EUnary E.Unary {op = E.OpNot, operand = paren w}} afterWhile = binary s E.OpOrElse unless' (paren (fromMaybe w (andAll filters))) in pure (Just E.Iterator {parameter = it.parameter, subtype = it.subtype, reverse = it.reverse, domain = it.domain, filter = andAll (maybe [] pure it.filter <> [afterWhile]), whileCondition = it.whileCondition, alongside = it.alongside}) _ -> pure (Just E.Iterator {parameter = it.parameter, subtype = it.subtype, reverse = it.reverse, domain = it.domain, filter = andAll (maybe [] pure it.filter <> filters), whileCondition = it.whileCondition, alongside = it.alongside}) Nothing -> pure Nothing where andAll = \case [] -> Nothing x : xs -> Just (foldl (binary s E.OpAndThen) x xs) -- | @[v for x in range(...)]@: an iterated array aggregate. comprehensionAggregate :: Span -> PyExpr -> Comprehension -> D E.Expr comprehensionAggregate s v c = case c.source.node of -- (over a range with a step: its values, a filter keeping those on a step) Call PyExpr {node = NameRef "range"} [_, _, _] -> generatorIterator s c >>= \case Just it -> do value <- expr v pure E.Expr {span = s, node = E.EAggregate E.Aggregate {bracket = True, contents = E.PlainAggregate (E.Associations [E.IteratedAssocNode E.IteratedAssoc {span = s, iterator = it, value}])}} Nothing -> pure (nameE s "Integer") _ -> comprehensionOver s v c comprehensionOver :: Span -> PyExpr -> Comprehension -> D E.Expr comprehensionOver s v c = do domain <- case c.source.node of Call PyExpr {node = NameRef "range"} args -> rangeDomain c.source.span args _ -> Just . E.OfContainer <$> expr c.source value <- expr v -- (an `if` filters the elements: the aggregate has those that pass) conditions <- mapM expr c.conditions let kept = case conditions of [] -> Nothing k : ks -> Just (foldl (binary s E.OpAndThen) k ks) case (c.target.node, domain) of (NameRef n, Just d) -> pure E.Expr {span = s, node = E.EAggregate E.Aggregate {bracket = True, contents = E.PlainAggregate (E.Associations [E.IteratedAssocNode E.IteratedAssoc {span = s, iterator = E.Iterator {parameter = ident c.target.span n, subtype = Nothing, reverse = False, domain = d, filter = kept, whileCondition = Nothing, alongside = []}, value}])}} _ -> nameE s "Integer" <$ reject c.target.span "a comprehension\x27s variable is one name" "target"