-- | Statements (Ada RM 5, 6.5, 11.3, SPARK pragmas). Declarations inside blocks are checked -- by the function passed in, which keeps this module independent of the declaration checker. module Verada.Sema.Check.Stmt ( DeclChecker , handlers , hasReturn , isCheckException , statements ) where import Verada.Diagnostics (Diagnostic (..), Label (..), Note (..), Phase (..), diagnostic, label) import Verada.Diagnostics.Codes (DiagCode (..)) import Verada.Sema.Check.Contract (sparkModeOff) import Verada.Sema.Check.Expr import Verada.Sema.Check.Levels (checkLevelReferences) import Verada.Sema.Env import Verada.Sema.Monad import Verada.Sema.Types (compatible, isDiscrete, isLimited, std, typeName) import Verada.Source (Span) import Verada.Syntax.AST.Decl qualified as AD import Verada.Syntax.AST.Expr qualified as A import Verada.Syntax.AST.Stmt qualified as AS import Verada.Syntax.AST.Type qualified as AT import Verada.Syntax.ProcedureResults (lastResultByPosition, resultMark, resultsBlock, resultsCall, tupleResults) import Verada.Syntax.SurfaceForm (resolvedFormExpr, resolvedStore) import Verada.TAST.Decl import Verada.TAST.Expr import Verada.TAST.Ids (DeclId) import Verada.TAST.Stmt import Verada.TAST.Unit (Justification (..)) import Control.Monad (forM, forM_, unless, when) import Control.Monad.Reader (asks, local) import Control.Monad.State.Strict (gets, modify') import Data.Data (Data, cast, gmapQ) import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe, isNothing) import Data.Set qualified as Set import Data.Text qualified as Text type DeclChecker = [AD.Decl] -> Sema [TDecl] statements :: DeclChecker -> [AS.Stmt] -> Sema [TStmt] statements decls ss = do -- a reviewed justification covers the statement before it (G2) forM_ (zip (Nothing : map Just ss) ss) \(previous, s) -> case s.node of AS.SPragma p | A.foldedName p.name == "annotate", Just (pattern, reason) <- justified p -> case previous of Just before -> modify' \st -> st {justifications = Justification {covers = before.span, pattern, reason, at = s.span} : st.justifications} -- (first in its statements: about a declaration, as GNATprove's about a leak is, which -- Verada's proof has no check for) Nothing -> pure () _ -> pure () -- (each after the compatibility checks of the range constraints written in it) concat <$> forM ss \s -> do (t, checks) <- collectCompatibility (statement decls s) pure ([TStmt {span = c.at, node = TCompatibilityStmt c} | c <- checks] <> [t]) where -- `(GNATprove | Verada, False_Positive | Intentional, "pattern", "reason")` justified p = case [a.value | a <- p.arguments] of [A.ArgExpr tool, A.ArgExpr kind, A.ArgExpr A.Expr {node = A.EString pattern}, A.ArgExpr A.Expr {node = A.EString reason}] | name tool `elem` ["gnatprove", "verada"], name kind `elem` ["false_positive", "intentional"] -> Just (pattern, reason) _ -> Nothing name e = case e.node of A.ENameRef i -> A.foldedName i _ -> "" nested :: Sema a -> Sema a nested = local (\c -> c {inLoopBody = False}) statement :: DeclChecker -> AS.Stmt -> Sema TStmt statement decls s = do node <- case s.node of AS.SNull -> pure TNullStmt AS.SError -> pure TErrorStmt AS.SAssign a -> resultsAssignment decls s.span a AS.SCall c -- a surface form's call of a procedure (Vibe's `xs.append(v)`) | A.ESurfaceForm f <- c.node -> formResolution False c.span f >>= \case Just r -> procedureCall (resolvedFormExpr c.span r f) Nothing -> pure TErrorStmt | otherwise -> procedureCall c -- (`delay` statements become calls of Verada.Tasking before analysis) AS.SDelay _ -> reportAt NotYetSupported s.span "a `delay` statement outside a unit that tasking applies to" "not here" >> pure TErrorStmt AS.SIf i -> nested do first <- branch i.condition i.thenPart rest <- forM i.elsifs \e -> branch e.condition e.statements elsePart <- maybe (pure []) (statements decls) i.elsePart pure (TIfStmtNode TIfStmt {branches = first : rest, elsePart}) AS.SCase c -> nested do selector <- selectorExpression c.selector discrete <- isDiscrete selector.typeOf unless discrete do tn <- typeName selector.typeOf reportAt TypeMismatch c.selector.span ("a case selector must be discrete, and this is of type `" <> tn <> "`") "not discrete" othersPlacement CaseCoverage (map (.choices) c.alternatives) alternatives <- forM c.alternatives \alt -> do choices <- mapM (choice selector.typeOf) alt.choices body <- statements decls alt.statements pure (alt.span, TCaseAlternative {choices, statements = body}) selectorSubtype <- subtypeOfExpr selector checkCoverage c.selector.span selectorSubtype [(sp, alt.choices) | (sp, alt) <- alternatives] pure (TCaseStmtNode TCaseStmt {selector, alternatives = map snd alternatives}) AS.SLoop l -> loop l -- (the block's name is declared around it, so that a declaration inside of the same name -- hides it, RM 5.6, 8.1) AS.SBlock b00 -> nested $ withScope BlockScope Nothing False $ (mapM (\n -> labelInBody n >> declare n.text n.span ELabel) b00.label >>=) $ \labelId -> withScope BlockScope Nothing False do depth <- gets (length . (.scopes)) forM_ labelId \d -> modify' \st -> st {labelScopes = Map.insert d depth st.labelScopes} b0 <- resultsDeclared b00 b <- initialisedByFirst decls b0 ds <- maybe (pure []) decls b.declarations body <- statements decls b.statements hs <- handlers decls b.handlers pure (TBlockNode TBlock {declarations = ds, statements = body, handlers = hs}) AS.SExit e -> exit s.span e AS.SReturn v -> returnStatement v AS.SExtendedReturn r -> extendedReturn decls s.span r AS.SRaise r -> raise s.span r AS.SPragma p -> pragmaStatement p pure TStmt {span = s.span, node} where -- (a block's or loop's name is declared in the innermost body's region, at the end of its -- declarative part, RM 5.1(12): not the name of a parameter or declaration of the body) labelInBody n = do scopes <- gets (.scopes) case take 1 [sc | sc <- scopes, sc.kind == SubprogramScope] of sc : _ -> do earlier <- mapM entity (Map.findWithDefault [] (folded n.text) sc.names) forM_ (take 1 [e | e <- earlier, case e.kind of { ELabel -> False; _ -> True }]) \first -> report (diagnostic DuplicateDeclaration Semantic ("`" <> n.text <> "` is already declared in this scope")) { primary = Just (label n.span "declared again here, as a block's or loop's name") , secondary = [Label {span = first.span, text = Just "first declared here"}] } [] -> pure () branch c body = do condition <- boolean c stmts <- statements decls body pure TIfBranch {condition, statements = stmts} loop l = withScope LoopScope Nothing False do labelId <- case l.label of Just n -> labelInBody n >> declare n.text n.span ELabel Nothing -> newEntity Entity {name = "", span = s.span, parent = Nothing, kind = ELabel} depth <- gets (length . (.scopes)) modify' \st -> st {labelScopes = Map.insert labelId depth st.labelScopes} scheme <- case l.scheme of AS.Forever -> pure Forever AS.WhileLoop c -> nested (While <$> boolean c) AS.ForLoop it -> nested (forScheme it) body <- local (\c -> c {loops = LoopContext {name = (.text) <$> l.label, label = labelId} : c.loops, inLoopBody = True}) (statements decls l.statements) pure (TLoopNode TLoop {label = labelId, scheme, statements = body}) -- | A block that declares one variable of an unconstrained array type without a value and -- first assigns it a function's result (as Vibe writes `t: Grid = table(3)`, not knowing -- whether the callee is a function or a procedure with its result last, LN11): the result is -- its initial value, from which it takes its bounds. Otherwise the block as it is. initialisedByFirst :: ([AD.Decl] -> Sema [TDecl]) -> AS.BlockStmt -> Sema AS.BlockStmt initialisedByFirst decls b = case (b.declarations, b.statements) of (Just [d@AD.Decl {node = AD.DObject o}], AS.Stmt {node = AS.SAssign a} : rest) | [n] <- o.names , Nothing <- o.initial , not o.constant , null b.handlers , A.ENameRef t <- a.target.node , A.foldedName t == A.foldedName n , A.EApply _ <- a.value.node -> do (_, problems) <- trial (decls [d]) (procedure, _) <- trial (resultProcedure a.value) pure if any ((== IndefiniteObject) . (.code)) problems && isNothing procedure -- (a constant unless the rest may change it: assigns it, or passes it to a call) then AS.BlockStmt {label = b.label, declarations = Just [AD.Decl {span = d.span, node = AD.DObject AD.ObjectDecl {names = o.names, aliased = o.aliased, constant = not (mayChange n rest), subtype = o.subtype, initial = Just a.value, aspects = o.aspects}}], statements = case rest of {[] -> [AS.Stmt {span = a.value.span, node = AS.SNull}]; _ -> rest}, handlers = b.handlers, endLabel = b.endLabel} else b _ -> pure b where mayChange n rest = or [A.foldedName t == A.foldedName n | AS.Assignment {target = A.Expr {node = A.ENameRef t}} <- everything rest] || or [A.foldedName t == A.foldedName n | A.Argument {value = A.ArgExpr A.Expr {node = A.ENameRef t}} <- everything rest] everything :: (Data x, Data y) => x -> [y] everything x = maybe [] pure (cast x) <> concat (gmapQ everything x) -- | `t = P(a)` of a procedure that gives its results (vibe-syntax LN10: its `out` -- parameters and its scalar `in out` ones): the call with t where that result goes. A call -- whose one result is its last parameter, `out`, and whose actuals are by position is the -- assignment it has always been. Each is recorded for translation, which writes the call. resultsAssignment :: DeclChecker -> Span -> AS.Assignment -> Sema TStmtNode resultsAssignment decls at a = case a.target.node of A.ESurfaceForm _ -> assignment a _ -> resultFormals 1 a.value >>= \case Just (ap, formals) | not (lastResultByPosition ap formals) , Just st <- resultsCall at [a.target] ap formals -> do noteResults a.value.span formals (.node) <$> statement decls st Just (ap, formals) -> do noteResults a.value.span formals checked <- assignment a -- (the actuals the call may change, the target last: Varc marks them with `&`) forM_ (zip formals ([x.span | A.Argument {value = A.ArgExpr x} <- ap.arguments] <> [a.target.span])) \(f, sp) -> when f.changed (modify' \st -> st {references = Set.insert sp st.references}) pure checked _ -> assignment a -- | A call of a procedure whose results its targets take, by the call's span, with the -- procedure's parameters (which a translation to Vada or Varc calls it with). noteResults :: Span -> [ResultFormal] -> Sema () noteResults s formals = modify' \st -> st {resultCalls = (s, formals) : st.resultCalls} -- | A block that Vibe's `a, b = P(x)` makes (a tuple, then each name its item), or that -- declares a name with a value that is a call of a procedure giving its result (`n: T = -- P(x)`): the names declared as variables, and the call giving them their values, when P -- gives as many results (LN10). Otherwise the block as it is. resultsDeclared :: AS.BlockStmt -> Sema AS.BlockStmt resultsDeclared b = case (tupleResults b, b.declarations) of (Just (value, targets), _) -> resultFormals targets value >>= \case Just (ap, formals) | Just b' <- resultsBlock b ap formals -> b' <$ noteResults value.span formals _ -> pure b (_, Just [d@AD.Decl {node = AD.DObject o}]) | [n] <- o.names , Just value <- o.initial -> do found <- resultFormals 1 value -- (a name without a type takes its one result's, `x = s.pop()`: by its full name, -- or its own where that one is hidden, as a main module's type is by its `main`) inferred <- case (o.subtype, found) of (AT.InferredType, Just (_, formals)) | [Just m] <- [f.mark | f <- formals, f.result] -> do let full = resultMark n.span m own = resultMark n.span (Text.takeWhileEnd (/= '.') m) byFull <- fst <$> trial (denote full) let (mark, written) = case byFull of Just (DSubtype _) -> (full, m) _ -> (own, Text.takeWhileEnd (/= '.') m) -- (the subtype a translation to Vada writes for it) modify' \st -> st {inferredTypes = (n.span, written) : st.inferredTypes} pure (Just (AT.Indication A.SubtypeIndication {span = n.span, notNull = False, mark, constraint = Nothing})) _ -> pure Nothing pure case found of Just _ | Just subtype <- case o.subtype of AT.InferredType -> inferred written -> Just written -> let declared = AD.Decl {span = d.span, node = AD.DObject AD.ObjectDecl {names = o.names, aliased = o.aliased, constant = False, subtype, initial = Nothing, aspects = o.aspects}} assigned = AS.Stmt {span = value.span, node = AS.SAssign AS.Assignment {target = A.Expr {span = n.span, node = A.ENameRef n}, value}} in AS.BlockStmt {label = b.label, declarations = Just [declared], statements = assigned : b.statements, handlers = b.handlers, endLabel = b.endLabel} _ -> b _ -> pure b assignment :: AS.Assignment -> Sema TStmtNode assignment a = case a.target.node of -- a store through a surface form (Vibe's `xs[i] = v`): to the element, or by the -- container's procedure A.ESurfaceForm f -> formResolution True a.target.span f >>= \case Just r -> case resolvedStore a.target.span r f.operands a.value of AS.Stmt {node = AS.SCall c} -> procedureCall c AS.Stmt {node = AS.SAssign stored} -> plainAssignment stored _ -> pure TErrorStmt Nothing -> pure TErrorStmt -- Varc's `xs[i] = v` of a list or `m[k] = v` of a map, D189: the store of Vibe's form A.EApply ap | ap.bracketed == Just True, [_] <- ap.arguments -> do (probe, _) <- trial (expression AnyType ap.prefix) varcElement probe.typeOf ap >>= \case Just f -> formResolution True a.target.span f >>= \case Just r -> case resolvedStore a.target.span r f.operands a.value of AS.Stmt {node = AS.SCall c} -> procedureCall c AS.Stmt {node = AS.SAssign stored} -> plainAssignment stored _ -> pure TErrorStmt Nothing -> pure TErrorStmt Nothing -> plainAssignment a _ -> plainAssignment a plainAssignment :: AS.Assignment -> Sema TStmtNode plainAssignment a = resultProcedure a.value >>= \case -- `x = s.pop()` of a procedure whose last parameter is its result: a call with x last Just callee -> do modify' \st -> st {procedureResults = a.target.span : st.procedureResults} procedureCall A.Expr {span = a.value.span, node = A.EApply A.Apply {prefix = callee.prefix, arguments = callee.arguments <> [A.Argument {span = a.target.span, formal = Nothing, value = A.ArgExpr a.target, reference = Nothing}], bracketed = Nothing}} Nothing -> valueAssignment a valueAssignment :: AS.Assignment -> Sema TStmtNode valueAssignment a = do target <- expression AnyType a.target variable <- isVariable target markWritten target unless variable do what <- describeTarget target report (diagnostic NotAVariable Semantic ("cannot assign to " <> what)) { primary = Just (label target.span "not a variable") , notes = [Note {text = "only variables can be assigned: not constants, `in` parameters or loop parameters", span = Nothing}] } value <- local (\c -> c {assignmentTarget = Just target, sideEffectCall = Just a.value.span}) (expression (Expect target.typeOf) a.value) limited <- isLimited target.typeOf when limited do tn <- typeName target.typeOf report (diagnostic LimitedCopy Semantic ("cannot assign a value of the limited type `" <> tn <> "`")) { primary = Just (label target.span "a limited object") , notes = [Note {text = "values of a limited type are never copied (RM 7.5): build them in place, with an aggregate or a function call where an object is declared", span = Nothing}] } pure (TAssignNode TAssign {target, value}) where describeTarget t = case t.node of TObject d -> entity d >>= \e -> pure case e.kind of EObject o | o.loopParameter -> "loop parameter `" <> e.name <> "`" | o.mode == Just ModeIn -> "`in` parameter `" <> e.name <> "`" | otherwise -> "constant `" <> e.name <> "`" _ -> "`" <> e.name <> "`" _ -> pure "this expression" exit :: Span -> AS.ExitStmt -> Sema TStmtNode exit stmtSpan e = do loops <- asks (.loops) target <- case e.loopName of Nothing -> case loops of l : _ -> pure (Just l.label) [] -> do reportAt MisplacedExit stmtSpan "`exit` is only allowed inside a loop" "not in a loop" pure Nothing Just n -> case [l | l <- loops, fmap folded l.name == Just (A.foldedName n)] of l : _ -> pure (Just l.label) [] -> do reportAt MisplacedExit n.span ("no enclosing loop is named `" <> n.text <> "`") "not an enclosing loop" pure Nothing condition <- traverse boolean e.condition pure (maybe TErrorStmt (\l -> TExitNode TExit {loop = l, condition}) target) returnStatement :: Maybe A.Expr -> Sema TStmtNode returnStatement value = do current <- asks (.subprogram) returned <- asks (.extendedReturn) case current of Nothing -> do maybe (pure ()) (\v -> reportAt MisplacedReturn v.span "`return` is only allowed in a subprogram" "not in a subprogram") value pure (TReturn Nothing) Just f -> do fe <- entity f case (fe.kind, value) of (ESubprogram info, Just v) -> case info.result of Just r -> TReturn . Just <$> expression (Expect r.base) v Nothing -> do reportAt MisplacedReturn v.span ("procedure `" <> fe.name <> "` cannot return a value") "remove this value" pure (TReturn Nothing) (ESubprogram _, Nothing) | Just x <- returned -> pure (TReturn (Just x)) (ESubprogram info, Nothing) | Just _ <- info.result -> do reportAt MisplacedReturn fe.span ("function `" <> fe.name <> "` must return a value in every `return` statement") "a function" pure (TReturn Nothing) _ -> pure (TReturn Nothing) -- | `return R : T [:= V] [do ... end return;]`: a block declaring R, its statements (where a -- plain `return` returns R), then `return R`. extendedReturn :: DeclChecker -> Span -> AS.ExtendedReturn -> Sema TStmtNode extendedReturn decls at r = do current <- asks (.subprogram) resultType <- case current of Just f -> entity f >>= \fe -> pure case fe.kind of ESubprogram info -> (.base) <$> info.result _ -> Nothing Nothing -> pure Nothing case resultType of Nothing -> do reportAt MisplacedReturn r.name.span "an extended return is only allowed in a function" "not in a function" pure TErrorStmt Just t -> withScope BlockScope Nothing False do -- the object is declared as by an object declaration declared <- decls [AD.Decl {span = r.name.span, node = AD.DObject AD.ObjectDecl {names = [r.name], aliased = r.aliased, constant = r.constant, subtype = r.subtype, initial = r.initial, aspects = r.aspects}}] -- (the last: the constants that hold an object's run-time bounds come before it) case reverse [od | TObjectDeclNode od <- declared] of od : _ -> do oe <- entity od.object let sub = case oe.kind of EObject info -> info.subtype _ -> unconstrained t ok <- compatible t sub.base unless ok (reportAt TypeMismatch r.name.span "the returned object must have the function's result type" "another type") object <- mkExpr r.name.span sub.base (TObject od.object) body <- local (\c -> c {extendedReturn = Just object}) (statements decls (fromMaybe [] r.statements)) let final = TStmt {span = at, node = TReturn (Just object)} pure (TBlockNode TBlock {declarations = declared, statements = body <> [final], handlers = []}) _ -> pure TErrorStmt raise :: Span -> AS.RaiseStmt -> Sema TStmtNode raise at r = case r.exception of -- `raise;`: the exception being handled, again Nothing -> do inHandler <- asks (.inHandler) if inHandler then pure TReraise else TErrorStmt <$ reportAt WrongKindOfEntity at "`raise;` propagates the exception being handled, so it is only in a handler" "not in a handler" Just e -> maybe TErrorStmt TRaiseStmt <$> raising e r.message -- | SPARK's statement pragmas: @Assert@, @Assume@, @Loop_Invariant@ (directly in a loop's -- statements), @Loop_Variant@; others are reported as unknown and ignored. pragmaStatement :: A.Pragma -> Sema TStmtNode pragmaStatement p = case A.foldedName p.name of "assert" -> assertion Assert "assume" -> assertion Assume "loop_invariant" -> do inLoop <- asks (.inLoopBody) unless inLoop do reportAt MisplacedPragma p.span "`pragma Loop_Invariant` must appear directly in a loop's statements" "not directly in a loop" assertion LoopInvariant "loop_variant" -> do inLoop <- asks (.inLoopBody) unless inLoop do reportAt MisplacedPragma p.span "`pragma Loop_Variant` must appear directly in a loop's statements" "not directly in a loop" parts <- variantParts p.span p.arguments pure (TLoopVariant parts) -- (`Off` reported as the aspect is, B8004) "spark_mode" -> TNullStmt <$ forM_ [v | [A.Argument {value = A.ArgExpr v}] <- [p.arguments]] (sparkModeOff p.span p.name.text . Just) name | name `elem` ["annotate", "warnings", "debug", "inspection_point"] -> pure TNullStmt _ -> do report (diagnostic UnknownPragma Semantic ("unknown pragma `" <> p.name.text <> "` is ignored")) { primary = Just (label p.name.span "not a pragma Verada knows") } pure TNullStmt where assertion kind = case p.arguments of arg : _ | A.ArgExpr x <- arg.value -> do -- (`pragma Assert (Level => Condition)`: at an assertion level, G9) levels <- gets (.assertionLevels) let level = case arg.formal of Just f | Map.member (A.foldedName f) levels -> Just (A.foldedName f) _ -> Nothing condition <- boolean x checkLevelReferences level condition -- (and its message, `pragma Assert (C, Message)`: a String, Ada's second argument) message <- case drop 1 p.arguments of [] -> pure Nothing m : more | kind /= LoopInvariant, A.ArgExpr y <- m.value, maybe True (\f -> A.foldedName f == "message") m.formal -> do forM_ (take 1 more) \extra -> reportAt WrongArguments extra.span ("`pragma " <> p.name.text <> "` takes a condition and a message") "one too many" st <- std Just <$> expression (Expect st.string) y m : _ -> Nothing <$ reportAt WrongArguments m.span ("`pragma " <> p.name.text <> "` takes " <> (if kind == LoopInvariant then "a condition alone" else "a condition and a message, a String")) "not taken" pure (TAssertionNode TAssertion {kind, condition, message}) _ -> do reportAt WrongArguments p.span ("`pragma " <> p.name.text <> "` needs a Boolean condition") "missing condition" pure TErrorStmt -- | Whether a statement list contains a @return@ (a function must, RM 6.5(5)). hasReturn :: [TStmt] -> Bool hasReturn = any \s -> case s.node of TReturn _ -> True TIfStmtNode i -> any (hasReturn . (.statements)) i.branches || hasReturn i.elsePart TCaseStmtNode c -> any (hasReturn . (.statements)) c.alternatives TLoopNode l -> hasReturn l.statements TBlockNode b -> hasReturn b.statements _ -> False -- | The components of a variant: `Increases => E` or `Decreases => E`, discrete expressions. variantParts :: Span -> [A.Argument] -> Sema [VariantPart] variantParts at args = fmap concat . forM args $ \a -> case (fmap A.foldedName a.formal, a.value) of (Just direction, A.ArgExpr x) | direction `elem` ["increases", "decreases"] -> do v <- expression AnyType x discrete <- isDiscrete v.typeOf unless discrete (reportAt TypeMismatch x.span "a variant must be of a discrete type" "not discrete") pure [VariantPart {increases = direction == "increases", value = v}] _ -> do reportAt WrongArguments (if null args then at else a.span) "a variant component is `Increases => E` or `Decreases => E`" "not a variant component" pure [] -- * Exception handlers (language L7, SPARK RM 11.2) -- | A handler's statements in a block that declares its occurrence: -- `declare X : constant Ada.Exceptions.Exception_Occurrence := Ada.Exceptions.Current_Occurrence;`. occurrenceBlock :: Span -> A.Identifier -> [AS.Stmt] -> AS.Stmt occurrenceBlock at o ss = AS.Stmt { span = at , node = AS.SBlock AS.BlockStmt {label = Nothing, declarations = Just [declaration], statements = ss, handlers = [], endLabel = Nothing} } where declaration = AD.Decl {span = o.span, node = AD.DObject AD.ObjectDecl {names = [o], aliased = False, constant = True, subtype = AT.Indication A.SubtypeIndication {span = o.span, notNull = False, mark = exceptions "Exception_Occurrence", constraint = Nothing}, initial = Just (exceptions "Current_Occurrence"), aspects = []}} exceptions n = foldl select (named "Ada") ["Exceptions", n] named n = A.Expr {span = o.span, node = A.ENameRef A.Identifier {span = o.span, text = n}} select p n = A.Expr {span = o.span, node = A.ESelected A.Selected {prefix = p, selector = A.SelectIdentifier A.Identifier {span = o.span, text = n}}} -- | Whether statements end by raising the exception being handled again (`raise;`). reraises :: [AS.Stmt] -> Bool reraises ss = case reverse ss of AS.Stmt {node = AS.SRaise AS.RaiseStmt {exception = Nothing}} : _ -> True _ -> False -- | The handlers of a block or body: each names user exceptions (a predefined check -- exception is never raised, since checks are proved: B1018), or `others`, last. handlers :: DeclChecker -> [AS.Handler] -> Sema [THandler] handlers decls hs = forM (zip [1 :: Int ..] hs) \(n, h) -> do exceptions <- concat <$> forM h.choices \case A.ChoiceOthers sp -> do unless (n == length hs && length h.choices == 1) do reportAt WrongKindOfEntity sp "`others` must be the only choice of the last handler" "not last" -- (a handler that ends by raising the exception again handles none: it cleans up on -- the way out, as Vibe's `finally` does; nor does a Vibe `with` statement's, which -- passes the exception to its context manager's `__exit__`, Verada.Vibe.With) unless (reraises h.statements || maybe False (Text.isPrefixOf "Verada_Exception_" . (.text)) h.occurrence) do report (diagnostic OthersHandlerChecks Semantic "`when others` handles the exceptions this program raises, not failed checks") { primary = Just (label sp "not for failed checks") , notes = [Note {text = "run-time checks are proved, and a check that fails in a build without proof stops the program as GNAT's would not (language 5.5)", span = Nothing}] } pure [] A.ChoiceExpr e -> handled e A.ChoiceRange r -> do reportAt WrongKindOfEntity r.span "a handler names exceptions" "not an exception" pure [] -- `when X : E`: X is a constant the handler's statements see, the occurrence being handled -- (from Ada.Exceptions, which the unit names in a with clause) loaded <- gets (Map.member "ada.exceptions" . (.libraryUnits)) forM_ h.occurrence \o -> unless loaded do report (diagnostic UnknownUnit Semantic "an exception occurrence is an `Ada.Exceptions.Exception_Occurrence`") { primary = Just (label o.span "needs Ada.Exceptions") , advice = Just "add `with Ada.Exceptions;` to the unit" } let withOccurrence = case h.occurrence of Just o | loaded -> [occurrenceBlock h.span o h.statements] _ -> h.statements body <- local (\c -> c {inHandler = True, handlerOccurrence = if loaded then (.span) <$> h.occurrence else Nothing}) (statements decls withOccurrence) pure THandler {exceptions, occurrence = Nothing, statements = body} where handled e = denote e >>= \case Just (DException d) -> do predefined <- isCheckException d when predefined do x <- entity d report (diagnostic HandlerForCheck Semantic ("`" <> x.name <> "` is raised only by a failed check, and checks are proved")) { primary = Just (label e.span "a check exception") , advice = Just "add the precondition or test that makes the check pass, and remove the handler" } pure [d] Just DNone -> pure [] _ -> do reportAt WrongKindOfEntity e.span "a handler names exceptions" "not an exception" pure [] -- | Whether an exception is one of the predefined ones a failed check raises. isCheckException :: DeclId -> Sema Bool isCheckException d = do x <- entity d st <- std pure (x.parent == Just st.package && x.name `elem` ["Constraint_Error", "Program_Error", "Storage_Error"])