{-# LANGUAGE MultiWayIf #-} -- | Expressions (Ada RM 4): name resolution with an expected type, calls (resolved among -- the visible candidates by arity, named associations and types), predefined operators, -- attributes, aggregates, conditional and quantified expressions, ranges and subtype -- indications. Every error yields a 'TErrorExpr' of the error type, which every later -- check accepts silently, so one mistake gives one diagnostic. module Verada.Sema.Check.Expr ( Denotation (..) , Expect (..) , boolean , caseSelector , selectorExpression , choice , elementAt , iterationOf , checkCoverage , othersPlacement , conform , declaredDefault , defaultInitialised , denote , denoteSubprogram , discreteRange , errorExpr , expression , forScheme , formResolution , operatorPackage , operatorVisible , orderedMethods , resultProcedure , ResultFormal (..) , resultFormals , isVariable , varcElement , markWritten , arrayRange , iterationDomain , raising , mkExpr , procedureCall , rangeOf , subtypeIndication , shapes , substituted , subtypeMarkOf , staticInteger , staticBounds , subtypeOfExpr , systemAddressType , wholeRange ) where import Verada.Diagnostics (Diagnostic (..), Fix (..), Label (..), Note (..), Phase (..), Replacement (..), diagnostic, label, rangeText) import Verada.Diagnostics qualified as Diagnostics import Verada.Diagnostics.Arrival (Arrival (..)) import Verada.Diagnostics.Codes (DiagCode (..)) import Verada.Diagnostics.Excluded (accessImageReplacement, dynamicTaskReplacement, excludedAttribute, excludedDeclaration, nestedSubprogramReplacement, reraiseReplacement, uncheckedAccessReplacement) import Verada.Sema.Check.Levels (checkReferenceLevel) import Verada.Sema.Env import Verada.Sema.Monad import Verada.Sema.Resolve (admitsAny, describeShapes) import Verada.Sema.Standard (staticRange) import Verada.Sema.Static (fromBool, staticBinary, staticUnary, toBool) import Verada.Sema.Suggest (closest, handlingConversions, undefinedName) import Verada.Sema.Types import Verada.Source (FileId (..), Span (..)) import Verada.Syntax.AST.Decl qualified as AD import Verada.Syntax.AST.Expr qualified as A import Verada.Syntax.AST.Type qualified as AT import Verada.Syntax.Scientific (integerValue) import Verada.Syntax.Apl.Embed (Hosts (..), ScopeContext (..), ScopeName (..), namesInApl, readApl, readAplWithOrigins) import Verada.Syntax.Apl.Lexer (AplToken (..), AplTokenKind (..), lexApl) import Verada.Syntax.Apl.Lower qualified as AplTrace import Verada.Syntax.Apl.Syntax (NameClass (..)) import Verada.Syntax.Pipeline (pipelineNode, scanExpansion) import Verada.Syntax.ProcedureResults (ResultFormal (..)) import Verada.Syntax.SurfaceForm (Coercion (..), FormResolution (..), PlainShape (..), Repr (..), resolvedExpr, resolvedFormExpr) import Verada.TAST.Decl import Verada.TAST.Expr import Verada.TAST.Ids (DeclId (..), TypeId (..)) import Verada.TAST.Stmt (TStmtNode (..)) import Verada.TAST.Type import Control.Applicative ((<|>)) import Control.Monad (filterM, foldM, forM, forM_, join, mfilter, unless, void, when, zipWithM) import Control.Monad.Reader (ask, asks, local) import Control.Monad.State.Strict (get, gets, modify') import Data.ByteString qualified as ByteString import Data.Char (chr, ord) import Data.Either (partitionEithers) import Data.Functor ((<&>)) import Data.IntMap.Strict qualified as IntMap import Data.List (elemIndex, find, nub, sortOn) import Data.Map.Strict qualified as Map import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe, mapMaybe) import Data.Ratio (denominator, numerator) import Data.Set qualified as Set import Data.Text (Text) import Data.Text qualified as Text import Data.Text.Encoding (encodeUtf8) -- | Whether an access type is a proof enclave's: declared in one, or designating a type one -- declares (its values share cells, F7). enclavePointer :: TypeId -> Sema Bool enclavePointer t = do marked <- gets (.enclaves) def <- typeDef t let inside d = entity d >>= \e -> case e.kind of EPackage _ -> pure (d `elem` marked) _ -> maybe (pure False) inside e.parent designated <- case def.kind of KAccess a -> (.decl) <$> typeDef a.designated.base _ -> pure Nothing if null marked then pure False else or <$> mapM inside (maybe [] pure def.decl <> maybe [] pure designated) -- | What the context requires of an expression. data Expect = Expect TypeId | AnyType -- | What a name denotes, before it is used as a value. data Denotation = DPackage DeclId | DSubtype Subtype | DOverloaded [DeclId] | DObjectLike DeclId | DException DeclId | DLabel DeclId | DGeneric DeclId | -- | undefined or ambiguous; already reported DNone -- * Building typed expressions -- | The same expression with another span (DuplicateRecordFields rules out record update). withSpan :: Span -> TExpr -> TExpr withSpan s e = TExpr {span = s, typeOf = e.typeOf, static = e.static, node = e.node} namedSubtype :: DeclId -> Subtype -> Subtype namedSubtype d sub = Subtype {base = sub.base, range = sub.range, indices = sub.indices, discriminantValues = sub.discriminantValues, predicates = sub.predicates, excludesNull = sub.excludesNull, name = Just d, digits = sub.digits} errorExpr :: Span -> Sema TExpr errorExpr s = do st <- std pure TExpr {span = s, typeOf = st.errorType, static = Nothing, node = TErrorExpr} -- | A typed expression with its static value, if it has one (RM 4.9). mkExpr :: Span -> TypeId -> TExprNode -> Sema TExpr mkExpr s t node = do exact <- staticValueOf t node -- (in Vibe, a float is Python's, a double: each static operation rounds to one, so that -- `0.1 + 0.2` is Python's 0.30000000000000004) python <- asks (.python) sd <- std floating <- fullKind t <&> \case KReal _ -> True _ -> False -- (a zero a float operation makes negative, `-0.0`, which a static value, exact, cannot -- be: the operation is done when the program runs, as Python's is and as GNAT's is, with -- IEEE's signed zeros; a universal value, a named number's, is exact) let negativeZero = floating && (python || t /= sd.universalReal) && exact == Just (StaticReal 0) && maybe False isNegativeZero (doubleOf node) value | negativeZero = Nothing | python && floating = machineDouble <$> exact | otherwise = exact -- (a converted negative zero: its operand, a universal value, made when the program runs -- too, so that it keeps its sign) let node' = case node of TConversionNode c | negativeZero -> TConversionNode TConversion {target = c.target, operand = TExpr {span = c.operand.span, typeOf = c.operand.typeOf, static = Nothing, node = c.operand.node}, qualified = c.qualified} _ -> node -- (a translation to Vada, whose static operations are exact, writes such a value) case (node, value) of (TBinaryNode _, Just (StaticReal r)) | value /= exact -> modify' \st -> st {roundedReals = (s, r) : st.roundedReals} _ -> pure () pure TExpr {span = s, typeOf = t, static = value, node = node'} -- | A static float operation's value as Python computes it, a double (with its sign of zero). doubleOf :: TExprNode -> Maybe Double doubleOf = \case TUnaryNode TUnary {op = TMinus, operand} -> negate <$> doubleOf' operand TBinaryNode TBinary {op, left, right} -> do l <- doubleOf' left r <- doubleOf' right case op of TMul -> Just (l * r) TDiv -> Just (l / r) TAdd -> Just (l + r) TSub -> Just (l - r) _ -> Nothing -- (a zero converted keeps its sign: `Long_Float (-0.0)`) TConversionNode c | Just (StaticReal 0) <- c.operand.static -> doubleOf c.operand.node _ -> Nothing where doubleOf' e = case e.static of Just (StaticReal r) | r /= 0 -> Just (fromRational r) -- (a zero: of its own operation's sign, else positive) Just (StaticReal _) -> Just (fromMaybe 0 (doubleOf e.node)) Just (StaticInteger n) -> Just (fromInteger n) _ -> Nothing -- | A real value as the double nearest it (an exact one beyond the doubles' range stays, for -- its overflow check). machineDouble :: StaticValue -> StaticValue machineDouble = \case StaticReal r | let d = fromRational r :: Double , not (isInfinite d) -> StaticReal (toRational d) v -> v -- | N for a decimal type whose delta is 10 ** (-N). decimalScale :: Rational -> Integer decimalScale d = case [n | n <- [-30 .. 30], 10 ^^ negate n == d] of n : _ -> n [] -> 0 -- | To the nearest integer, halves away from zero (Ada's conversion of a real, RM 4.6(33)). roundHalfAway :: Rational -> Integer roundHalfAway r = let n = floor (abs r + 1 / 2) in if r < 0 then negate n else n staticValueOf :: TypeId -> TExprNode -> Sema (Maybe StaticValue) staticValueOf t = \case TLiteral v -> pure (Just v) TObject d -> entity d >>= \e -> pure case e.kind of EObject o | o.constant -> o.value _ -> Nothing TBinaryNode b -> do kind <- fullKind b.left.typeOf pure case (b.op, b.left.static, b.right.static) of (TAndThen, Just l, _) | toBool l == Just False -> Just (fromBool False) (TOrElse, Just l, _) | toBool l == Just True -> Just (fromBool True) (_, Just l, Just r) -> either (const Nothing) Just (staticBinary kind b.op l r) _ -> Nothing TUnaryNode u -> do kind <- fullKind t pure (u.operand.static >>= either (const Nothing) Just . staticUnary kind u.op) -- (a real converted to an integer type rounds to the nearest, halves away from zero, RM -- 4.6(33); an integer converted to a real type is that real, so that `Long_Float (7) / -- Long_Float (2)` is 3.5, not the integers' quotient) TConversionNode c -> do kind <- fullKind t pure case (c.operand.static, kind) of (Just (StaticReal r), KInteger _) -> Just (StaticInteger (roundHalfAway r)) (Just (StaticInteger n), KReal _) -> Just (StaticReal (fromInteger n)) (Just (StaticInteger n), KFixed _) -> Just (StaticReal (fromInteger n)) (v, _) -> v TIfNode i -> pure (staticIf i.branches i.elseValue) -- (`Character'Val (9)` of a static position: the character there, a static value, so that a -- string a translation writes with it, `"a" & Character'Val (9)`, is one too) TAttributeNode TAttribute {attribute = AVal, arguments = [x]} | Just (StaticInteger n) <- x.static -> do kind <- fullKind t pure case kind of KEnumeration en | en.isCharacter, n >= 0, n < en.characters -> Just (StaticEnum (fromInteger n)) _ -> Nothing _ -> pure Nothing where staticIf branches elseValue = case branches of [] -> elseValue >>= (.static) b : rest -> case toBool =<< b.condition.static of Just True -> b.value.static Just False -> staticIf rest elseValue Nothing -> Nothing -- * Type expectations -- | Check an expression's type against the expectation; universal values are converted to -- the expected type (and checked against its base range). conform :: Expect -> TExpr -> Sema TExpr conform AnyType e = pure e conform (Expect t) e = do ok <- compatible t e.typeOf optionals <- optionalsHere if not ok then (if optionals then optionalCoercion t e else pure Nothing) >>= maybe (mismatch t e) pure else do universal <- isUniversal e.typeOf expectedUniversal <- isUniversal t if universal && not expectedUniversal then convertUniversal t e else pure e -- | Whether optional values are coerced here (Vibe's `T | None`, Varc's `T?`, D189): a value -- where an optional one is wanted is it present, an optional one where its element is -- wanted its value, `None`/`null` the absent one. optionalsHere :: Sema Bool optionalsHere = (||) <$> asks (.python) <*> asks (.varc) -- | Verada.Optionals' `Optional` of an instance (Vibe's `T | None`, `Optional[T]`): its -- element type and its operations. data OptionalType = OptionalType { element :: TypeId , just :: DeclId , none :: DeclId , value :: DeclId , hasValue :: DeclId } optionalType :: TypeId -> Sema (Maybe OptionalType) optionalType t = do tn <- typeName t if folded tn /= "optional" then pure Nothing else fullKind t >>= \case KRecord r | Just item <- find (\c -> folded c.name == "item") r.components -> do let op n = listToMaybe <$> primitivesNamed n t ops <- (,,,) <$> op "Just" <*> op "None" <*> op "Value" <*> op "Has_Value" pure case ops of (Just j, Just n, Just v, Just h) -> Just OptionalType {element = item.subtype.base, just = j, none = n, value = v, hasValue = h} _ -> Nothing _ -> pure Nothing -- | In Vibe, a value where an optional one of its type is wanted is that value present -- (`Just`), and an optional value where its element is wanted is its value (`Value`, whose -- precondition, that it has one, is proved: after `x is not None`, or where the program -- shows it otherwise). Recorded for translation, which writes the call. optionalCoercion :: TypeId -> TExpr -> Sema (Maybe TExpr) optionalCoercion t e = do wanted <- optionalType t elementGiven <- maybe (pure False) (\o -> compatible o.element e.typeOf) wanted case wanted of Just o | elementGiven -> do v <- conform (Expect o.element) e Just <$> optionalCall e.span t o.just [v] _ -> optionalType e.typeOf >>= \case Just o -> do fits <- compatible t o.element if fits then Just <$> (optionalCall e.span o.element o.value [e] >>= conform (Expect t)) else pure Nothing Nothing -> pure Nothing -- | Python's `d.get(k)` of a dictionary without a default where a `V | None` is wanted: the -- value at k if d has one, else `None` (recorded as the form's resolution). optionalLookup :: Expect -> Span -> A.SurfaceForm -> Sema (Maybe FormResolution) optionalLookup expect s f = do python <- asks (.python) case (expect, f.kind, f.operands) of (Expect t, A.FormMethod m [], [d, _]) | python , Text.toLower m.text == "get" -> optionalType t >>= \case Nothing -> pure Nothing Just o -> do (probe, _) <- trial (expression AnyType d) tn <- typeName probe.typeOf contains <- primitivesNamed "Contains" probe.typeOf values <- primitivesNamed "Value" probe.typeOf case (contains, values) of (c : _, v : _) | "Dictionary" `Text.isSuffixOf` tn -> do r <- AsOptionalLookup <$> denotingName s c <*> denotingName s v <*> denotingName s o.just <*> denotingName s o.none modify' \state -> state {surfaceForms = ((s, A.surfaceFormName f.kind), r) : state.surfaceForms} pure (Just r) _ -> pure Nothing _ -> pure Nothing -- | The shortest name that denotes a declaration here (its own, where that is visible, then -- through its packages). denotingName :: Span -> DeclId -> Sema Text denotingName s d = do full <- fullName d let parts = Text.splitOn "." full suffixes = [Text.intercalate "." (drop k parts) | k <- reverse [0 .. length parts - 1]] shortestDenoting s d suffixes full -- | A call of an optional type's operation that Vibe's forms leave unwritten, recorded so -- that a translation writes it. optionalCall :: Span -> TypeId -> DeclId -> [TExpr] -> Sema TExpr optionalCall s t d args = do full <- denotingName s d modify' \st -> st {coercions = (s, if null args then ReplaceBy full else WrapIn full) : st.coercions} mkExpr s t (TCallNode TCall {callee = d, arguments = args}) -- | In Vibe, an optional value where an operation of its element works on it: the call of -- its `Value` (at places of their own, as the operand's keeps its type), recorded for -- translation; any other expression as it is. narrowed :: A.Expr -> Sema A.Expr narrowed x | not (named x.node) = pure x | otherwise = do (probe, _) <- trial (expression AnyType x) optionalType probe.typeOf >>= \case Just o -> do full <- denotingName x.span o.value modify' \st -> st {coercions = (x.span, WrapIn full) : st.coercions} let at0 = Span {file = x.span.file, start = x.span.start, end = x.span.start} at1 = Span {file = x.span.file, start = x.span.end, end = x.span.end} pure A.Expr {span = at1, node = A.EApply A.Apply {prefix = dottedExpr at1 (Text.splitOn "." full), arguments = [A.Argument {span = at0, formal = Nothing, value = A.ArgExpr A.Expr {span = at0, node = A.EParen x}, reference = Nothing}], bracketed = Nothing}} Nothing -> pure x where -- (an optional value is an object's, a component's or a call's) named = \case A.ENameRef _ -> True A.ESelected _ -> True A.EApply _ -> True A.EParen y -> named y.node _ -> False mismatch :: TypeId -> TExpr -> Sema TExpr mismatch expected e = do expectedName <- typeName expected actualName <- typeName e.typeOf let found = case actualName of "universal_integer" -> "an integer value" "universal_real" -> "a real value" _ -> "`" <> actualName <> "`" numericBoth <- (&&) <$> isNumeric expected <*> isNumeric e.typeOf universal <- isUniversal e.typeOf python <- asks (.python) -- (in Vibe, Python's conversions: `int(...)` truncates a float, `float(...)` converts an -- int, as Python's do) let conversionAdvice | python, expectedName == "Integer" = "if the conversion is intended, write `int(...)` (which truncates toward zero), or `round(...)`" | python, expectedName == "Long_Float" = "if the conversion is intended, write `float(...)`; Vibe converts an `int` meeting a `float` where the annotations say which is which, so annotating the names involved may be enough" | otherwise = "if the conversion is intended, write `" <> expectedName <> " (...)`" report (diagnostic TypeMismatch Semantic ("expected `" <> expectedName <> "`, found " <> found)) { primary = Just (label e.span ("this is " <> (if "`" `Text.isPrefixOf` found then "of type " else "") <> found)) , advice = if | numericBoth && not universal -> Just conversionAdvice -- (a text given for a String: Verada.Strings.Texts' To_String makes one) | expectedName == "String" && actualName == "Text" -> Just "a text's characters are a `String` by Verada.Strings.Texts' `To_String`; its `Put` and `Put_Line` write a text as it is" | otherwise -> Nothing } errorExpr e.span modularKind :: TypeKind -> Bool modularKind = \case KModular _ -> True _ -> False -- | A static conversion or qualified expression of a discrete value to a static subtype -- that does not hold it: its evaluation fails a range check, and a static expression that -- fails one is illegal (RM 4.9(34)). An instance's text is checked with its generic's. staticInSubtype :: Subtype -> TExpr -> Sema TExpr staticInSubtype target e = do making <- asks (.instancesMaking) skipped <- asks (.unevaluated) discrete <- isDiscrete target.base bounds <- if discrete && null making && not skipped && isJust e.static then staticBounds target else pure Nothing case (bounds, position =<< e.static) of (Just (lo, hi), Just v) | v < lo || v > hi -> do name <- typeName target.base reportAt StaticValueOutOfRange e.span ("this static value is not in the subtype it is converted to, `" <> name <> "`, so its check fails") "fails a range check" errorExpr e.span _ -> pure e where position = \case StaticInteger v -> Just v StaticEnum p -> Just (toInteger p) _ -> Nothing -- | A universal (static) value used as a value of a specific type: retyped, and checked -- against the type's base range (RM 4.9(35)). convertUniversal :: TypeId -> TExpr -> Sema TExpr convertUniversal t e = do kind <- fullKind t case (kind, e.static) of (KInteger i, Just (StaticInteger v)) | not i.universal && (v < i.baseFirst || v > i.baseLast) -> outOfRange (i.baseFirst, i.baseLast) (KModular m, Just (StaticInteger v)) | v < 0 || v >= m.modulus -> outOfRange (0, m.modulus - 1) _ -> pure e {typeOf = t} where outOfRange (lo, hi) = do name <- typeName t reportAt StaticValueOutOfRange e.span ("value " <> showValue e.static <> " does not fit in `" <> name <> "`") ("`" <> name <> "` holds " <> rangeText (tshow lo) (tshow hi)) errorExpr e.span showValue :: Maybe StaticValue -> Text showValue = \case -- (a value of many digits by its size: a universal integer has no limit, D185) Just (StaticInteger v) | Text.length shown > 60 -> "of " <> tshow (Text.length (Text.dropWhile (== '-') shown)) <> " digits" | otherwise -> shown where shown = tshow v Just (StaticReal r) -> tshow (fromRational r :: Double) Just (StaticEnum p) -> tshow p Just (StaticString s) -> "\"" <> s <> "\"" Nothing -> "?" boolean :: A.Expr -> Sema TExpr boolean e = do st <- std -- (a condition may be of any boolean type, RM 4.5.7(2), 5.3(3): one of a type derived from -- Boolean is converted to Boolean, which its values are) guess <- otherBooleanType e derived <- case guess of Just t -> (\(_, problems) -> if null problems then Just t else Nothing) <$> trial (expression (Expect t) e) Nothing -> pure Nothing case derived of Just t -> do v <- expression (Expect t) e mkExpr e.span st.boolean (TConversionNode TConversion {target = unconstrained st.boolean, operand = v, qualified = False}) Nothing -> expression (Expect st.boolean) e -- | The one boolean type other than Boolean an expression may have (a type derived from -- Boolean), judged by its possible types alone. otherBooleanType :: A.Expr -> Sema (Maybe TypeId) otherBooleanType e = do st <- std ss <- shapes e others <- filterM (\t -> fullKind t <&> \case { KEnumeration en -> en.isBoolean && t /= st.boolean; _ -> False }) [t | Exactly t <- ss] pure case (nub others, Exactly st.boolean `elem` ss) of ([t], False) -> Just t _ -> Nothing -- * Names -- | What a name (identifier or selected name) denotes; 'Nothing' for other expressions and -- for a selected component of a value. denote :: A.Expr -> Sema (Maybe Denotation) denote e = case e.node of A.ENameRef i -> do ds <- lookupDirect i.text self <- currentInstance i.text case (ds, self) of -- (a library generic is not directly visible in its own text: its name is still the -- current instance's) ([], Just current) -> pure (Just current) ([], Nothing) -> do -- (the root of a unit the context clause names but the driver could not give, which -- it has reported) missing <- asks (.missingUnits) unless (any (\m -> folded i.text == Text.takeWhile (/= '.') m) missing) (undefinedName i.span i.text >>= report) pure (Just DNone) _ -> do found <- classify i.span i.text ds >>= \case DGeneric g -> fromMaybe (DGeneric g) <$> (entity g >>= currentInstance . (.name)) other -> pure other privateWithUse i.span i.text found pure (Just found) -- `ASCII.X` (Annex J.5): reported with the fix to `Ada.Characters.Latin_1` A.ESelected sel | A.SelectIdentifier i <- sel.selector , A.ENameRef p <- sel.prefix.node , A.foldedName p == "ascii" -> do declared <- lookupDirect p.text if null declared then Just DNone <$ obsoleteAscii sel.prefix i else denoteSelected sel i A.ESelected sel | A.SelectIdentifier i <- sel.selector -> denoteSelected sel i -- `P."+"`: an operator declared in P, by its expanded name (RM 4.1.3(5), 6.1) A.ESelected sel | A.SelectOperator op <- sel.selector -> do prefix <- denote sel.prefix case prefix of Just (DPackage p) -> do let n = "\"" <> Text.toLower op <> "\"" ds <- lookupInPackage p n -- (or a formal of the generic whose instance the prefix is, RM 4.1.3(4): `G."="`) formal <- if null ds then instanceFormal sel.prefix prefix n else pure Nothing case (ds, formal) of ([], Just d) -> Just <$> classify sel.prefix.span n [d] ([], Nothing) -> pure Nothing _ -> Just <$> classify sel.prefix.span n ds _ -> pure Nothing -- `T'Class` names the class-wide type A.EAttribute a | A.foldedName a.designator == "class" -> Just . DSubtype <$> subtypeMarkOf e -- `T'Base`: T's base type, without T's constraint (RM 3.5(15)) A.EAttribute a | A.foldedName a.designator == "base", null a.arguments -> denote a.prefix <&> \case Just (DSubtype sub) -> Just (DSubtype (unconstrained sub.base)) other -> other A.EParen inner -> denote inner >>= \case Just (DSubtype _) -> pure Nothing other -> pure other _ -> pure Nothing where packageNames p = entity p >>= \pe -> case pe.kind of EPackage info -> mapM (fmap (.name) . entity) info.visible _ -> pure [] denoteSelected sel i = do prefix <- denote sel.prefix case prefix of -- `B.X`: X declared in the block or loop named B, though a nearer X hides it Just (DLabel b) -> do depth <- gets (Map.lookup b . (.labelScopes)) scs <- gets (.scopes) let inner = case depth of Just n -> case drop (length scs - n) scs of sc : _ -> Map.findWithDefault [] (folded i.text) sc.names [] -> [] Nothing -> [] if null inner then pure Nothing else Just <$> classify i.span i.text inner _ -> denoteSelectedOf sel i prefix denoteSelectedOf sel i prefix = do formal <- instanceFormal sel.prefix prefix i.text case (formal, prefix) of -- an expanded name (RM 4.1.3(4-5)) whose prefix is the current instance of a generic -- unit: one of the generic's formals, as this instance binds it (RM 8.6(18), 12.3(13)) (Just d, _) -> Just <$> classify i.span i.text [d] -- or an enclosing subprogram: what is declared immediately in it (_, Just (DOverloaded ds)) -> do scs <- gets (.scopes) case [x | sc <- scs, sc.kind == SubprogramScope, Just o <- [sc.owner], o `elem` ds, x <- Map.findWithDefault [] (folded i.text) sc.names] of [] -> pure Nothing found -> Just <$> classify i.span i.text found (_, Just (DPackage p)) -> do declared <- lookupInPackage p i.text -- (inside the package, its body's declarations too: `Pkg.Name` in Pkg's body) scs <- gets (.scopes) let own = [x | sc <- scs, sc.owner == Just p, x <- Map.findWithDefault [] (folded i.text) sc.names] ds = if null declared then nub own else declared if null ds then do pkg <- fullName p visible <- packageNames p missing <- asks (.missingUnits) let suggestion = closest i.text visible named = folded (pkg <> "." <> i.text) conversions <- if folded pkg == "ada.characters.handling" && folded i.text `elem` handlingConversions then obsoleteConversion sel.prefix i else pure Nothing case (conversions, excludedDeclaration pkg i.text) of (Just _, _) -> pure () (Nothing, Just (what, r)) -> reportExcluded i.span ("`" <> pkg <> "." <> i.text <> "` (" <> what <> ") is not in Verada") r (Nothing, Nothing) -> unless (any (\m -> m == named || (named <> ".") `Text.isPrefixOf` m) missing) $ report (diagnostic UndefinedName Semantic ("`" <> pkg <> "` has no visible declaration of `" <> i.text <> "`")) { primary = Just (label i.span (maybe "not declared in this package" (\c -> "did you mean `" <> c <> "`?") suggestion)) , fixes = [Fix {span = i.span, replacement = Verbatim c, description = "write `" <> c <> "`"} | Just c <- [suggestion]] } pure (Just (fromMaybe DNone conversions)) else do -- (inside an instance's text, the generic's expanded name denotes the current -- instance too: `Ada.Text_IO.Wide_Generic`, RM 8.6(18)) making <- asks (.genericsMaking) found <- classify i.span i.text ds >>= \case DGeneric g | g `elem` making -> fromMaybe (DGeneric g) <$> (entity g >>= currentInstance . (.name)) other -> pure other privateWithUse i.span i.text found pure (Just found) (_, Just DNone) -> pure (Just DNone) _ -> pure Nothing -- | `Ada.Characters.Handling.To_Wide_String` and the other J.14 conversions: reported with the -- fix to `Ada.Characters.Conversions` (and the with clause it needs), and taken as that -- unit's, when the unit names it, so that the rest of the program is checked. obsoleteConversion :: A.Expr -> A.Identifier -> Sema (Maybe Denotation) obsoleteConversion prefix i = do start <- asks (.unitStart) withed <- asks (.withedUnits) conversions <- filterM (\d -> (\x -> folded x.name == "conversions") <$> entity d) withed let whole = Span {file = prefix.span.file, start = prefix.span.start, end = i.span.end} modern = "Ada.Characters.Conversions." <> i.text withClause = [Fix {span = Span {file = prefix.span.file, start, end = start}, replacement = Verbatim "with Ada.Characters.Conversions; ", description = "name `Ada.Characters.Conversions` in a with clause"} | null conversions] report (diagnostic ObsolescentLibraryName Semantic ("`Ada.Characters.Handling." <> i.text <> "` is an obsolescent name for `" <> modern <> "`")) { primary = Just (label whole "Annex J.14 renaming") , fixes = Fix {span = whole, replacement = Verbatim modern, description = "write `" <> modern <> "`"} : withClause } case conversions of d : _ -> do ds <- lookupInPackage d i.text if null ds then pure (Just DNone) else Just <$> classify i.span i.text ds [] -> pure (Just DNone) -- | `ASCII.X` (Annex J.5): the obsolescent package of ASCII's characters, reported with the -- fix to `Ada.Characters.Latin_1`, whose name for X it gives (and the with clause it needs). obsoleteAscii :: A.Expr -> A.Identifier -> Sema () obsoleteAscii prefix i = do start <- asks (.unitStart) withed <- asks (.withedUnits) latin <- filterM (\d -> (\x -> folded x.name == "latin_1") <$> entity d) withed let modern = fromMaybe i.text (lookup (folded i.text) renamed) whole = Span {file = prefix.span.file, start = prefix.span.start, end = i.span.end} clause = Fix {span = Span {file = prefix.span.file, start, end = start}, replacement = Verbatim "with Ada.Characters.Latin_1; ", description = "name `Ada.Characters.Latin_1` in a with clause"} -- one with clause for the unit, however many uses of ASCII it has: the fix-its of a check -- are applied together, and one use's fix-it already brings it earlier <- gets (.diagnostics) let withClause = [clause | null latin, clause `notElem` concatMap (.fixes) earlier] report (diagnostic ObsolescentLibraryName Semantic ("`ASCII` is an obsolescent name for the characters of `Ada.Characters.Latin_1`")) { primary = Just (label whole "Annex J.5 package") , fixes = Fix {span = whole, replacement = Verbatim ("Ada.Characters.Latin_1." <> modern), description = "write `Ada.Characters.Latin_1." <> modern <> "`"} : withClause } where -- (the names ASCII gives that Latin_1 spells otherwise, RM J.5, A.3.3) renamed = [ ("exclam", "Exclamation"), ("quotation", "Quotation"), ("sharp", "Number_Sign"), ("dollar", "Dollar_Sign") , ("percent", "Percent_Sign"), ("ampersand", "Ampersand"), ("colon", "Colon"), ("semicolon", "Semicolon") , ("query", "Question"), ("at_sign", "Commercial_At"), ("l_bracket", "Left_Square_Bracket") , ("back_slash", "Reverse_Solidus"), ("r_bracket", "Right_Square_Bracket"), ("circumflex", "Circumflex") , ("underline", "Low_Line"), ("grave", "Grave"), ("l_brace", "Left_Curly_Bracket"), ("bar", "Vertical_Line") , ("r_brace", "Right_Curly_Bracket"), ("tilde", "Tilde") ] -- | The formal a name selects when the prefix is the generic unit's own name, denoting the -- current instance (and not something declared since under the same name): `G.Size`. instanceFormal :: A.Expr -> Maybe Denotation -> Text -> Sema (Maybe DeclId) instanceFormal prefix denoted selector = case prefix.node of A.ENameRef g -> selecting g -- (or its expanded name: `Ada.Text_IO.Wide_Generic.Mode`) A.ESelected sel | A.SelectIdentifier g <- sel.selector -> selecting g _ -> pure Nothing where selecting g = do formals <- asks (lookup (folded g.text) . (.formalsMaking)) self <- currentInstance g.text let current = case (self, denoted) of (Just (DPackage a), Just (DPackage b)) -> a == b (Just (DOverloaded [a]), Just (DOverloaded bs)) -> a `elem` bs _ -> False pure if current then lookup (folded selector) =<< formals else Nothing -- | Inside an instance's text, the generic unit's name denotes the instance, the current -- instance (RM 8.6(18)): `G.Get` in the body of the generic package G. currentInstance :: Text -> Sema (Maybe Denotation) currentInstance genericName = do making <- asks (.instancesMaking) case lookup (folded genericName) making of Nothing -> pure Nothing Just instanceName -> do owners <- gets (mapMaybe (.owner) . (.scopes)) named <- filterM (\o -> (\x -> folded x.name == folded instanceName) <$> entity o) owners case named of o : _ -> entity o <&> \x -> case x.kind of EPackage _ -> Just (DPackage o) ESubprogram _ -> Just (DOverloaded [o]) _ -> Nothing [] -> pure Nothing -- | A unit named only by a `private with` of the library unit being declared, used outside -- its private part (RM 10.1.2(11)): its visible part is what other units see, and cannot -- depend on what only the private part may name. privateWithUse :: Span -> Text -> Denotation -> Sema () privateWithUse s n = \case DPackage p -> do hidden <- asks (.privateWithed) when (p `elem` hidden) do unit <- asks (.unitName) scs <- gets (.scopes) inPrivatePart <- or <$> forM [o | sc <- scs, sc.kind == PackageScope, sc.privateVisible, Just o <- [sc.owner]] \o -> (\x -> folded x == folded unit) <$> fullName o already <- gets (any (\d -> d.code == UndefinedName && fmap (.span) d.primary == Just s) . (.diagnostics)) unless (inPrivatePart || already) $ report (diagnostic UndefinedName Semantic ("`" <> n <> "` is named by a `private with`, so only the private part of `" <> unit <> "` and its body can use it")) { primary = Just (label s "used in the visible part") , advice = Just "move this declaration to the private part, or name the unit in a plain `with` clause" } _ -> pure () -- | The discrete range of an iterated component association (Varc's names resolved first, -- 'resolvedDomain'). rangeDomain :: A.IterationDomain -> Maybe A.DiscreteRange rangeDomain = \case A.InRange dr -> Just dr A.InNamed n -> Just (A.DiscreteSubtype A.SubtypeIndication {span = n.span, notNull = False, mark = n, constraint = Nothing}) A.OfContainer _ -> Nothing -- | An iterated component association with Varc's @for e in a@ resolved, as a loop's is. resolvedDomain :: A.ComponentAssoc -> Sema A.ComponentAssoc resolvedDomain = \case A.IteratedAssocNode it -> do domain <- iterationDomain it.iterator.domain let iterator = A.Iterator {parameter = it.iterator.parameter, subtype = it.iterator.subtype, reverse = it.iterator.reverse, domain, filter = it.iterator.filter, whileCondition = it.iterator.whileCondition, alongside = it.iterator.alongside} pure (A.IteratedAssocNode A.IteratedAssoc {span = it.span, iterator, value = it.value}) other -> pure other -- | An iteration domain with its names resolved: Varc's @for e in a@ ranges over a subtype, -- or iterates over an array (Ada's @for E of A@), by what @a@ denotes. -- | The scheme of `for` over an iterator (a loop's, or a value sequence's, `[for X of A => -- ...]'Reduce`): over a range, an array's components (an index, the parameter naming the -- component there), or an `Iterable` container's cursors. Its parameter is declared in the -- current scope. forScheme :: A.Iterator -> Sema LoopScheme forScheme it = iterationDomain it.domain >>= \case A.InRange dr -> do (sub, range) <- discreteRange dr parameter <- declare it.parameter.text it.parameter.span (EObject ObjectInfo {subtype = sub, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}) steps <- mapM stepSource it.alongside kept <- traverse boolean it.filter stopping <- traverse boolean it.whileCondition pure (For TFor {parameter, subtype = sub, range, reverse = it.reverse, filter = kept, stop = stopping, lockstep = steps, further = []}) A.OfContainer container -> do -- `for E of A`: an index over A'Range, and E naming A (Index) array <- expression AnyType container kind <- fullKind array.typeOf case kind of -- (a multidimensional array's: an index for each dimension, the last varying fastest) KArray a | ix : rest <- a.indices -> do range <- arrayRangeOf 1 array a ix index <- newEntity Entity {name = it.parameter.text <> "'Index", span = it.parameter.span, parent = Nothing, kind = EObject ObjectInfo {subtype = ix, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}} further <- forM (zip [2 ..] rest) \(k, ixk) -> do rk <- arrayRangeOf k array a ixk d <- newEntity Entity {name = it.parameter.text <> "'Index_" <> tshow k, span = it.parameter.span, parent = Nothing, kind = EObject ObjectInfo {subtype = ixk, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}} pure TDimension {index = d, subtype = ixk, extent = rk} indexRefs <- forM ((index, ix) : [(d.index, d.subtype) | d <- further]) \(d, sub) -> mkExpr it.parameter.span sub.base (TObject d) element <- mkExpr it.parameter.span a.component.base (TIndexedNode TIndexed {prefix = array, indices = indexRefs}) variable <- isVariable array _ <- declare it.parameter.text it.parameter.span (EObject ObjectInfo {subtype = a.component, constant = not variable, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Just element}) unless (null further) (modify' \st -> st {multidimensional = Map.insert container.span (length a.indices) st.multidimensional}) steps <- mapM stepSource it.alongside kept <- traverse boolean it.filter stopping <- traverse boolean it.whileCondition pure (For TFor {parameter = index, subtype = ix, range, reverse = it.reverse, filter = kept, stop = stopping, lockstep = steps, further}) KError -> pure Forever _ -> iterationOf array.typeOf >>= \case -- a container with `Iterable`: a cursor over it, E naming its element there Just iteration -> do cursor <- newEntity Entity {name = it.parameter.text <> "'Cursor", span = it.parameter.span, parent = Nothing, kind = EObject ObjectInfo {subtype = unconstrained iteration.cursor, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}} source <- iteratedOnce it.parameter array element <- elementAt it.parameter.span source iteration cursor _ <- declare it.parameter.text it.parameter.span (EObject ObjectInfo {subtype = unconstrained iteration.elementType, constant = True, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Just element}) steps <- mapM stepSource it.alongside kept <- traverse boolean it.filter stopping <- traverse boolean it.whileCondition pure (OverCursors TCursors {cursor, container = source, iteration, filter = kept, stop = stopping, lockstep = steps}) Nothing -> do reportAt WrongKindOfEntity container.span "`for ... of` iterates over the components of an array, or the elements of a container whose type has `Iterable`" "not an array or an iterable container" pure Forever -- resolved by iterationDomain A.InNamed _ -> pure Forever -- | `Y of B` or `J in L .. H` walked in step: a position from the low bound, the parameter -- naming it (a range's) or the component at it (an array's) stepSource :: A.Lockstep -> Sema TLockstep stepSource l = iterationDomain l.domain >>= \case A.InRange dr -> do (sub, range) <- discreteRange dr position <- declare l.parameter.text l.parameter.span (EObject ObjectInfo {subtype = sub, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}) pure TLockstep {position, low = range.low, high = range.high, over = Nothing, further = []} A.OfContainer container -> do array <- expression AnyType container kind <- fullKind array.typeOf case kind of -- (a multidimensional array's: an index for each dimension, the last fastest) KArray a | ix : rest <- a.indices -> do range <- arrayRange array a ix position <- newEntity Entity {name = l.parameter.text <> "'Index", span = l.parameter.span, parent = Nothing, kind = EObject ObjectInfo {subtype = ix, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}} further <- forM (zip [2 ..] rest) \(k, ixk) -> do rk <- arrayRangeOf k array a ixk d <- newEntity Entity {name = l.parameter.text <> "'Index_" <> tshow k, span = l.parameter.span, parent = Nothing, kind = EObject ObjectInfo {subtype = ixk, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}} pure TDimension {index = d, subtype = ixk, extent = rk} ats <- forM ((position, ix) : [(d.index, d.subtype) | d <- further]) \(d, sub) -> mkExpr l.parameter.span sub.base (TObject d) element <- mkExpr l.parameter.span a.component.base (TIndexedNode TIndexed {prefix = array, indices = ats}) variable <- isVariable array _ <- declare l.parameter.text l.parameter.span (EObject ObjectInfo {subtype = a.component, constant = not variable, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Just element}) unless (null further) (modify' \st -> st {multidimensional = Map.insert container.span (length a.indices) st.multidimensional}) pure TLockstep {position, low = range.low, high = range.high, over = Nothing, further} KError -> pure TLockstep {position = DeclId 0, low = array, high = array, over = Nothing, further = []} _ -> -- a container with `Iterable`: a cursor of its own, the parameter naming its element iterationOf array.typeOf >>= \case Just iteration -> do -- (of `First`'s result subtype, which `Next` keeps too: what a loop's head -- then knows of it, where nothing else bounds it) firstInfo <- entity iteration.first let cursorSubtype = case firstInfo.kind of ESubprogram SubprogramInfo {result = Just r} -> r _ -> unconstrained iteration.cursor cursor <- newEntity Entity {name = l.parameter.text <> "'Cursor", span = l.parameter.span, parent = Nothing, kind = EObject ObjectInfo {subtype = cursorSubtype, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}} source <- iteratedOnce l.parameter array element <- elementAt l.parameter.span source iteration cursor _ <- declare l.parameter.text l.parameter.span (EObject ObjectInfo {subtype = unconstrained iteration.elementType, constant = True, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Just element}) pure TLockstep {position = cursor, low = source, high = source, over = Just (source, iteration), further = []} Nothing -> do reportAt WrongKindOfEntity container.span "a source in step is an array, a range, or a container whose type has `Iterable`" "not iterable" pure TLockstep {position = DeclId 0, low = array, high = array, over = Nothing, further = []} A.InNamed _ -> do notYetSupported l.parameter.span "this source in step" T25b errorExpr l.parameter.span >>= \e -> pure TLockstep {position = DeclId 0, low = e, high = e, over = Nothing, further = []} -- | The container a `for ... of` iterates, as the loop uses it: a function's result is -- evaluated once, before the loop (RM 5.5.2), and named by a hidden constant renaming it, -- which the loop's `First`, `Has_Element`, `Next` and element calls all read; any other -- container as it is. iteratedOnce :: A.Identifier -> TExpr -> Sema TExpr iteratedOnce parameter container = case container.node of TCallNode _ -> do source <- newEntity Entity {name = parameter.text <> "'Source", span = parameter.span, parent = Nothing, kind = EObject ObjectInfo {subtype = unconstrained container.typeOf, constant = True, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Just container}} mkExpr container.span container.typeOf (TObject source) _ -> pure container iterationDomain :: A.IterationDomain -> Sema A.IterationDomain iterationDomain = \case A.InNamed n -> do container <- case n.node of A.ENameRef i -> do es <- mapM entity =<< lookupDirect i.text pure (not (null es) && not (any (isSubtypeKind . (.kind)) es)) _ -> denote n >>= \case Just (DSubtype _) -> pure False Just DNone -> pure False _ -> pure True -- (recorded for a translation to a syntax that tells them apart, Vada's `of`: a field -- that holds a container is no object the units declare) when container (modify' \st -> st {surfaceForms = ((n.span, "of"), AsOperand) : st.surfaceForms}) pure if container then A.OfContainer n else A.InRange (A.DiscreteSubtype A.SubtypeIndication {span = n.span, notNull = False, mark = n, constraint = Nothing}) d -> pure d where isSubtypeKind = \case EType _ -> True ESubtype _ -> True _ -> False classify :: Span -> Text -> [DeclId] -> Sema Denotation classify s n ds = do es <- mapM entity ds if all (isOverloadable . (.kind)) es then pure (DOverloaded ds) else case zip ds es of [(d, e)] -> pure case e.kind of EObject _ -> DObjectLike d ENamedNumber _ -> DObjectLike d EState _ -> DObjectLike d EType t -> DSubtype (namedSubtype d t.first) ESubtype st -> DSubtype (namedSubtype d st) EPackage _ -> DPackage d EException -> DException d ELabel -> DLabel d EGeneric _ -> DGeneric d _ -> DNone several -> do report (diagnostic AmbiguousName Semantic ("`" <> n <> "` is ambiguous")) { primary = Just (label s "could mean several declarations") , secondary = [Label {span = e.span, text = Just "one candidate"} | (_, e) <- several] , advice = Just "qualify the name with its package, e.g. `P.Name`" } pure DNone -- | The subtype a subtype mark denotes (B1004 when it is something else). subtypeMarkOf :: A.Expr -> Sema Subtype subtypeMarkOf e = do st <- std case e.node of A.EAttribute a | A.foldedName a.designator == "base" -> do s <- subtypeMarkOf a.prefix pure (unconstrained s.base) A.EAttribute a | A.foldedName a.designator == "class" -> do s <- subtypeMarkOf a.prefix kind <- fullKind s.base tagInfoOf s.base >>= \case Just ti -> pure (unconstrained ti.classWide) Nothing | KError <- kind -> pure (unconstrained st.errorType) Nothing -> do reportAt WrongKindOfEntity e.span "only tagged types have class-wide types" "not a tagged type" pure (unconstrained st.errorType) _ -> denote e >>= \case Just (DSubtype s) -> pure s Just DNone -> pure (unconstrained st.errorType) -- a task or protected type (a generic package underneath) as a type: of an access -- type's allocated objects or of components, tasks made at run time or in numbers Just (DGeneric g) -> do objectType <- gets (Map.lookup g . (.generics)) <&> \case Just src | AD.DPackage p <- src.unit.node -> any (\a -> A.foldedName a.mark == "verada_object_type") p.aspects _ -> False if objectType then reportExcluded e.span "task and protected types as designated or component types are not in Verada" dynamicTaskReplacement else reportAt WrongKindOfEntity e.span "a type or subtype is required here" "not a type" pure (unconstrained st.errorType) _ -> do reportAt WrongKindOfEntity e.span "a type or subtype is required here" "not a type" pure (unconstrained st.errorType) -- * Expressions expression :: Expect -> A.Expr -> Sema TExpr expression expect e = do before <- gets (length . (.expressionChecks)) value0 <- expressionWithoutOrigins expect e -- (the compatibility checks of the constraints written in this expression that only it -- can make, its bounds' names bound around it: before it) made <- gets (.expressionChecks) let fresh = take (length made - before) made value <- if null fresh then pure value0 else do modify' \st -> st {expressionChecks = drop (length fresh) made} pure TExpr {span = value0.span, typeOf = value0.typeOf, static = Nothing, node = TCheckedNode TChecked {checks = reverse fresh, value = value0}} candidates <- asks (Map.findWithDefault [] e.span . (.aplOriginTargets)) forM_ [target | target <- candidates, target.generated == e] \target -> do coordinateValues <- checkedOriginPositions target.site.positions let site = target.site retained = TypedAplOrigin {embedding = target.embedding , payloadRange = (site.source.start - target.payloadBase, site.source.end - target.payloadBase) , rank = site.rank, positions = site.positions, coordinateValues, generatedPath = site.generatedPath, checked = value} known <- gets (.aplOrigins) if retained `elem` known then pure () else if length (take 513 known) >= 512 then modify' (\state -> state {aplOriginFailure = Just "Typed origin retention exceeds 512 checked expressions."}) else modify' (\state -> state {aplOrigins = retained : state.aplOrigins}) pure value -- Coordinate metadata is checked against the scope at the original element -- computation. Run in an isolated semantic state: even memo/overload activity -- must not alter the ordinary checked program. Complex or effectful coordinate -- recipes remain unavailable rather than adding work or calls to a probe. checkedOriginPositions :: [A.Expr] -> Sema (Maybe [TExpr]) checkedOriginPositions positions | not (all (simple (0 :: Int)) positions) = pure Nothing | otherwise = do context <- ask saved <- get let (values, after) = runSema context {aplOriginTargets = Map.empty} saved {diagnostics = []} (mapM (expression (Expect context.standard.integer)) positions) known x = IntMap.member (typeKey x.typeOf) saved.types && case x.node of TObject (DeclId d) -> IntMap.member d saved.entities TLiteral _ -> True TBinaryNode _ -> all known (subExpressions x) TUnaryNode _ -> all known (subExpressions x) TAttributeNode a | a.attribute `elem` [AFirst, ALast, ALength] -> all known (subExpressions x) _ -> False pure (if any Diagnostics.isError after.diagnostics || not (all known values) then Nothing else Just values) where typeKey (TypeId key) = key simple depth x | depth >= 16 = False | otherwise = case x.node of A.ENameRef _ -> True A.EInteger _ -> True A.EParen y -> simple (depth + 1) y A.EUnary u -> simple (depth + 1) u.operand A.EBinary b -> simple (depth + 1) b.left && simple (depth + 1) b.right A.EAttribute a -> Text.toCaseFold a.designator.text `elem` ["first", "last", "length"] && simple (depth + 1) a.prefix && all (simple (depth + 1)) a.arguments _ -> False -- Type-check exactly the ordinary generated AST. Origin targets are an external -- lookup table, so shape inference, overload trials and static folding never see -- marker wrappers or different expected types. expressionWithoutOrigins :: Expect -> A.Expr -> Sema TExpr expressionWithoutOrigins expect e = do st <- std case e.node of A.ENameRef _ -> named A.ESelected _ -> named A.EInteger n -> mkExpr e.span st.universalInteger (TLiteral (StaticInteger n)) >>= conform expect -- (a literal of over 65,536 bits: a universal integer's value, expanded as it is used, and -- beyond every typed integer, which is told without expanding it, D185) A.ELargeInteger s -> do universal <- case expect of AnyType -> pure True Expect t -> isUniversal t if universal then expressionWithoutOrigins expect e {A.node = A.EInteger (integerValue s)} else do name <- case expect of Expect t -> typeName t AnyType -> pure "the type" reportAt StaticValueOutOfRange e.span ("this literal, of over 65,536 bits, does not fit in `" <> name <> "`") "too large for the type" errorExpr e.span A.EReal r -> mkExpr e.span st.universalReal (TLiteral (StaticReal r)) >>= conform expect A.ECharacter c -> characterLiteral expect e.span c A.EString s -> stringLiteral expect e.span s A.EParen inner -> withSpan e.span <$> expression expect inner A.EOrigin origin -> expression expect origin.value A.EApply ap | Just call <- operatorCall ap -> do r <- expression expect A.Expr {span = e.span, node = call} namedOperands ap r pure r | otherwise -> apply expect e.span ap A.EAttribute at -> attribute expect e.span at A.EPipeline p -> expression expect A.Expr {span = e.span, node = pipelineNode e.span p} A.ECodeString c -> codeString expect e.span c A.EQualified q -> do target <- subtypeMarkOf q.mark operand <- expression (Expect target.base) q.operand mkExpr e.span target.base (TConversionNode TConversion {target, operand, qualified = True}) >>= staticInSubtype target >>= conform expect A.EUnary u -> unary expect e.span u A.EBinary b -> binary expect e.span b A.EMembership m -> membership expect e.span m A.EAggregate ag -> aggregate expect e.span ag A.EIf i -> ifExpression expect e.span i A.ECase c -> caseExpression expect e.span c A.EQuantified q -> quantified expect e.span q A.ETargetName -> asks (.assignmentTarget) >>= \case Just target -> conform expect (withSpan e.span target) Nothing -> do reportAt MisplacedAttribute e.span "`@` stands for the target of an assignment and is only allowed in its value" "not in an assignment" errorExpr e.span A.ENull -> case expect of Expect t -> do kind <- fullKind t optionals <- optionalsHere optional <- if optionals then optionalType t else pure Nothing case kind of -- (Vibe's `None` where a `T | None` is wanted: its `None`) _ | Just o <- optional -> optionalCall e.span t o.none [] KAccess _ -> mkExpr e.span t TNull KSubprogramAccess _ -> mkExpr e.span t TNull KError -> errorExpr e.span _ -> do tn <- typeName t reportAt TypeMismatch e.span ("`null` is a value of an access type, but `" <> tn <> "` is expected here") "not an access type" errorExpr e.span AnyType -> do reportAt TypeMismatch e.span "the type of `null` is not known here" "an access type is required" errorExpr e.span A.EDereference p -> do prefix <- expression AnyType p kind <- fullKind prefix.typeOf wanted <- case expect of Expect t -> fullKind t AnyType -> pure KError case (kind, wanted) of -- `F.all` where a value of another type is wanted: a call of the designated -- parameterless function (KSubprogramAccess _, w) | wantsValue w -> indexWith expect e.span p.span prefix [] _ -> dereference e.span prefix >>= conform expect A.EAllocator a -> allocator expect e.span a A.EDeclare d -> declareExpression expect e.span d A.ERaise r -> raiseExpression expect e.span r -- Varc's implicit instances name types only, and become instance units before analysis A.EInstance _ -> reportAt WrongKindOfEntity e.span "a generic instance names a type here, `G.T`, not a value" "an instance in an expression" >> errorExpr e.span -- a Python string: a text where a text is wanted, or where nothing says (Python's `str` -- is a text, T30); else the string itself -- (a Varc string literal is a text only where a text is wanted, as To_Text would be) A.ESurfaceForm A.SurfaceForm {kind = formKind, operands = [x]} | formKind `elem` [A.FormText, A.FormLiteralText] -> do st0 <- std textType <- fst <$> trial (denote (dottedExpr e.span ["Verada", "Strings", "Texts", "Text"])) wanted <- case expect of -- (where a `str | None` is wanted, a text, which is then that one present) Expect t -> fullKind t >>= \_ -> optionalType t <&> \case Just o -> Just o.element Nothing -> Just t AnyType -> pure Nothing -- (the operand's own shapes, not the memo's: a form and its operand share a span) operandShapes <- fst <$> trial (shapesOf x) let toText = case (textType, wanted) of (Just (DSubtype tt), Just t) -> t == tt.base (Just (DSubtype _), Nothing) -> formKind == A.FormText _ -> False -- (already a text: itself) isText = case textType of Just (DSubtype tt) -> Exactly tt.base `elem` operandShapes _ -> False -- (a literal beyond Latin-1: a text of its code points, D171) wide = case x.node of A.EString t -> Text.any (\c -> ord c > 255) t _ -> False -- (a text where a String is wanted, an interpolation given to `Put_Line`: its -- characters, D189) wantsString = wanted == Just st0.string && isText r | wantsString = AsCall "Verada.Strings.Texts.To_String" 0 | toText && isText = AsOperand | toText && wide = AsCall "Verada.Strings.Texts.To_Text_Of" 0 | toText = AsCall "Verada.Strings.Texts.To_Text" 0 | otherwise = AsOperand modify' \state -> state {surfaceForms = ((e.span, A.surfaceFormName formKind), r) : state.surfaceForms} expression expect (resolvedExpr e.span r [x]) A.ESurfaceForm f0 -> do -- (an optional value a form works on, `s.upper()` of a `str | None`: its value) f <- case f0.operands of x : rest | narrowable f0.kind -> ownOperation f0.kind x >>= \case -- (an optional value's own operation, Varc's `o.Value()` that `??` and `if let` -- write, works on it) True -> pure f0 False -> narrowed x <&> \x' -> A.SurfaceForm {kind = f0.kind, operands = x' : rest} _ -> pure f0 lookup' <- optionalLookup expect e.span f maybe (formResolution False e.span f) (pure . Just) lookup' >>= \case Just r -> expression expect (resolvedFormExpr e.span r f) Nothing -> errorExpr e.span where ownOperation kind x = case kind of A.FormMethod m _ -> do (probe, _) <- trial (expression AnyType x) optionalType probe.typeOf >>= \case Just _ -> not . null <$> primitivesNamed m.text probe.typeOf Nothing -> pure False _ -> pure False -- (an image is of the optional value itself; a construction's first operand is a type) narrowable = \case A.FormImage -> False A.FormConstruct _ -> False _ -> True named = denote e >>= \case Nothing -> selectedComponent expect e Just d -> useDenotation expect e.span d [] -- | @A.B.C@ from its parts. dottedExpr :: Span -> [Text] -> A.Expr dottedExpr s = \case [] -> A.Expr {span = s, node = A.ENameRef A.Identifier {span = s, text = ""}} first : rest -> foldl (\p n -> A.Expr {span = s, node = A.ESelected A.Selected {prefix = p, selector = A.SelectIdentifier A.Identifier {span = s, text = n}}}) (A.Expr {span = s, node = A.ENameRef A.Identifier {span = s, text = first}}) rest -- | A name used as a value: an object, a parameterless call or an enumeration literal. useDenotation :: Expect -> Span -> Denotation -> [A.Argument] -> Sema TExpr useDenotation expect s d args = case d of DObjectLike o -> do e <- entity o case e.kind of EObject info -> checkReferenceLevel s o >> mkExpr s info.subtype.base (TObject o) >>= conform expect ENamedNumber v -> do st <- std let t = case v of StaticReal _ -> st.universalReal _ -> st.universalInteger mkExpr s t (TLiteral v) >>= conform expect EState _ -> do reportAt WrongKindOfEntity s ("`" <> e.name <> "` is a state abstraction, which names variables but has no value") "not a value" errorExpr s _ -> errorExpr s DOverloaded ds -> resolveCall CallFunction expect s ds args DSubtype _ -> wrongKind "a type" DPackage _ -> wrongKind "a package" DException _ -> wrongKind "an exception" DLabel _ -> wrongKind "a loop or block name" DGeneric _ -> wrongKind "a generic unit (instantiate it first)" DNone -> errorExpr s where wrongKind what = do reportAt WrongKindOfEntity s ("this names " <> what <> ", but a value is required here") ("names " <> what) errorExpr s -- | A value that is a call of procedures only (by the method's resolution for a surface form): -- what to call, and with what. resultProcedure :: A.Expr -> Sema (Maybe A.Apply) resultProcedure v = do callee <- case v.node of A.EApply ap -> pure (Just ap) -- (a method's call, or a call by name of a capitalised name, `ops.Split(N=7)`) A.ESurfaceForm f | isCallForm f.kind -> fst <$> trial (formResolution False v.span f) >>= \case Just r | A.EApply ap <- (resolvedFormExpr v.span r f).node -> pure (Just ap) _ -> pure Nothing _ -> pure Nothing case callee of Just ap -> do -- (by name, or as a prefixed view: a protected object's operation, a primitive) viewed <- case ap.prefix.node of A.ESelected sel -> fst <$> trial (prefixedView sel) _ -> pure Nothing denoted <- fst <$> trial (denote ap.prefix) let candidates = case (denoted, viewed) of (Just (DOverloaded ds@(_ : _)), _) -> ds (_, Just ds) -> ds _ -> [] kinds <- mapM (fmap (.kind) . entity) candidates pure if not (null kinds) && all isProcedure kinds then Just ap else Nothing Nothing -> pure Nothing where isProcedure = \case ESubprogram i -> i.kind == Procedure _ -> False isCallForm = \case A.FormMethod _ _ -> True A.FormConstruct _ -> True _ -> False -- | A value that is a call of procedures only, with as many results as a target takes -- (vibe-syntax LN10): what to call, and its parameters (after a prefixed view's object), -- when every candidate the call's arity and names fit has the same ones. resultFormals :: Int -> A.Expr -> Sema (Maybe (A.Apply, [ResultFormal])) resultFormals targets v = resultProcedure v >>= \case Nothing -> pure Nothing Just ap -> do denoted <- fst <$> trial (denote ap.prefix) viewed <- case (denoted, ap.prefix.node) of (Just (DOverloaded (_ : _)), _) -> pure Nothing (_, A.ESelected sel) -> fst <$> trial (prefixedView sel) _ -> pure Nothing let (candidates, implicitObject) = case (denoted, viewed) of (Just (DOverloaded ds@(_ : _)), _) -> (ds, False) (_, Just ds) -> (ds, True) _ -> ([], False) positional = length [() | A.Argument {formal = Nothing} <- ap.arguments] named = [A.foldedName f | A.Argument {formal = Just f} <- ap.arguments] -- (the type of each candidate's first parameter, which tells apart the operations of -- several types of one name, `Verada_Enter (Manager)`) firsts <- forM candidates \d -> entity d >>= \e -> case e.kind of ESubprogram info | not implicitObject, p : _ <- info.parameters -> entity p <&> \pe -> case pe.kind of EObject o -> Just o.subtype.base _ -> Nothing _ -> pure Nothing profiles <- forM candidates \d -> entity d >>= \e -> case e.kind of ESubprogram info -> Just <$> forM (if implicitObject then drop 1 info.parameters else info.parameters) \p -> do pe <- entity p case pe.kind of EObject o -> do scalar <- isScalar o.subtype.base mark <- traverse fullName o.subtype.name let mode = fromMaybe ModeIn o.mode pure ResultFormal {name = pe.name, input = mode /= ModeOut, result = mode == ModeOut || (mode == ModeInOut && scalar), mark, changed = mode /= ModeIn} _ -> pure ResultFormal {name = pe.name, input = True, result = False, mark = Nothing, changed = False} _ -> pure Nothing let fits formals = let inputs = [Text.toCaseFold f.name | f <- formals, f.input] in length [() | f <- formals, f.result] == targets && positional + length named == length inputs && all (`elem` drop positional inputs) named firstType <- case ap.arguments of A.Argument {formal = Nothing, value = A.ArgExpr x} : _ -> Just . (.typeOf) . fst <$> trial (expression AnyType x) _ -> pure Nothing let fitting = [(fs, first) | (Just fs, first) <- zip profiles firsts, fits fs] ofFirst = [fs | (fs, Just t) <- fitting, Just t == firstType] pure case (nub (map fst fitting), nub ofFirst) of ([formals], _) -> Just (ap, formals) (_, [formals]) -> Just (ap, formals) _ -> Nothing -- | What a surface form (Vibe's @len(x)@, @x[i]@, @str(x)@, @x.m(...)@) means, by its first -- operand's type, recorded for translation (or reported when it means nothing). Storing -- through it (@x[i] = v@, the flag) changes a container by its @Replace_Element@. formResolution :: Bool -> Span -> A.SurfaceForm -> Sema (Maybe FormResolution) formResolution storing s f0 = do f <- varcForm f0 r <- formResolutionOf storing s f -- (recorded by the name written too, which a translation looks for) when (f.kind /= f0.kind) do forM_ r \r' -> modify' \state -> state {surfaceForms = ((s, A.surfaceFormName f0.kind), r') : state.surfaceForms} pure r -- | Varc's names for the operations of a text, a list, a map or a set (Rust's, D189) as the -- forms Vibe's names are: an operation of the object's own type by the name written wins. varcForm :: A.SurfaceForm -> Sema A.SurfaceForm varcForm f = do varc <- asks (.varc) case (f.kind, f.operands) of (A.FormMethod m names, x : rest) | varc -> do (probe, _) <- trial (expression AnyType x) kind <- fullKind probe.typeOf own <- not . null <$> primitivesNamed m.text probe.typeOf tn <- typeName probe.typeOf let named n = A.SurfaceForm {kind = A.FormMethod A.Identifier {span = m.span, text = n} names, operands = f.operands} container = not (isArray kind) && any (`Text.isSuffixOf` tn) ["Vector", "Dictionary", "Set"] -- (a text's: Verada.Strings.Text_Operations' functions, by Python's names) textual = [("to_upper", "upper"), ("to_uppercase", "upper"), ("to_lower", "lower"), ("to_lowercase", "lower"), ("trim", "strip"), ("trim_start", "lstrip"), ("trim_end", "rstrip"), ("starts_with", "startswith"), ("ends_with", "endswith")] -- (a list's `remove(i)` and `insert(i, x)` are by position, from 0) collection | not container = [] | "Vector" `Text.isSuffixOf` tn = [("push", "append"), ("remove", "delete"), ("is_empty", "Is_Empty")] | "Dictionary" `Text.isSuffixOf` tn = [("insert", "Include"), ("remove", "Delete"), ("contains_key", "Contains"), ("get_or", "Get"), ("is_empty", "Is_Empty")] | "Set" `Text.isSuffixOf` tn = [("insert", "Include"), ("remove", "Exclude")] | otherwise = [] -- (a library container's or a text's Varc names first: its own `Remove` is by value, -- Varc's `remove(i)` by position) let library = container || tn == "Text" pure if | kind == KError -> f | own && not library -> f | m.text == "len", null rest, tn == "Text" || container || isArray kind -> A.SurfaceForm {kind = A.FormLength, operands = [x]} | m.text == "contains", [_] <- rest, tn == "Text" -> A.SurfaceForm {kind = A.FormContains, operands = f.operands} | tn == "Text", Just n <- lookup m.text textual -> named n | Just n <- lookup m.text collection -> named n | otherwise -> f _ -> pure f where isArray = \case KArray _ -> True _ -> False formResolutionOf :: Bool -> Span -> A.SurfaceForm -> Sema (Maybe FormResolution) formResolutionOf storing s f = case f.operands of [] -> pure Nothing -- `C(f=v)`: an aggregate when C is a type, else a call with named actuals x : _ | A.FormConstruct names <- f.kind -> do denoted <- fst <$> trial (denote x) let r = case denoted of Just (DSubtype _) -> AsAggregate (map (.text) names) _ -> AsNamedCall (map (.text) names) modify' \state -> state {surfaceForms = ((s, A.surfaceFormName f.kind), r) : state.surfaceForms} pure (Just r) -- `o.m(...)` where o.m names an operation of o itself (a protected object, which becomes -- a package): called through it x : _ | A.FormMethod m _ <- f.kind , isName x -> fst <$> trial (denote x) >>= \case Just (DPackage _) -> do let r = AsSelectedCall m.text modify' \state -> state {surfaceForms = ((s, A.surfaceFormName f.kind), r) : state.surfaceForms} pure (Just r) _ -> byType x x : _ -> byType x where isName x = case x.node of A.ENameRef _ -> True A.ESelected _ -> True _ -> False byType x = do (probe, _) <- trial (expression AnyType x) st <- std kind <- fullKind probe.typeOf tn <- typeName probe.typeOf -- (a class-wide value's operations are its root type's, and dispatch) owner <- case kind of KClassWide root -> pure root _ -> pure probe.typeOf let hasOperation n = not . null <$> primitivesNamed n owner -- a container's operation; its positions count from 1, Python's from 0 let operation n offset missing = case kind of KError -> pure Nothing _ -> primitivesNamed n owner >>= \case -- (by its simple name where that is visible, as in its own package) -- (by the shortest name that denotes it here: its own where that is visible, then -- through its package, as an outer name of the same spelling may hide the full -- one) d : _ -> do full <- fullName d let parts = Text.splitOn "." full suffixes = [Text.intercalate "." (drop k parts) | k <- reverse [0 .. length parts - 1]] name <- shortestDenoting s d suffixes full pure (Just (AsCall name offset)) [] -> Nothing <$ reportAt TypeMismatch x.span missing ("of type `" <> tn <> "`") python <- asks (.python) varc <- asks (.varc) let imageAsAda = do def <- typeDef probe.typeOf full <- maybe (pure tn) fullName def.decl pure (Just (AsImage full)) -- (the function of an `Enum` class that Vibe declares with it, `name` or `value`, by -- the name that denotes it here, and whether its result is a text; a primitive, or -- declared beside a type among a subprogram's declarations) enumFunction n = do candidates <- primitivesNamed n owner >>= \case [] -> fst <$> trial (denote A.Expr {span = s, node = A.ENameRef A.Identifier {span = s, text = n}}) <&> \case Just (DOverloaded ds) -> ds _ -> [] ds -> pure ds found <- filterM ofOwner candidates case found of d : _ -> do full <- fullName d let parts = Text.splitOn "." full suffixes = [Text.intercalate "." (drop k parts) | k <- reverse [0 .. length parts - 1]] name <- shortestDenoting s d suffixes full textual <- entity d >>= \e -> case e.kind of ESubprogram i | Just r <- i.result -> (== "Text") <$> typeName r.base _ -> pure False pure (Just (name, textual)) [] -> pure Nothing ofOwner d = entity d >>= \e -> case e.kind of ESubprogram i | [p] <- i.parameters, Just _ <- i.result -> entity p <&> \pe -> case pe.kind of EObject o -> o.subtype.base == owner _ -> False _ -> pure False -- (Python's str and repr of a list, a dict, a set or a tuple: its elements' reprs) collection <- if python && (case f.kind of { A.FormImage -> True; A.FormMethod m _ -> m.text == "Verada_Repr"; _ -> False }) then reprShape s probe.typeOf <&> \case Just r@ReprElements {} -> Just r Just r@ReprPairs {} -> Just r Just r@ReprItems {} -> Just r _ -> Nothing else pure Nothing -- (a Vibe class's str and repr: its own `__str__` and `__repr__`, or the repr Vibe makes -- for a dataclass, Python's, D188) ownStr <- if python && kind /= KError && (case f.kind of { A.FormImage -> True; _ -> False }) then hasOperation "Verada_Str" else pure False -- (its own `__repr__`, or the one Vibe makes for a dataclass) let reprNamed = do own <- hasOperation "Verada_Repr" made <- hasOperation "Verada_Made_Repr" pure (if own then Just "Verada_Repr" else if made then Just "Verada_Made_Repr" else Nothing) ownRepr <- if python && kind /= KError && (case f.kind of { A.FormMethod m _ -> m.text == "Verada_Repr"; _ -> False }) then reprNamed else pure Nothing -- (Python's str of an object without `__str__` is its repr) reprForStr <- if python && kind /= KError && not ownStr && (case f.kind of { A.FormImage -> True; _ -> False }) then reprNamed else pure Nothing resolved <- case (f.kind, kind) of _ | ownStr -> operation "Verada_Str" 0 "" _ | Just r <- reprForStr -> operation r 0 "" _ | Just r <- ownRepr -> operation r 0 "" (_, _) | Just r <- collection -> pure (Just (AsRepr r)) -- (the operand's own mistakes, which the probe kept to itself, are reported: a form -- around it, `print(x in 5)`, would otherwise fail for no reason it gives) (_, KError) -> Nothing <$ expression AnyType x -- (resolved by its name, before its operands' types) (A.FormConstruct _, _) -> pure Nothing -- (resolved by what is wanted, in 'expression') (A.FormText, _) -> pure (Just AsOperand) (A.FormLiteralText, _) -> pure (Just AsOperand) (A.FormLength, KArray _) -> pure (Just (AsAttribute "Length")) (A.FormLength, _) -> operation "Length" 0 ("`len()` takes an array, a string or a container, and `" <> tn <> "` has no `Length`") -- (by position from its first index, as Python's, when an array's bounds are each -- value's and its index type is Vibe's own, `Natural`; by value otherwise, as an -- `index=` type says) (A.FormItem, KArray a) -> pure (Just (AsIndex (not a.constrained && all ((== Just st.natural) . (.name)) a.indices))) -- a tuple's item, by a literal position (A.FormItem, KRecord r) | [_, A.Expr {node = A.EInteger k}] <- f.operands , let c = "Item_" <> Text.pack (show k) , any (\d -> folded d.name == Text.toCaseFold c) r.components -> pure (Just (AsComponent c)) -- a dict's store and lookup are by key; a list's by position (A.FormItem, _) | storing -> hasOperation "Replace_Element" >>= \case True -> operation "Replace_Element" 1 "" False -> operation "Include" 0 ("only an array, a string or a container is indexed, and `" <> tn <> "` has neither `Replace_Element` nor `Include`") -- (Python's s[i] is a str: the text of the code point there, D171) (A.FormItem, _) | not storing, tn == "Text" -> operation "Item" 1 "" (A.FormItem, _) | not storing -> hasOperation "Element" >>= \case True -> operation "Element" 1 "" False -> operation "Value" 0 ("only an array, a string or a container is indexed, and `" <> tn <> "` has neither `Element` nor `Value`") -- `x.value` and `x.name` of an enumeration (Vibe's `Enum`): its functions so named; of -- anything else, its component -- (by its name where the type is declared among a subprogram's declarations, where its -- functions are no primitives) (A.FormField field, KEnumeration _) -> hasOperation field.text >>= \case True -> operation field.text 0 "" False -> pure (Just (AsCall field.text 0)) (A.FormField field, _) -> pure (Just (AsComponent field.text)) -- Python's slice: an array's by position (from its first index), a text's code points, -- a container's own `Slice`; only an array's is stored into (lengths alike, as NumPy's) (A.FormSlice, KArray a) | [_] <- a.indices, all ((== Just st.natural) . (.name)) a.indices -> pure (Just AsSlice) | otherwise -> Nothing <$ reportAt TypeMismatch x.span "a slice takes positions of a sequence: an array of one dimension indexed by position (from 0), a string or a list" ("of type `" <> tn <> "`") (A.FormSlice, _) | storing -> Nothing <$ reportAt TypeMismatch x.span ("a slice is assigned to only in an array, whose length stays the same; for `" <> tn <> "`, build the new value and assign it whole") ("of type `" <> tn <> "`") (A.FormSlice, _) | tn == "Text" -> pure (Just AsTextSlice) (A.FormSlice, _) -> operation "Slice" 0 ("a slice takes positions of a sequence (an array, a string or a list), and `" <> tn <> "` is none") (A.FormContains, KArray _) -> pure (Just AsSomeElement) -- (`t in s` of texts: a substring) (A.FormContains, _) | tn == "Text" -> pure (Just (AsCall "Verada.Strings.Text_Operations.Contains" 0)) -- (a container without its own `Contains`, Python's list: one of its elements) (A.FormContains, _) -> do contains <- hasOperation "Contains" iterable <- gets (isJust . lookup owner . (.iterables)) if not contains && iterable then pure (Just AsSomeElement) else operation "Contains" 0 ("`in` asks an array or a container, and `" <> tn <> "` has no `Contains`") (A.FormItem, _) -> operation "Element" 1 ("only an array, a string or a container is indexed, and `" <> tn <> "` has no `Element`") -- (Python's int() truncates a float; of an integer it is the integer) (A.FormInt, KReal _) -> pure (Just AsTruncation) -- (Python's `int(s)` of a str: its decimal value, which it must have) (A.FormInt, _) | tn == "Text" -> pure (Just (AsCall "Verada.Vibe.Formatting.To_Integer" 0)) (A.FormInt, _) | probe.typeOf == st.universalReal -> pure (Just AsTruncation) -- (of another integer type, a RangeInt class's: the integer, as an `int`) (A.FormInt, KInteger _) | probe.typeOf /= st.integer, probe.typeOf /= st.universalInteger -> pure (Just (AsCall "Integer" 0)) (A.FormInt, _) -> pure (Just AsOperand) (A.FormImage, _) | probe.typeOf == st.string -> pure (Just AsOperand) -- (a text's image is the text, its code points: it is printed as UTF-8, and joins other -- pieces as a text, D171) (A.FormImage, _) | tn == "Text" -> pure (Just AsOperand) (A.FormImage, _) | probe.typeOf == st.character -> pure (Just AsCharacterString) -- (a float as Python writes it, not as `'Image` does) (A.FormImage, KReal _) -> pure (Just AsFloatImage) -- (a universal value, such as a length, has Integer's image) -- (Python's str of an exception is its message: `print(e)` of `except E as e`) (A.FormImage, _) | python , tn == "Exception_Occurrence" -> -- (its message's UTF-8 as a text: Vibe's messages are UTF-8, D176) pure (Just (AsCall "Verada.Vibe.Message_Text" 0)) -- (an optional value's: its value's, or `None` (Varc's `null`)) (A.FormImage, KRecord _) | python || varc -> optionalType probe.typeOf >>= \case Just o -> do hasFn <- denotingName s o.hasValue valueFn <- denotingName s o.value -- (the element's own image: of the form of its value, at places of their own, -- as the operand shares the form's) let at0 = Span {file = x.span.file, start = x.span.start, end = x.span.start} at1 = Span {file = x.span.file, start = x.span.end, end = x.span.end} valueOf = A.Expr {span = at1, node = A.EApply A.Apply {prefix = dottedExpr at1 (Text.splitOn "." valueFn), arguments = [A.Argument {span = at0, formal = Nothing, value = A.ArgExpr A.Expr {span = at0, node = A.EParen x}, reference = Nothing}], bracketed = Nothing}} elementName <- typeName o.element inner <- formResolution False at1 A.SurfaceForm {kind = A.FormImage, operands = [valueOf]} held <- if python then pure Nothing else Just <$> spelledType probe.typeOf pure ((\r -> AsOptionalImage hasFn valueFn r (elementName == "Text") (if python then "None" else "null") held) <$> inner) Nothing -> imageAsAda -- (Python's str of an `Enum` member is `Colour.RED`, its class's name and its own) (A.FormImage, KEnumeration _) | python -> enumFunction "name" >>= \case Just (nameFn, _) -> pure (Just (AsEnumImage tn nameFn)) Nothing -> imageAsAda (A.FormImage, _) | probe.typeOf == st.universalInteger -> pure (Just (AsImage "Integer")) | probe.typeOf == st.universalReal -> pure (Just AsFloatImage) | otherwise -> imageAsAda -- (Python's names for operations Verada's containers name otherwise) -- (the element at a position from 0 in the order a `for` takes them: Vibe's -- comprehensions over a container walk it by position) (A.FormMethod m _, KArray _) | m.text == "Verada_Element_At" -> pure (Just (AsIndex True)) (A.FormMethod m _, _) | m.text == "Verada_Element_At" -> if tn == "Text" then operation "Item" 1 "" else hasOperation "Iter_Element" >>= \case True -> operation "Iter_Element" 1 "" False -> operation "Iter_Key" 1 ("`" <> tn <> "` is not iterated by position") -- (`d.get(k)` would be `None` for a missing key, which a `dict`'s value is not) (A.FormMethod m _, _) | Text.toLower m.text == "get" , "Dictionary" `Text.isSuffixOf` tn , length f.operands == 2 -> Nothing <$ reportAt TypeMismatch s "`d.get(k)` gives `None` for a missing key, a `V | None`, which needs its type here: write `v: int | None = d.get(k)`, or `d.get(k, default)`" "no default" -- (Python's repr: a str's with its quotes, another value's its str) -- (an `Enum` member's repr, ``, by its value where it has one) (A.FormMethod m _, KEnumeration _) | m.text == "Verada_Repr" , python -> (,) <$> enumFunction "name" <*> enumFunction "value" >>= \case (Just (nameFn, _), Just (valueFn, textual)) -> pure (Just (AsEnumRepr tn nameFn valueFn textual)) _ -> formResolution storing s A.SurfaceForm {kind = A.FormImage, operands = f.operands} (A.FormMethod m _, _) | m.text == "Verada_Repr" -> if tn == "Text" then pure (Just (AsCall "Verada.Vibe.Formatting.Repr" 0)) else formResolution storing s A.SurfaceForm {kind = A.FormImage, operands = f.operands} -- (Varc's `s.find(t)`, Rust's: an optional position from 0, a `Natural?`, D189) (A.FormMethod m _, _) | tn == "Text" , m.text == "find" -> asks (.varc) >>= \case True -> do optional <- fst <$> trial (denote (dottedExpr s ["Instance_Verada_Optionals_Natural", "Optional"])) found <- case optional of Just (DSubtype o) -> optionalType o.base _ -> pure Nothing case found of Just o -> Just <$> (AsOptionalPosition "Verada.Strings.Text_Operations.Find" <$> denotingName s o.just <*> denotingName s o.none) -- (Varc's files name the instance where they call `find`, Verada.Varc.Sugar) Nothing -> Nothing <$ reportAt UndefinedName x.span "a text's `find` gives a `Natural?`, Verada.Optionals' instance for `Natural`, which is not visible here" "a text" False -> pure (Just (AsPosition "Verada.Strings.Text_Operations.Find" 0)) -- (a str's methods are Verada.Strings.Text_Operations' functions, Python's positions -- from 0) (A.FormMethod m _, _) | tn == "Text" , Just (op, position) <- lookup (Text.toLower m.text) textMethods -> do let full = "Verada.Strings.Text_Operations." <> op pure (Just (if position then AsPosition full 0 else AsCall full 0)) -- (`xs.index(x)` of a list: its position from 0) (A.FormMethod m _, _) | Text.toLower m.text == "index" , "Vector" `Text.isSuffixOf` tn -> operation "Index" 0 "" >>= \case Just (AsCall name _) -> pure (Just (AsPosition name 0)) r -> pure r -- (a list's operations that need its elements' order, Python's `<`: a generic of the -- list's package, instantiated where it is called) (A.FormMethod m _, _) | Just op <- lookup (Text.toLower m.text) orderedMethods , "Vector" `Text.isSuffixOf` tn -> do def <- typeDef owner package <- maybe (pure Nothing) (fmap (.parent) . entity) def.decl generic <- maybe (pure []) (`lookupInPackage` op) package case (package, generic) of (Just p, _ : _) -> do full <- fullName p pure (Just (AsCall (full <> "." <> op) 0)) _ -> Nothing <$ reportAt TypeMismatch x.span ("`" <> tn <> "` has no operation `" <> m.text <> "`") ("of type `" <> tn <> "`") -- (a Vibe `with` statement's calls of its context manager's operations, Verada.Vibe.With: -- said once, at its `__enter__`, of an object that is none) (A.FormMethod m _, _) | m.text `elem` ["Verada_Enter", "Verada_Exit", "Verada_Rejoin", "Verada_Reflect"] -> do own <- hasOperation m.text if own then operation m.text 0 "" else Nothing <$ when (m.text == "Verada_Enter") (reportAt TypeMismatch x.span ("`" <> tn <> "` is not a context manager: a `with` statement's object is of a class with `__enter__(self)` and `__exit__(self, exc_type, exc, tb)`") ("of type `" <> tn <> "`")) -- (Varc's `x << n` and `x >> n`, D189: an unsigned type's own `Shift_Left` and -- `Shift_Right` (Interfaces'), else an Integer's by Verada.Vibe.Integers, Python's and -- Rust's arithmetic shifts, whose preconditions say what fits) (A.FormMethod m _, _) | m.text `elem` ["Shift_Left", "Shift_Right"] -> hasOperation m.text >>= \case True -> operation m.text 0 "" False | probe.typeOf `elem` [st.integer, st.universalInteger] || (case kind of { KInteger _ -> tn `elem` ["Integer", "Natural", "Positive"]; _ -> False }) -> pure (Just (AsCall ("Verada.Vibe.Integers." <> m.text) 0)) | otherwise -> Nothing <$ reportAt TypeMismatch x.span ("`" <> (if m.text == "Shift_Left" then "<<" else ">>") <> "` shifts an `Integer` or a value of an unsigned type with its own `" <> m.text <> "` (Interfaces' `Unsigned_8` to `Unsigned_64`), and `" <> tn <> "` is neither: convert it, or multiply or divide by `2 ** n`") ("of type `" <> tn <> "`") (A.FormMethod m _, _) -> do let alias = fromMaybe m.text (lookup (Text.toLower m.text) [("add", "Include"), ("discard", "Exclude"), ("reverse", "Reverse_Elements"), ("reversed", "Reversed")]) own <- hasOperation m.text aliased <- hasOperation alias -- (an object's own operation, a protected object's: called through it) selected <- fst <$> trial (denote A.Expr {span = x.span, node = A.ESelected A.Selected {prefix = x, selector = A.SelectIdentifier m}}) case selected of Just (DOverloaded (_ : _)) | not own, not aliased -> pure (Just (AsSelectedCall m.text)) -- (a list's `insert(i, x)` and `pop(i)` count positions from 0, its vector from 1) _ -> operation (if own then m.text else alias) (if Text.toLower m.text `elem` ["insert", "pop", "delete"] && "Vector" `Text.isSuffixOf` tn then 1 else 0) ("`" <> tn <> "` has no operation `" <> m.text <> "`") forM_ resolved \r -> modify' \state -> state {surfaceForms = ((s, A.surfaceFormName f.kind), r) : state.surfaceForms} pure resolved -- | A type's name as a translation writes it where Sema met it: an implicit instance's by its -- full name (only that is visible), another's by its own. spelledType :: TypeId -> Sema Text spelledType t = typeDef t >>= \def -> maybe (pure def.name) spelledEntity def.decl spelledEntity :: DeclId -> Sema Text spelledEntity d = do full <- fullName d e <- entity d pure if "Instance_" `Text.isPrefixOf` full then full else e.name -- | How Python's repr shows a value of this type, as a collection shows its elements: an -- int, a float, a bool and a str by Verada.Vibe's `Repr`; a list, a set, a dict and a tuple -- by their elements' own, in turn. Nothing for a type Vibe does not show so (a class's -- value, an `Enum` member, a `RangeInt`). reprShape :: Span -> TypeId -> Sema (Maybe Repr) reprShape s t = do st <- std tn <- typeName t kind <- fullKind t let named d = do full <- fullName d let parts = Text.splitOn "." full shortestDenoting s d [Text.intercalate "." (drop k parts) | k <- reverse [0 .. length parts - 1]] full resultOf d = entity d <&> \e -> case e.kind of ESubprogram i | Just r <- i.result -> Just r.base _ -> Nothing if t `elem` [st.integer, st.universalInteger, st.boolean, st.universalReal] || tn `elem` ["Long_Float", "Text"] then pure (Just (ReprBy "Verada.Vibe.Repr")) else case kind of _ | tn `elem` ["Vector", "Set"] -> iterationOf t >>= \case Just it -> fmap (if tn == "Vector" then ReprElements "[" "]" "[]" else ReprElements "{" "}" "set()") <$> reprShape s it.elementType Nothing -> pure Nothing | tn == "Dictionary" -> do it <- iterationOf t valueFn <- listToMaybe <$> primitivesNamed "Value" t valueType <- maybe (pure Nothing) resultOf valueFn case (it, valueFn, valueType) of (Just i, Just v, Just vt) -> do name <- named v key <- reprShape s i.elementType value <- reprShape s vt pure (ReprPairs name <$> key <*> value) _ -> pure Nothing KRecord r | tn == "Tuple" -> do items <- forM r.components \c -> fmap (c.name,) <$> reprShape s c.subtype.base pure (ReprItems <$> sequence items) _ -> pure Nothing -- | Python's methods of a `str`: the function of Verada.Strings.Text_Operations each is, and -- whether its result is a position (from 1 there, from 0 in Python). textMethods :: [(Text, (Text, Bool))] textMethods = [ ("find", ("Find", True)) , ("index", ("Index", True)) , ("count", ("Count", False)) , ("startswith", ("Starts_With", False)) , ("endswith", ("Ends_With", False)) , ("replace", ("Replace", False)) , ("upper", ("Upper", False)) , ("lower", ("Lower", False)) , ("isdigit", ("Is_Digit", False)) , ("isalpha", ("Is_Alpha", False)) , ("isspace", ("Is_Space", False)) , ("strip", ("Strip", False)) , ("lstrip", ("Strip_Left", False)) , ("rstrip", ("Strip_Right", False)) , ("split", ("Split", False)) , ("join", ("Join", False)) , ("swapcase", ("Swap_Case", False)) , ("capitalize", ("Capitalize", False)) , ("title", ("Title", False)) , ("ljust", ("Left_Justify", False)) , ("rjust", ("Right_Justify", False)) , ("center", ("Center", False)) , ("zfill", ("Zero_Fill", False)) ] -- | Python's operations of a list that compare its elements (`xs.sort()`, and the builtins -- `sorted`, `min` and `max` of one list, which Vibe writes as methods): the generic of the -- list's package each is. orderedMethods :: [(Text, Text)] orderedMethods = [("sort", "Generic_Sort"), ("sorted", "Generic_Sorted"), ("min", "Generic_Minimum"), ("max", "Generic_Maximum")] -- | The instance a call of a generic subprogram calls (Vibe's `first(xs)` of `def first[T]`): -- each formal type is the type of an argument whose parameter names it, and one instance is -- made per generic and actual types in the subprogram body making the call. callInstance :: Span -> DeclId -> A.Apply -> Sema (Maybe DeclId) callInstance s g ap = do source <- gets (Map.lookup g . (.generics)) hook <- asks (.instantiateHook) pending <- gets (.callInstances) case (source, hook, pending) of (Just src, Just instantiate, Just calls) -> do let typeFormals = [A.foldedName t.name | AD.FormalTypeNode t <- src.formals] profile = case src.unit.node of AD.DSubprogram d -> Just d.spec AD.DSubprogramBody b -> Just b.spec _ -> Nothing marks = concat [replicate (length p.names) (markName p.subtype) | Just spec <- [profile], p <- spec.profile.parameters] markName = \case AT.ParameterSubtype m | A.ENameRef i <- m.mark.node -> Just (A.foldedName i) _ -> Nothing -- (a formal package of a container of a formal type, Vibe's `list[T]`, D188: its actual -- the package of the argument's type, and the formal type its elements' type) let packageFormals = [(A.foldedName p.name, p.name.text, [A.foldedName i | AD.GivenActuals [A.Argument {value = A.ArgExpr A.Expr {node = A.ENameRef i}}] <- [p.actuals]]) | AD.FormalPackageNode p <- src.formals] packageMarks = concat [replicate (length p.names) (markPackage p.subtype) | Just spec <- [profile], p <- spec.profile.parameters] markPackage = \case AT.ParameterSubtype m | A.ESelected sel <- m.mark.node, A.ENameRef i <- sel.prefix.node -> Just (A.foldedName i) _ -> Nothing packages <- forM (zip packageMarks ap.arguments) \(m, a) -> case (m, a.value) of (Just f, A.ArgExpr x) | Just (_, _, elementFormals) <- find (\(n, _, _) -> n == f) packageFormals -> do (probe, _) <- trial (expression AnyType x) def <- typeDef probe.typeOf package <- case def.decl of Just d -> entity d >>= \e -> maybe (pure Nothing) (fmap Just . fullName) e.parent Nothing -> pure Nothing element <- iterationOf probe.typeOf pure ([(f, p) | Just p <- [package]], [(t, it.elementType) | Just it <- [element], t <- take 1 elementFormals]) _ -> pure ([], []) types <- forM (zip marks ap.arguments) \(m, a) -> case (m, a.value) of (Just f, A.ArgExpr x) | f `elem` typeFormals -> do (probe, _) <- trial (expression AnyType x) pure [(f, probe.typeOf)] _ -> pure [] let bound = concat types <> concatMap snd packages packageActuals = [(written, lookup f (concatMap fst packages)) | (f, written, _) <- packageFormals] actuals <- forM typeFormals \f -> case lookup f bound of Just t -> Just <$> actualTypeName t Nothing -> pure Nothing gname <- fullName g let isFunction = maybe False (\spec -> spec.kind == AD.FunctionKind) profile record d = do e <- entity d modify' \st -> st {instanceCalls = (s, (isFunction, e.name, gname, fromMaybe [] (sequence actuals))) : st.instanceCalls} pure (Just d) case (sequence actuals, mapM snd packageActuals) of (Nothing, _) -> Nothing <$ reportAt WrongKindOfEntity ap.prefix.span ("the types of `" <> gname <> "` cannot all be told from these arguments: each must be the type of an argument") "a generic" (_, Nothing) -> Nothing <$ reportAt WrongKindOfEntity ap.prefix.span ("the containers of `" <> gname <> "` cannot all be told from these arguments: each must be the type of an argument") "a generic" (Just names0, Just packageNames) -> let names = names0 <> packageNames in case Map.lookup (g, names) calls.made of Just d -> record d Nothing -> do let instanceName = A.Identifier {span = s, text = "Instance_" <> Text.intercalate "_" (map (Text.replace "." "_") (gname : names))} kind = case profile of Just spec | spec.kind == AD.FunctionKind -> AD.InstantiateFunction _ -> AD.InstantiateProcedure instantiation = AD.Instantiation {kind, overriding = Nothing, name = A.Expr {span = s, node = A.ENameRef instanceName}, generic = ap.prefix, actuals = [A.Argument {span = s, formal = Nothing, value = A.ArgExpr (dottedName s n), reference = Nothing} | n <- names0] <> [A.Argument {span = s, formal = Just A.Identifier {span = s, text = written}, value = A.ArgExpr (dottedName s n), reference = Nothing} | ((written, _), n) <- zip packageActuals packageNames], aspects = []} made <- local (\c -> c {implicitCall = True}) (instantiate instanceName instantiation) forM_ made \(d, decls) -> modify' \st -> st {callInstances = (\c -> c {declarations = c.declarations <> decls, made = Map.insert (g, names) d c.made}) <$> st.callInstances} maybe (pure Nothing) (record . fst) made (Just _, _, Nothing) -> Nothing <$ notYetSupported s "a call of a generic subprogram outside a subprogram body" T29 _ -> pure Nothing where -- (a universal value's type is Integer's or Long_Float's) actualTypeName t = do st <- std if t == st.universalInteger then pure "Integer" else if t == st.universalReal then pure "Long_Float" else do def <- typeDef t maybe (pure def.name) fullName def.decl dottedName sp n = case reverse (Text.splitOn "." n) of final : outer@(_ : _) -> A.Expr {span = sp, node = A.ESelected A.Selected {prefix = dottedName sp (Text.intercalate "." (reverse outer)), selector = A.SelectIdentifier A.Identifier {span = sp, text = final}}} _ -> A.Expr {span = sp, node = A.ENameRef A.Identifier {span = sp, text = n}} -- | The first of these names that denotes the declaration here, or the last resort. shortestDenoting :: Span -> DeclId -> [Text] -> Text -> Sema Text shortestDenoting sp d candidates fallback = case candidates of [] -> pure fallback c : rest -> do found <- fst <$> trial (denote (dotted c)) case found of Just (DOverloaded ds) | d `elem` ds -> pure c _ -> shortestDenoting sp d rest fallback where dotted t = case reverse (Text.splitOn "." t) of final : outer@(_ : _) -> A.Expr {span = sp, node = A.ESelected A.Selected {prefix = dotted (Text.intercalate "." (reverse outer)), selector = A.SelectIdentifier A.Identifier {span = sp, text = final}}} _ -> A.Expr {span = sp, node = A.ENameRef A.Identifier {span = sp, text = t}} -- | Ada 2005's prefixed view (RM 4.1.3(9.2)): @X.F (Args)@ calls a primitive subprogram F of -- X's tagged type (or one it inherits) with X as the first actual; Varc's methods are called -- so (@s.area()@). The candidate subprograms when the selector names no component of X. prefixedView :: A.Selected -> Sema (Maybe [DeclId]) prefixedView sel = case sel.selector of A.SelectIdentifier i -> denote sel.prefix >>= \case Just (DObjectLike d) -> entity d >>= \x -> case x.kind of EObject o -> candidates i o.subtype.base _ -> pure Nothing _ -> pure Nothing _ -> pure Nothing where candidates i t0 = do t <- fullKind t0 >>= \case KClassWide root -> pure root _ -> pure t0 fullKind t >>= \case KRecord r | isJust r.tag , not (any (\c -> folded c.name == A.foldedName i) r.components) -> do chain <- ancestors t direct <- lookupDirect i.text overloadable <- filterM (fmap (isOverloadable . (.kind)) . entity) direct inherited <- concat <$> mapM (primitivesNamed i.text) chain pure case nub (inherited <> overloadable) of [] -> Nothing ds -> Just ds _ -> pure Nothing ancestors t = do def <- typeDef t (t :) <$> maybe (pure []) ancestors def.parent -- | The first actual of a prefixed view: its prefix. prefixArgument :: A.Selected -> A.Argument prefixArgument sel = A.Argument {span = sel.prefix.span, formal = Nothing, value = A.ArgExpr sel.prefix, reference = Nothing} selectedComponent :: Expect -> A.Expr -> Sema TExpr selectedComponent expect e0 = do python <- optionalsHere -- (in Vibe, a field of an optional value, `p.x` of a `Point | None`: its value's) e <- case e0.node of A.ESelected sel0 | python , A.SelectIdentifier i <- sel0.selector , folded i.text `notElem` ["present", "item"] -> narrowed sel0.prefix <&> \p -> A.Expr {span = e0.span, node = A.ESelected A.Selected {prefix = p, selector = sel0.selector}} _ -> pure e0 selectedComponentOf expect e selectedComponentOf :: Expect -> A.Expr -> Sema TExpr selectedComponentOf expect e = case e.node of -- `P.'a'`: a character literal of an enumeration type declared in P (RM 4.1.3(4)) A.ESelected A.Selected {prefix, selector = A.SelectCharacter c} -> denote prefix >>= \case Just (DPackage p) -> do ds <- lookupInPackage p (Text.pack ['\'', c, '\'']) literals <- fmap catMaybes . forM ds $ \d -> entity d <&> \x -> case x.kind of EEnumLiteral l -> Just (l.typeId, l.position) _ -> Nothing let chosen = case expect of Expect t -> find ((== t) . fst) literals AnyType -> case literals of [l] -> Just l _ -> Nothing -- (Standard's character types have their characters as literals, not entities, -- RM A.1(35): `Standard.'A'` is one of them) st <- std standardCharacter <- if p /= st.package then pure Nothing else case expect of AnyType -> pure (Just (st.character, fromEnum c)) Expect t -> do def <- typeDef t pure case def.kind of KEnumeration en | en.isCharacter , isNothing def.parent , def.name `elem` ["Character", "Wide_Character", "Wide_Wide_Character"] , toInteger (fromEnum c) < en.characters -> Just (t, fromEnum c) _ -> Nothing case maybe standardCharacter Just chosen of Just (t, pos) -> mkExpr e.span t (TLiteral (StaticEnum pos)) Nothing -> do pkg <- fullName p reportAt UndefinedName e.span ("`" <> pkg <> "` declares no character literal `'" <> Text.singleton c <> "'` of the type expected here") "not declared in this package" errorExpr e.span _ -> expression expect A.Expr {span = e.span, node = A.ECharacter c} A.ESelected sel | A.SelectIdentifier _ <- sel.selector -> prefixedView sel >>= \case Just ds -> resolveCall CallFunction expect e.span ds [prefixArgument sel] Nothing -> component sel _ -> do notYetSupported e.span "selected names of this kind" T35 errorExpr e.span where component sel = case sel.selector of A.SelectIdentifier i -> do prefix <- expression AnyType sel.prefix >>= implicitDereference partials <- gets (.partialDiscriminants) let lookupIndex n ds = listToMaybe [(ix, dsub) | (ix, (dn, dsub)) <- zip [0 ..] ds, folded dn == n] -- (in an instance, a formal type's discriminant names the actual's at its position) renamedDiscriminant r = do names <- asks (Map.lookup prefix.typeOf . (.formalDiscriminants)) pure case names >>= elemIndex (A.foldedName i) of Just k | j : _ <- drop k (visibleDiscriminantFields r), c : _ <- drop j r.components -> Just (j, c) _ -> Nothing -- (in an instance, a formal derived type names the components of its ancestor, whose -- discriminants its actual may have renamed or hidden, D254: an ancestor's component -- by its position, which every type derived from it keeps, RM 12.5.1(21/3), D257) let ancestorComponent r = asks (elem prefix.typeOf . (.formalAncestorViews)) >>= \case False -> pure Nothing True -> do let up t = typeDef t >>= \def -> case def.parent of Nothing -> pure Nothing Just p -> fullKind p >>= \case KRecord pr | Just (k, _) <- find (\(_, c) -> folded c.name == A.foldedName i) (zip [0 :: Int ..] pr.components), c : _ <- drop k r.components -> pure (Just (k, c)) _ -> up p up prefix.typeOf kind <- fullKind prefix.typeOf >>= \case -- the components of a class-wide value are its root type's KClassWide root -> fullKind root k -> pure k case kind of KError -> errorExpr e.span KRecord r -> renamedDiscriminant r >>= \renamed -> ancestorComponent r >>= \inherited -> case renamed <|> find (\(_, c) -> folded c.name == A.foldedName i) (namedComponents r) <|> inherited of Just (ix, c) -> mkExpr e.span c.subtype.base (TComponentNode TComponent {prefix, component = ix}) >>= conform expect Nothing -> do tn <- typeName prefix.typeOf let suggestion = closest i.text (map ((.name) . snd) (namedComponents r)) report (diagnostic UnknownComponent Semantic ("`" <> tn <> "` has no component `" <> i.text <> "`")) { primary = Just (label i.span (maybe "no such component" (\c -> "did you mean `" <> c <> "`?") suggestion)) , fixes = [Fix {span = i.span, replacement = Verbatim c, description = "write `" <> c <> "`"} | Just c <- [suggestion]] , notes = [Note {text = "its components are " <> Text.intercalate ", " ["`" <> c.name <> "`" | c <- r.components], span = Nothing}] } errorExpr e.span -- a discriminant of a partial view declared with known discriminants (RM 7.3(13)): -- the full view's component of that position, the discriminants coming first KPrivate p | Just (ix, dsub) <- lookupIndex (A.foldedName i) =<< Map.lookup prefix.typeOf partials -> do -- (where the full view's discriminants are, D248) place <- case p.fullView of Just full -> typeDef full <&> \fd -> case fd.kind of KRecord r -> fromMaybe ix (listToMaybe (drop ix (visibleDiscriminantFields r))) _ -> ix Nothing -> pure ix mkExpr e.span dsub.base (TComponentNode TComponent {prefix, component = place}) >>= conform expect _ -> do tn <- typeName prefix.typeOf reportAt WrongKindOfEntity i.span ("a value of type `" <> tn <> "` has no components") "not a record" errorExpr e.span _ -> do notYetSupported e.span "selected names of this kind" T35 errorExpr e.span -- * Access values (L4a) -- | @P.all@: the object an access value designates. dereference :: Span -> TExpr -> Sema TExpr dereference s prefix = do kind <- fullKind prefix.typeOf case kind of KAccess a -> mkExpr s a.designated.base (TDereference prefix) -- `P.all` of an access-to-subprogram value: the value itself, which a call applies KSubprogramAccess _ -> pure prefix KError -> errorExpr s _ -> do tn <- typeName prefix.typeOf reportAt TypeMismatch prefix.span ("only access values designate objects, and this is a `" <> tn <> "`") "not an access value" errorExpr s -- | The value itself, or the object it designates when it is an access value (the implicit -- dereference of a component, index or slice, RM 4.1(9)). implicitDereference :: TExpr -> Sema TExpr implicitDereference e = fullKind e.typeOf >>= \case KAccess a -> mkExpr e.span a.designated.base (TDereference e) _ -> pure e -- | @new T@ or @new T'(V)@, of the access type the context expects. allocator :: Expect -> Span -> A.Allocator -> Sema TExpr allocator expect s a = do target <- case expect of Expect t -> fullKind t >>= \case KAccess acc -> pure (Just (t, acc)) KError -> pure Nothing _ -> do tn <- typeName t reportAt TypeMismatch s ("an allocator gives an access value, but `" <> tn <> "` is expected here") "not an access type" pure Nothing AnyType -> do reportAt TypeMismatch s "the access type of this allocator is not known here" "an access type is required" pure Nothing -- (an object `new` makes for a general access type can never be freed, so only a library-level -- one, made once, SPARK RM 3.10, G6) forM_ target \(_, acc) -> when acc.general do level <- dynamicLevel when (level > 0) $ reportAt GeneralAccessOwnership s "an object made by `new` for a general access type cannot be freed, so it is made only at library level" "would leak" case target of Nothing -> errorExpr s Just (t, acc) -> do (designated, initial) <- case a of A.AllocateSubtype ind -> do sub <- subtypeIndication ind initialised <- defaultInitialised sub.base unless (initialised || acc.toConstant) do tn <- typeName sub.base reportAt UninitialisedAllocator s ("an object of `" <> tn <> "` made by `new` would have no value") "give it one: `new T'(...)`" when acc.toConstant do reportAt UninitialisedAllocator s "an object designated by an access-to-constant value needs its value in the allocator" "give it one: `new T'(...)`" pure (sub, Nothing) A.AllocateQualified q -> do v <- expression (Expect acc.designated.base) q let sub = case v.node of TConversionNode c -> c.target _ -> unconstrained v.typeOf pure (sub, Just v) ok <- compatible acc.designated.base designated.base if ok then mkExpr s t (TAllocatorNode TAllocator {designated, initial}) else do tn <- typeName acc.designated.base reportAt TypeMismatch s ("this access type designates `" <> tn <> "` objects") "another type" errorExpr s -- | Whether every part of an object of the type has a default value (SPARK's "full default -- initialization"): access values, records whose components all have defaults or such types, -- arrays of such components, private types whose full view is one of these. defaultInitialised :: TypeId -> Sema Bool defaultInitialised t = do def <- typeDef t case def.kind of KAccess _ -> pure True KSubprogramAccess _ -> pure True KPrivate p -> maybe (pure True) defaultInitialised p.fullView KRecord r -> and <$> forM r.components \c -> if isJust c.initial then pure True else defaultInitialised c.subtype.base KArray a -> do own <- declaredDefault (.defaultComponentValues) t if isJust own then pure True else defaultInitialised a.component.base KError -> pure True -- (a scalar type with `Default_Value`, or derived from one) _ -> isJust <$> declaredDefault (.defaultValues) t -- | The `Default_Value` (of a scalar type) or `Default_Component_Value` (of an array type) -- given to a type or to an ancestor of it (derived types inherit them, RM 13.1(15)). declaredDefault :: (SemaState -> [(TypeId, TExpr)]) -> TypeId -> Sema (Maybe TExpr) declaredDefault field t = do known <- gets field case lookup t known of Just x -> pure (Just x) Nothing -> do def <- typeDef t case def.kind of KPrivate p | Just full <- p.fullView -> declaredDefault field full _ -> case def.parent of Just p | p /= t -> declaredDefault field p _ -> pure Nothing -- * Literals characterLiteral :: Expect -> Span -> Char -> Sema TExpr characterLiteral expect s c = do st <- std userLiterals <- lookupDirect (Text.pack ['\'', c, '\'']) candidates <- forM userLiterals \d -> entity d >>= \e -> pure case e.kind of EEnumLiteral l -> Just (l.typeId, l.position) _ -> Nothing let options = catMaybes candidates <> [(st.character, fromEnum c)] chosen <- case expect of Expect t -> case find ((== t) . fst) options of Just o -> pure (Just o) -- (a character type's literal is its character, when it is one of the type's: a wide -- one's beyond Latin-1, RM 3.5.2) Nothing -> fullKind t <&> \case KEnumeration e | e.isCharacter, toInteger (fromEnum c) < e.characters -> Just (t, fromEnum c) -- (or the expected type's own literal, visible or not: the type decides a -- character literal, RM 4.2(3), `M : P.Mixed := 'B'` without `use P`) KEnumeration e | Just k <- elemIndex (Text.pack ['\'', c, '\'']) e.literals -> Just (t, k) _ -> Nothing AnyType -> pure (Just (st.character, fromEnum c)) case chosen of Just (t, pos) | t == st.character, pos > 255 -> do reportAt NonLatin1Literal s ("`" <> Text.singleton c <> "` is not a `Character`") "outside Latin-1: a `Wide_Wide_Character` holds it" mkExpr s t (TLiteral (StaticEnum 0)) | otherwise -> mkExpr s t (TLiteral (StaticEnum pos)) Nothing | fromEnum c > 255 -> do reportAt NonLatin1Literal s ("`" <> Text.singleton c <> "` is not a character of the type expected here") "outside Latin-1: a `Wide_Wide_Character` holds it" mkExpr s st.character (TLiteral (StaticEnum 0)) >>= conform expect | otherwise -> mkExpr s st.character (TLiteral (StaticEnum (fromEnum c))) >>= conform expect stringLiteral :: Expect -> Span -> Text -> Sema TExpr stringLiteral expect s text = do st <- std target <- case expect of Expect t -> do kind <- fullKind t pure case kind of KArray a | length a.indices == 1 -> t _ -> st.string AnyType -> pure st.string -- (each character must be one of the component type's: `String`'s are Latin-1's, RM 3.5.2) kind <- fullKind target limit <- case kind of KArray a -> fullKind a.component.base <&> \case KEnumeration e | e.isCharacter -> Just e.characters _ -> Nothing _ -> pure Nothing forM_ limit \n -> case [c | c <- Text.unpack text, toInteger (ord c) >= n] of c : _ -> do tn <- typeName target reportAt NonLatin1Literal s ("`" <> Text.singleton c <> "` is not a character of `" <> tn <> "`") (if n == 256 then "outside Latin-1: a `Wide_Wide_String` holds it" else "outside the component type") [] -> pure () mkExpr s target (TLiteral (StaticString text)) >>= conform expect -- * Overload resolution, bottom up (RM 8.6) -- | The possible types of an expression on its own, without reporting anything. shapes :: A.Expr -> Sema [Shape] shapes e = do known <- gets (Map.lookup e.span . (.shapeMemo)) case known of Just ss -> pure ss Nothing -> do ss <- fst <$> trial (shapesOf e) modify' \st -> st {shapeMemo = Map.insert e.span ss st.shapeMemo} pure ss shapesOf :: A.Expr -> Sema [Shape] shapesOf e = do st <- std case e.node of A.EInteger _ -> pure [Exactly st.universalInteger] A.EReal _ -> pure [Exactly st.universalReal] A.ECharacter c -> pure [CharacterLike c] A.EString _ -> pure [StringLike] -- (a Varc string literal: a string, or a text where texts are visible) A.ESurfaceForm A.SurfaceForm {kind = A.FormLiteralText} -> do textType <- fst <$> trial (denote (dottedExpr e.span ["Verada", "Strings", "Texts", "Text"])) pure (StringLike : [Exactly tt.base | Just (DSubtype tt) <- [textType]]) A.EAggregate _ -> pure [CompositeLike] A.ENull -> pure [AccessLike] A.EAllocator _ -> pure [AccessLike] A.EParen inner -> shapesOf inner -- (a conditional expression's: the types every branch may have, RM 4.5.7(10): `if C -- then Jan else Oct` of two types with an `Oct` is a Month) A.EIf i -> do branches <- mapM shapesOf (i.thenValue : map (.value) i.elsifs <> maybe [] pure i.elseValue) -- (a branch of a universal value, a literal's, fits the others' types as a literal does) specific <- forM branches \b -> filterM (fmap not . isUniversal) [t | Exactly t <- b] pure case filter (not . null) specific of [] -> nub (concat branches) k : ks -> [Exactly t | t <- nub k, all (elem t) ks] A.ENameRef _ -> named [] A.ESelected _ -> named [] A.EApply ap | Just call <- operatorCall ap -> shapesOf A.Expr {span = e.span, node = call} A.EApply ap -> denote ap.prefix >>= \case Just (DOverloaded ds) -> callShapes ds ap.arguments Just DNone -> pure [] _ -> typed A.EUnary u -> do operand <- shapesOf u.operand predefined <- filterM (\t -> unaryApplies u.op <$> fullKind t) (nub [t | Exactly t <- operand]) users <- operatorShapes (A.unaryOpText u.op) [operand] pure (nub (map Exactly predefined <> users)) A.EBinary b | b.op `elem` [A.OpAndThen, A.OpOrElse, A.OpEq, A.OpNe, A.OpLt, A.OpLe, A.OpGt, A.OpGe] -> do users <- if b.op `elem` [A.OpAndThen, A.OpOrElse] then pure [] else binaryUsers b pure (nub (Exactly st.boolean : users)) | otherwise -> do ls <- shapesOf b.left rs <- shapesOf b.right predefined <- predefinedTypes b.op ls rs users <- operatorShapes (A.binaryOpText b.op) [ls, rs] -- (literals joined, with no operand naming a type: any string type, as a literal -- is, which the context chooses; with texts visible a literal may also be a text) let joinedLiterals = b.op == A.OpConcat && null predefined && (StringLike `elem` ls || StringLike `elem` rs) pure (nub (map Exactly predefined <> users <> [StringLike | joinedLiterals])) A.EMembership _ -> pure [Exactly st.boolean] A.EQuantified _ -> pure [Exactly st.boolean] _ -> typed where named args = denote e >>= \case Just (DOverloaded ds) -> callShapes ds args Just DNone -> pure [] _ -> typed typed = do x <- expression AnyType e bad <- isError x.typeOf pure [Exactly x.typeOf | not bad] binaryUsers b = do ls <- shapesOf b.left rs <- shapesOf b.right operatorShapes (A.binaryOpText b.op) [ls, rs] -- | The result types of the functions (and literals) among these that accept the arguments. callShapes :: [DeclId] -> [A.Argument] -> Sema [Shape] callShapes ds args = fmap (nub . concat) . forM ds $ \d -> entity d >>= \e -> case e.kind of EEnumLiteral l | null args -> pure [Exactly l.typeId] ESubprogram info | info.kind == Function, Just r <- info.result -> do reason <- argumentMismatch info args pure [Exactly r.base | isNothing reason] _ -> pure [] -- | The result types of user-declared operators that accept operands of these shapes. operatorShapes :: Text -> [[Shape]] -> Sema [Shape] operatorShapes opText operands = do candidates <- operatorCandidates opText (length operands) fmap concat . forM candidates $ \(_, info) -> do types <- formalTypes info ok <- and <$> zipWithM admitsAny types operands pure [Exactly r.base | ok, Just r <- [info.result]] -- | Visible user-declared operator functions with this many operands. operatorCandidates :: Text -> Int -> Sema [(DeclId, SubprogramInfo)] operatorCandidates opText arity = do ds <- lookupDirect ("\"" <> opText <> "\"") fmap catMaybes . forM ds $ \d -> entity d >>= \e -> pure case e.kind of ESubprogram info | info.kind == Function && length info.parameters == arity -> Just (d, info) _ -> Nothing formalTypes :: SubprogramInfo -> Sema [TypeId] formalTypes info = do st <- std formals <- mapM entity info.parameters pure [case f.kind of EObject o -> o.subtype.base; _ -> st.errorType | f <- formals] -- | The types for which a predefined adding, multiplying or exponentiating operator could -- take operands of these shapes: a type one operand has, or universal when both are. predefinedTypes :: A.BinaryOp -> [Shape] -> [Shape] -> Sema [TypeId] predefinedTypes op ls rs = do st <- std let named' = nub [t | Exactly t <- ls <> rs] specific <- filterM (fmap not . isUniversal) named' let candidates = if null specific then named' else specific flip filterM candidates \t -> do kind <- fullKind t -- (an operand of `&` is an array of the type or one of its components, RM 4.5.3(3)) let operandOk ss = case kind of KArray a | op == A.OpConcat, length a.indices == 1 -> (||) <$> admitsAny t ss <*> admitsAny a.component.base ss _ -> admitsAny t ss leftOk <- operandOk ls rightOk <- if op == A.OpPow then admitsAny st.integer rs else operandOk rs pure (leftOk && rightOk && (if op == A.OpPow then powApplies kind else operatorApplies op kind)) where powApplies = \case KInteger _ -> True KModular _ -> True KReal _ -> True KError -> True _ -> False unaryApplies :: A.UnaryOp -> TypeKind -> Bool unaryApplies op kind = case (op, kind) of (_, KError) -> True (A.OpNot, KEnumeration e) -> e.isBoolean (A.OpNot, KModular _) -> True (A.OpNot, _) -> False (_, KInteger _) -> True (A.OpAbs, KModular _) -> False (_, KModular _) -> True (_, KReal _) -> True (_, KFixed _) -> True _ -> False -- | Why the arguments do not fit a candidate's formal types ('Nothing' when they do). argumentMismatch :: SubprogramInfo -> [A.Argument] -> Sema (Maybe Text) argumentMismatch info args = associate info args >>= \case Left why -> pure (Just why) Right assoc -> do formals <- mapM entity info.parameters types <- formalTypes info reasons <- forM (zip3 formals types assoc) \(formal, t, (_, given)) -> case given of Just a | A.ArgExpr x <- a.value -> do ss <- shapes x ok <- admitsAny t ss if ok then pure Nothing else do tn <- typeName t described <- describeShapes ss pure (Just ("`" <> formal.name <> "` is of type `" <> tn <> "`, but the argument is " <> described)) _ -> pure Nothing pure (headMaybe (catMaybes reasons)) -- * Calls, indexing and conversions data CallKind = CallFunction | CallProcedure deriving stock (Eq) apply :: Expect -> Span -> A.Apply -> Sema TExpr apply expect s ap = do view <- case ap.prefix.node of A.ESelected sel -> fmap (sel,) <$> prefixedView sel _ -> pure Nothing case view of Just (sel, ds) -> called >> resolveCall CallFunction expect s ds (prefixArgument sel : ap.arguments) Nothing -> plain where plain = denote ap.prefix >>= \case Just (DSubtype target) -> called >> conversion expect s target ap.arguments Just (DOverloaded ds) -> called >> resolveCall CallFunction expect s ds ap.arguments Just (DGeneric g) -> called >> callInstance s g ap >>= \case Just d -> resolveCall CallFunction expect s [d] ap.arguments Nothing -> errorExpr s Just DNone -> errorExpr s Just (DObjectLike _) -> indexed -- `P."+" (A, B)` of a predefined operator (not declared in P as a subprogram): the -- operator, as `"+" (A, B)` is Nothing | A.ESelected A.Selected {prefix = owner, selector = A.SelectOperator op} <- ap.prefix.node , Just call <- operatorCall A.Apply {prefix = A.Expr {span = ap.prefix.span, node = A.EString op}, arguments = ap.arguments, bracketed = ap.bracketed} -> do packages <- operatorPackage owner local (\c -> c {operatorsOf = packages <> c.operatorsOf, predefinedAt = Just s}) (expression expect A.Expr {span = s, node = call}) Nothing -> indexed Just _ -> do reportAt NotCallable ap.prefix.span "this name cannot be called or indexed" "not a function, array or type" errorExpr s indexed = do prefix <- expression AnyType ap.prefix >>= implicitDereference -- (a call through an access-to-subprogram value is a call) kind <- fullKind prefix.typeOf element <- varcElement prefix.typeOf ap case element of -- (Varc's `xs[i]` of a list, `m[k]` of a map, `s[i]` of a text: Vibe's `x[i]`, -- recorded at the indexing, D189) Just form -> formResolution False s form >>= \case Just r -> expression expect (resolvedFormExpr s r form) Nothing -> errorExpr s Nothing -> do bracketMark case kind of KSubprogramAccess _ -> False _ -> True indexWith expect s ap.prefix.span prefix ap.arguments called = bracketMark False -- Varc writes indexing with brackets and calls with parentheses (LX3): the other is -- reported (B0705, B0706); indexings are recorded (by their prefix, which a call that -- Vibe's forms expand to at the same place does not share), so that a translation to -- Varc brackets them bracketMark indexing = do when indexing (modify' \st -> st {indexings = Set.insert ap.prefix.span st.indexings}) let opening = Span {file = s.file, start = ap.prefix.span.end, end = ap.prefix.span.end + 1} closingSpan = Span {file = s.file, start = s.end - 1, end = s.end} rewrite open close = [Fix {span = opening, replacement = Verbatim open, description = "write `" <> open <> close <> "`"}, Fix {span = closingSpan, replacement = Verbatim close, description = "write `" <> open <> close <> "`"}] case (ap.bracketed, indexing) of (Just True, False) -> report (diagnostic BracketsForCall Semantic "a call or conversion is written with parentheses") { primary = Just (label opening "brackets index an array") , fixes = rewrite "(" ")" } (Just False, True) -> report (diagnostic ParenthesesForIndex Semantic "indexing is written with brackets") { primary = Just (label opening "parentheses call a subprogram or convert") , fixes = rewrite "[" "]" } _ -> pure () -- | In Varc, a list, a map or a text indexed with brackets by one value (`xs[i]`, `m[k]`): -- Vibe's form of the element there (by position from 0, or by key), D189. varcElement :: TypeId -> A.Apply -> Sema (Maybe A.SurfaceForm) varcElement t ap = do varc <- asks (.varc) tn <- typeName t -- (an array is indexed as an array, whatever its type's name) array <- fullKind t <&> \case KArray _ -> True _ -> False pure case ap.arguments of [A.Argument {formal = Nothing, value = A.ArgExpr i}] | varc , not array , ap.bracketed == Just True , tn == "Text" || any (`Text.isSuffixOf` tn) ["Vector", "Dictionary"] -> Just A.SurfaceForm {kind = A.FormItem, operands = [ap.prefix, i]} _ -> Nothing -- | A value of an array type indexed or sliced (`A (I)`, `A (L .. H)`, `F'Result (I)`, -- `F (I)` for a parameterless function F). indexWith :: Expect -> Span -> Span -> TExpr -> [A.Argument] -> Sema TExpr indexWith expect s prefixSpan prefix args = do kind <- fullKind prefix.typeOf case kind of KError -> errorExpr s -- `P (X)` for an access-to-subprogram value P: an indirect call, its arguments matched -- to the type's profile KSubprogramAccess sa -> do call <- resolveCall CallFunction expect s [sa.profile] args case call.node of TCallNode c -> pure call {node = TIndirectCallNode TIndirectCall {target = prefix, arguments = c.arguments}} _ -> pure call KArray a | [arg] <- args, [ix] <- a.indices -> do isSlice <- sliceLike arg if isSlice then do bounds <- indexRange ix arg mkExpr s prefix.typeOf (TSliceNode TSlice {prefix, bounds}) >>= conform expect else do index <- argumentValue (Expect ix.base) arg mkExpr s a.component.base (TIndexedNode TIndexed {prefix, indices = [index]}) >>= conform expect -- RM 4.1.2: a slice is of a one-dimensional array | any isRange args -> reportAt WrongArguments s "only a one-dimensional array can be sliced" "a range in an index of a multidimensional array" >> errorExpr s | length args /= length a.indices -> do reportAt WrongArguments s ("this array has " <> tshow (length a.indices) <> " index" <> plural (length a.indices) <> ", but " <> tshow (length args) <> " given") "wrong number of indices" errorExpr s | otherwise -> do indices <- zipWithM (\ix arg -> argumentValue (Expect ix.base) arg) a.indices args mkExpr s a.component.base (TIndexedNode TIndexed {prefix, indices}) >>= conform expect _ -> do tn <- typeName prefix.typeOf reportAt NotCallable prefixSpan ("a value of type `" <> tn <> "` cannot be called or indexed") "not a function or array" errorExpr s where isRange a = case a.value of A.ArgRange _ -> True _ -> False -- a range, a discrete subtype or `X'Range` (not an index value) sliceLike a = case a.value of A.ArgRange _ -> pure True A.ArgExpr e -> case e.node of A.EAttribute at | A.foldedName at.designator == "range" -> pure True _ -> denote e >>= \case Just (DSubtype _) -> pure True _ -> pure False A.ArgBox -> pure False plural n = if n == 1 then "" else "es" argumentValue :: Expect -> A.Argument -> Sema TExpr argumentValue expect a = case a.value of A.ArgExpr x -> expression expect x A.ArgRange r -> do reportAt WrongArguments r.span "a range is not a value: only an array can be sliced with one" "a range here" errorExpr r.span A.ArgBox -> do reportAt WrongArguments a.span "`<>` is not a value here (it stands for an actual only in a formal package)" "`<>` here" errorExpr a.span -- | @T (X)@: a value conversion between related types (RM 4.6). conversion :: Expect -> Span -> Subtype -> [A.Argument] -> Sema TExpr conversion expect s target args = case args of [a] | isNothing a.formal -> do targetKind <- fullKind target.base -- a product or quotient of two fixed-point values is universal_fixed, here in the target universalFixed <- case (targetKind, a.value) of (KFixed _, A.ArgExpr e) -> fixedOperands e _ -> pure False operand <- argumentValue (if universalFixed then Expect target.base else AnyType) a operandKind <- fullKind operand.typeOf ancestor <- descendsFrom operand.typeOf target.base -- between untagged types with a common ancestor, either way (RM 4.6(21)) untaggedRelative <- do down <- descendsFrom target.base operand.typeOf tagged <- isJust <$> tagInfoOf target.base pure (down && not tagged) -- from a class-wide value to a type of the class (a tag check), or to a class-wide type classWide <- case (operandKind, targetKind) of (KClassWide from, KClassWide to) -> or <$> sequence [compatible target.base operand.typeOf, descendsFrom target.base from, eitherInterface from to] (KClassWide root, _) -> descendsFrom target.base root (_, KClassWide _) -> compatible target.base operand.typeOf _ -> pure False let ancestorOrClass = ancestor || classWide || untaggedRelative ok <- (ancestorOrClass ||) <$> convertible targetKind operandKind target.base operand.typeOf if ok then mkExpr s target.base (TConversionNode TConversion {target, operand, qualified = False}) >>= staticInSubtype target >>= conform expect else do tn <- typeName target.base on <- typeName operand.typeOf let from = case on of "universal_integer" -> "an integer value" "universal_real" -> "a real value" _ -> "`" <> on <> "`" reportAt InvalidConversion s ("cannot convert " <> from <> " to `" <> tn <> "`") "unrelated types" errorExpr s _ -> do reportAt WrongArguments s "a type conversion takes exactly one value" "write `T (Value)`" errorExpr s where convertible tk ok tt ot | tt == ot = pure True | otherwise = pure case (tk, ok) of (KError, _) -> True (_, KError) -> True (KInteger _, KInteger _) -> True (KInteger _, KModular _) -> True (KModular _, KInteger _) -> True (KModular _, KModular _) -> True (KReal _, KInteger _) -> True (KInteger _, KReal _) -> True (KModular _, KReal _) -> True (KReal _, KModular _) -> True (KFixed _, KModular _) -> True (KModular _, KFixed _) -> True (KReal _, KReal _) -> True (KFixed _, KFixed _) -> True (KFixed _, KInteger _) -> True (KFixed _, KReal _) -> True (KInteger _, KFixed _) -> True (KReal _, KFixed _) -> True -- (a derived type's codes may differ: its literals are the parent's, C46051B) (KEnumeration a, KEnumeration b) -> a.literals == b.literals && a.isBoolean == b.isBoolean && a.isCharacter == b.isCharacter (KArray a, KArray b) -> length a.indices == length b.indices && a.component.base == b.component.base _ -> False -- | Match arguments to a subprogram's formals (positional first, then named; defaults for -- the rest). 'Left' says why they do not fit. associate :: SubprogramInfo -> [A.Argument] -> Sema (Either Text [(DeclId, Maybe A.Argument)]) associate info args = do formals <- mapM (\d -> (d,) <$> entity d) info.parameters let (positional, named) = span (isNothing . (.formal)) args byPosition = zip (map fst formals) (map Just positional) restFormals = drop (length positional) formals lookupNamed (d, e) = (d, find (\a -> fmap A.foldedName a.formal == Just (folded e.name)) named) assigned = byPosition <> map lookupNamed restFormals namedFormals = [f | a <- named, Just f <- [a.formal]] positionalNames = map (folded . (.name) . snd) (take (length positional) formals) byPositionToo = [f | f <- namedFormals, A.foldedName f `elem` positionalNames] unknown = [f | f <- namedFormals, A.foldedName f `notElem` map (folded . (.name) . snd) formals] twice = [f | (i, f) <- zip [0 :: Int ..] namedFormals, A.foldedName f `elem` map A.foldedName (take i namedFormals)] missing = [e.name | ((_, Nothing), (_, e), dflt) <- zip3 assigned formals info.defaults, isNothing dflt] pure if | length positional > length formals -> Left ("takes " <> tshow (length formals) <> " argument" <> (if length formals == 1 then "" else "s") <> ", " <> tshow (length args) <> " given") | f : _ <- unknown -> Left ("has no parameter named `" <> f.text <> "`") | f : _ <- byPositionToo -> Left ("gets `" <> f.text <> "` both by position and by name") | f : _ <- twice -> Left ("gets `" <> f.text <> "` twice") | (m : _) <- missing -> Left ("needs a value for `" <> m <> "`") | otherwise -> Right assigned -- | Resolve a call (or an enumeration literal) among visible candidates: by arity and named -- associations, then by argument and result types. One candidate left is checked for real; -- several or none are reported with each candidate. resolveCall :: CallKind -> Expect -> Span -> [DeclId] -> [A.Argument] -> Sema TExpr resolveCall kind expect s ds0 args = do -- (in an instance's text, the call the generic's own text makes, RM 12.3(14)) ds <- asInGeneric (s, callKey) ds0 entities <- mapM (\d -> (d,) <$> entity d) ds -- enumeration literals: no arguments, chosen by the expected type let literals = [(d, l) | (d, e) <- entities, EEnumLiteral l <- [e.kind]] subprograms = [(d, info) | (d, e) <- entities, ESubprogram info <- [e.kind], kindFits info] case (literals, null args) of (_ : _, True) | null subprograms -> chooseLiteral literals -- a literal and parameterless functions of the same name: the context decides -- (unless a parameterless function of that type is a homograph of the literal: declared -- or derived, it overrides the literal, RM 8.3(9-13), ACATS C83032A) (_ : _, True) | Expect t <- expect, any (\(_, l) -> l.typeId == t) literals, not (any (\(_, info) -> null info.parameters && fmap (.base) info.result == Just t) subprograms) -> chooseLiteral literals _ -> do structural <- forM subprograms \(d, info) -> (d,info,) <$> associate info args let (reasons, fits) = partitionEithers [either (\why -> Left (d, why)) (\m -> Right (d, info, m)) r | (d, info, r) <- structural] case fits of -- `F (I)` for a parameterless function F of an array type: a component of its result -- (its result implicitly dereferenced when it is an access value, RM 4.1(9)) [] | not (null args), [(d, _)] <- [x | x@(_, i) <- subprograms, null i.parameters, isJust i.result] -> do call <- resolveCall kind AnyType s [d] [] >>= implicitDereference indexWith expect s s call args -- (of several such functions, the one whose result's indexing fits: its index type, -- number of indices and component type decide, RM 8.6, ACATS C41101D) [] | not (null args), parameterless@(_ : _ : _) <- [d | (d, i) <- subprograms, null i.parameters, isJust i.result] -> do fitting <- filterM (\d -> null . snd <$> trial (resolveCall kind AnyType s [d] [] >>= implicitDereference >>= \call -> indexWith expect s s call args)) parameterless case fitting of [d] -> do call <- resolveCall kind AnyType s [d] [] >>= implicitDereference indexWith expect s s call args _ -> noCandidate reasons [] -> noCandidate reasons [(d, info, m)] -> finishCall d info m several -> do noteRivals [d | (d, _, _) <- several] False -- the first pass: keep the candidates whose formals admit the arguments' possible -- types and whose result fits the context judged <- forM several \c@(_, info, _) -> do argumentWhy <- argumentMismatch info args resultWhy <- resultMismatch info pure (c, argumentWhy <|> resultWhy) case [c | (c, Nothing) <- judged] of [] -> noCandidate (reasons <> [(d, why) | ((d, _, _), Just why) <- judged]) [(d, info, m)] -> finishCall d info m good -> tieBreak good where tieBreak good = do tried <- forM good \c@(d, info, m) -> (c,) . snd <$> trial (finishCall d info m) case [c | (c, diags) <- tried, null diags] of [(d, info, m)] -> finishCall d info m [] -> case good of (d, info, m) : _ -> finishCall d info m [] -> errorExpr s ambiguous -> innermostHomograph ambiguous >>= \case -- homographs (one profile): the innermost declaration hides the others, and a -- declaration a use-visible one (RM 8.3(8), 8.4(9)) Just (d, info, m) -> finishCall d info m Nothing -> do described <- forM ambiguous \(d, info, _) -> do e <- entity d result <- traverse (typeName . (.base)) info.result pure (e, result) let results = nub [r | (_, Just r) <- described] byResult = length results == length described calleeName = case described of (e, _) : _ -> e.name [] -> "F" qualified r = "`" <> r <> "'(" <> calleeName <> (if null args then "" else " (...)") <> ")`" report (diagnostic AmbiguousName Semantic "this call is ambiguous") { primary = Just (label s "matches more than one subprogram") , secondary = [Label {span = e.span, text = Just (maybe "candidate" (\r -> if byResult then "candidate returning `" <> r <> "`" else "candidate") result)} | (e, result) <- described] , advice = Just case results of r : _ | byResult -> "the candidates return different types: say which one is wanted, e.g. " <> qualified r _ -> "qualify an argument (`T'(X)`) or the name to say which one is meant" } errorExpr s innermostHomograph cs = do profiles <- forM cs \(_, info, _) -> do params <- forM info.parameters \q -> entity q <&> \qe -> case qe.kind of EObject o -> Just (o.mode, o.subtype.base) _ -> Nothing pure (params, fmap (.base) info.result) scs <- gets (.scopes) let depth d = listToMaybe [k | (k, sc) <- zip [0 :: Int ..] scs, any (elem d) (Map.elems sc.names)] ranked = [(depth d, c) | c@(d, _, _) <- cs] placed = [(k, c) | (Just k, c) <- ranked] nearest = foldr (min . fst) maxBound placed pure case (nub profiles, [c | (k, c) <- placed, k == nearest]) of ([_], [c]) -> Just c _ -> Nothing resultMismatch info = case (expect, info.result) of (Expect t, Just r) | kind == CallFunction -> do ok <- compatible t r.base if ok then pure Nothing else do rn <- typeName r.base tn <- typeName t pure (Just ("returns `" <> rn <> "`, but `" <> tn <> "` is expected here")) _ -> pure Nothing kindFits info = case (kind, info.kind) of (CallFunction, Function) -> True (CallProcedure, Procedure) -> True _ -> False chooseLiteral literals = do let matching = case expect of Expect t -> [x | x@(_, l) <- literals, l.typeId == t] AnyType -> literals case matching of [(_, l)] -> mkExpr s l.typeId (TLiteral (StaticEnum l.position)) [] -> case literals of (_, l) : _ -> mkExpr s l.typeId (TLiteral (StaticEnum l.position)) >>= conform expect [] -> errorExpr s _ -> do reportAt AmbiguousName s "this enumeration literal belongs to several types" "qualify it, e.g. `Color'(Red)`" errorExpr s noCandidate reasons = do e <- maybe (pure Nothing) (fmap Just . entity . fst) (headMaybe reasons) case (reasons, e) of ([(_, why)], Just callee) -> do report (diagnostic WrongArguments Semantic ("`" <> callee.name <> "` " <> why)) { primary = Just (label s why) , secondary = [Label {span = callee.span, text = Just "declared here"}] } errorExpr s _ -> do spans <- forM reasons \(d, why) -> (\x -> Label {span = x.span, text = Just why}) <$> entity d report (diagnostic WrongArguments Semantic (if null reasons then "nothing callable with this name here" else "no candidate matches these arguments")) { primary = Just (label s (if kind == CallProcedure then "no matching procedure" else "no matching function")) , secondary = spans } errorExpr s finishCall d info assoc = do logResolution (s, callKey) d formals <- mapM entity info.parameters arguments <- forM (zip3 formals assoc info.defaults) \(formal, (_, given), dflt) -> case (formal.kind, given) of (EObject o, Just a) -> do v <- argumentValue (Expect o.subtype.base) a referenceMark o.mode formal.name a -- (a scalar `in out` actual: one of the call's results, as Vibe writes the call) when (o.mode == Just ModeInOut) do scalar <- isScalar o.subtype.base when scalar (modify' \st -> st {scalarInOutActuals = v.span : st.scalarInOutActuals}) when (o.mode `elem` [Just ModeOut, Just ModeInOut]) do -- (a conversion of a variable is a view conversion as such an actual, RM 4.6(5/2): -- Verada's of scalars and of tagged types; an array's is refused, whose rules, -- RM 4.6(24.8/2-24.13/2), Verada does not check) variable <- case v.node of TConversionNode c -> do targetKind <- fullKind v.typeOf -- (of a tagged type through any view of it, a private one's too: `P.Root (C)`) tagged <- isJust <$> tagInfoOf v.typeOf viewable <- case targetKind of KClassWide _ -> pure True _ | tagged -> pure True _ -> isScalar v.typeOf if viewable then isVariable c.operand else pure False _ -> isVariable v markWritten v unless variable do reportAt NotAVariable v.span ("the `" <> modeText o.mode <> "` parameter `" <> formal.name <> "` needs a variable") "not a variable" pure v (_, Nothing) -> maybe (errorExpr s) pure dflt (_, Just a) -> argumentValue AnyType a st <- std let resultType = maybe st.errorType (.base) info.result checkReferenceLevel s d -- (a function with side effects is called only as an assignment's value or an object's -- initial value, SPARK RM 6.1.11) effects <- gets (elem d . (.sideEffectFunctions)) allowed <- asks (.sideEffectCall) when (effects && kind /= CallProcedure && allowed /= Just s) $ reportAt SideEffectCallPlace s "a function with `Side_Effects` is called only as the whole value of an assignment or of an object's declaration" "called inside an expression" transparent <- gets (Set.member d . (.transparentFunctions)) applied <- case info.expressionBody of Just body | transparent -> substituted s (zip info.parameters arguments) body _ -> pure Nothing case applied of Just x -> conform expect x Nothing -> mkExpr s resultType (TCallNode TCall {callee = d, arguments}) >>= conform (if kind == CallProcedure then AnyType else expect) modeText = \case Just ModeOut -> "out" Just ModeInOut -> "in out" _ -> "in" -- | The body of a transparent function with its parameters replaced by a call's arguments: -- an operation of its parameters, or a literal (Nothing for any other body). substituted :: Span -> [(DeclId, TExpr)] -> TExpr -> Sema (Maybe TExpr) substituted s actuals = go where go e = case e.node of TObject p | Just a <- lookup p actuals -> pure (Just a) TLiteral _ -> pure (Just (withSpan s e)) TBinaryNode b -> do l <- go b.left r <- go b.right traverse (mkExpr s e.typeOf) (TBinaryNode <$> (TBinary b.op <$> l <*> r)) TUnaryNode u -> do x <- go u.operand traverse (mkExpr s e.typeOf) (TUnaryNode . TUnary u.op <$> x) _ -> pure Nothing -- | Varc marks the actuals of @out@ and @inout@ parameters with @&@ (ledger D65): one -- missing (B0703) or one on another actual (B0704) is reported. The marked actuals are -- recorded, so that a translation to Varc can mark them. referenceMark :: Maybe ParamMode -> Text -> A.Argument -> Sema () referenceMark mode formalName a = do let byReference = mode `elem` [Just ModeOut, Just ModeInOut] valueSpan = case a.value of A.ArgExpr x -> x.span A.ArgRange r -> r.span A.ArgBox -> a.span when byReference (modify' \st -> st {references = Set.insert valueSpan st.references}) when (mode == Just ModeOut) (modify' \st -> st {outActuals = valueSpan : st.outActuals}) case a.reference of Just False | byReference -> report (diagnostic ReferenceMarkMissing Semantic ("the `" <> modeName <> "` parameter `" <> formalName <> "` needs `&` on its argument")) { primary = Just (label valueSpan "changed by the call") , notes = [Note {text = "Varc marks every argument a call may change, so that the call says so", span = Nothing}] , fixes = [Fix {span = valueSpan {end = valueSpan.start}, replacement = Verbatim "&", description = "add `&`"}] } Just True | not byReference -> report (diagnostic ReferenceMarkNeedless Semantic ("`&` on the argument of the `in` parameter `" <> formalName <> "`")) { primary = Just (label valueSpan "not changed by the call") , notes = [Note {text = "only the arguments of `out` and `inout` parameters are marked with `&`", span = Nothing}] , fixes = [Fix {span = valueSpan {start = valueSpan.start - 1, end = valueSpan.start}, replacement = Verbatim "", description = "remove `&`"}] } _ -> pure () where modeName = if mode == Just ModeOut then "out" else "inout" -- | A procedure call statement: the name, with or without arguments. procedureCall :: A.Expr -> Sema TStmtNode procedureCall e = do let (prefix, args) = case e.node of A.EApply ap -> (ap.prefix, ap.arguments) _ -> (e, []) view <- case prefix.node of A.ESelected sel -> fmap (sel,) <$> prefixedView sel _ -> pure Nothing case view of Just (sel, ds) -> do call <- resolveCall CallProcedure AnyType e.span ds (prefixArgument sel : args) pure case call.node of TCallNode c -> TCallStmt c _ -> TErrorStmt Nothing -> plainCall prefix args where plainCall prefix args = denote prefix >>= \case Just (DOverloaded ds) -> do call <- resolveCall CallProcedure AnyType e.span ds args case call.node of TCallNode c -> reraiseOccurrence c _ -> pure TErrorStmt -- (a generic procedure called directly: the instance its arguments' types make) Just (DGeneric g) | A.EApply ap <- e.node -> callInstance e.span g ap >>= \case Just d -> do call <- resolveCall CallProcedure AnyType e.span [d] args pure case call.node of TCallNode c -> TCallStmt c _ -> TErrorStmt Nothing -> pure TErrorStmt Just DNone -> pure TErrorStmt -- a generic procedure called by name (Vibe's `xs.sort()`): of its instance made here Just (DGeneric g) -> callInstance e.span g A.Apply {prefix, arguments = args, bracketed = Nothing} >>= \case Just d -> do call <- resolveCall CallProcedure AnyType e.span [d] args pure case call.node of TCallNode c -> TCallStmt c _ -> TErrorStmt Nothing -> pure TErrorStmt _ -> do -- an access-to-procedure value: an indirect call (its arguments matched to the profile) target <- expression AnyType prefix >>= implicitDereference kind <- fullKind target.typeOf case kind of KSubprogramAccess sa -> do call <- resolveCall CallProcedure AnyType e.span [sa.profile] args pure case call.node of TCallNode c -> TIndirectCallStmt TIndirectCall {target, arguments = c.arguments} _ -> TErrorStmt KError -> pure TErrorStmt _ -> do reportAt NotCallable prefix.span "this is not a procedure" "a procedure name is required for a call statement" pure TErrorStmt -- | A procedure call, but `Ada.Exceptions.Reraise_Occurrence (X)` of the occurrence its -- handler names (`when X : E`) is `raise;` (D251): the exception is one of the handler's -- choices, which the proof covers as for any raise. Of any other occurrence (one kept and -- reraised elsewhere) the proof cannot know the exception, so it is left out (B0501). reraiseOccurrence :: TCall -> Sema TStmtNode reraiseOccurrence c = do name <- fullName c.callee if Text.toCaseFold name /= "ada.exceptions.reraise_occurrence" then pure (TCallStmt c) else do own <- asks (.handlerOccurrence) case c.arguments of [x] | TObject d <- x.node -> do o <- entity d if Just o.span == own then pure TReraise else TErrorStmt <$ elsewhere x.span x : _ -> TErrorStmt <$ elsewhere x.span [] -> pure TErrorStmt where elsewhere at = reportExcluded at "`Reraise_Occurrence` of an occurrence other than the one its handler names is not in Verada" reraiseReplacement -- | Whether a context of this kind wants a value other than an access-to-subprogram one (so -- that `F.all` there calls F). wantsValue :: TypeKind -> Bool wantsValue = \case KSubprogramAccess _ -> False KError -> False _ -> True headMaybe :: [a] -> Maybe a headMaybe = \case x : _ -> Just x [] -> Nothing -- | Whether an expression denotes a variable (RM 3.3): an object that is not a constant or -- an @in@ parameter, or a component or element of one. isVariable :: TExpr -> Sema Bool isVariable e = case e.node of TErrorExpr -> pure True TObject d -> entity d >>= \x -> pure case x.kind of EObject o -> not o.constant && o.mode /= Just ModeIn _ -> False TIndexedNode i -> isVariable i.prefix -- a discriminant is a constant of its record (RM 3.7(28)) TComponentNode c -> do kind <- fullKind c.prefix.typeOf case kind of KRecord r | isDiscriminantField r c.component -> pure False _ -> isVariable c.prefix TSliceNode sl -> isVariable sl.prefix -- a view conversion of a tagged variable (RM 4.6(5/2)) TConversionNode c -> do kind <- fullKind e.typeOf tagged <- isJust <$> tagInfoOf e.typeOf case kind of KClassWide _ -> isVariable c.operand _ | tagged -> isVariable c.operand _ -> pure False -- writing through an access value writes the value (ownership makes it unique) TDereference p -> fullKind p.typeOf >>= \case KAccess a | not a.toConstant -> do -- through a borrower (an anonymous access-to-variable value), even a constant one; -- through a general access-to-variable value, even a constant one: it designates a -- variable (RM 4.1(9), 3.10(9)), aliased or made by `new` at library level, which is -- used only through such values from then on (B6002), so the write is seen anonymous <- (\def -> isNothing def.decl) <$> typeDef p.typeOf if anonymous || a.general then pure True else (||) <$> isVariable p <*> borrowedParameter p _ -> pure False _ -> pure False -- | Record that a variable is changed through this name (for B8005): the object it names, -- and what that object renames. markWritten :: TExpr -> Sema () markWritten e = case e.node of TObject d -> do x <- entity d case x.kind of EObject o | Just target <- o.renames -> markWritten target _ -> pure () modify' \st -> st {written = Set.insert d st.written} TIndexedNode i -> markWritten i.prefix TComponentNode c -> markWritten c.prefix TSliceNode sl -> markWritten sl.prefix TConversionNode c -> markWritten c.operand _ -> pure () -- | An `in` parameter of a procedure that has an access-to-variable type borrows what it -- designates (SPARK RM 3.10), so that can be written. borrowedParameter :: TExpr -> Sema Bool borrowedParameter e = case e.node of TObject d -> do x <- entity d case x.kind of EObject o | o.mode == Just ModeIn, Just owner <- x.parent -> do oe <- entity owner pure case oe.kind of ESubprogram s -> s.kind == Procedure _ -> False _ -> pure False _ -> pure False -- | Whether one of two tagged types is an interface (a value of the other's class may also -- be of the interface's: only its tag tells). eitherInterface :: TypeId -> TypeId -> Sema Bool eitherInterface a b = do ta <- tagInfoOf a tb <- tagInfoOf b pure (maybe False (.isInterface) ta || maybe False (.isInterface) tb) -- * Operators (RM 4.5) unary :: Expect -> Span -> A.Unary -> Sema TExpr unary expect s u0 = do python <- optionalsHere u <- if python then narrowed u0.operand <&> \x -> A.Unary {op = u0.op, operand = x} else pure u0 operandShapes <- shapes u.operand predefined <- filterM (\t -> unaryApplies u.op <$> fullKind t) (nub [t | Exactly t <- operandShapes]) user <- userOperatorCall expect s (A.unaryOpText u.op) [u.operand] [(t, t) | t <- predefined] -- (where the operand could be of several types and the predefined operator applies to -- one of them, that one: `not (+E1 < E2)` takes the predefined `<` of E1's type, whose -- result is Boolean, over a user `<` returning E1's type, which has no `not`, RM 8.6(29)) specific <- filterM (fmap not . isUniversal) predefined -- (and where the context's type is one of them, that one: `not False /= X` of a type -- derived from Boolean, RM 8.6) let operandType = case (expect, specific, nub [t | Exactly t <- operandShapes]) of (Expect t, _, _ : _ : _) | t `elem` predefined -> Expect t (_, [t], _ : _ : _) -> Expect t _ -> AnyType maybe (predefinedUnary operandType expect s u) pure user predefinedUnary :: Expect -> Expect -> Span -> A.Unary -> Sema TExpr predefinedUnary operandType expect s u = booleanArrayOperation s (A.unaryOpText u.op) [u.operand] >>= \case Just (t, x) -> expression (Expect t) x >>= conform expect Nothing -> predefinedUnaryOf operandType expect s u predefinedUnaryOf :: Expect -> Expect -> Span -> A.Unary -> Sema TExpr predefinedUnaryOf operandType expect s u = do operand0 <- expression operandType u.operand universal <- isUniversal operand0.typeOf operand <- if universal then conform expect operand0 else pure operand0 let t = operand.typeOf kind <- fullKind t let op = case u.op of A.OpPlus -> TPlus A.OpMinus -> TMinus A.OpNot -> TNot A.OpAbs -> TAbs allowed = case (op, kind) of (_, KError) -> True (TNot, KEnumeration e) -> e.isBoolean (TNot, KModular _) -> True (TNot, KArray _) -> False (TNot, _) -> False (_, KInteger _) -> True (_, KModular _) -> op /= TAbs (_, KReal _) -> True (_, KFixed _) -> op /= TNot _ -> False if allowed then do operatorVisible s (A.unaryOpText u.op) t mkExpr s t (TUnaryNode TUnary {op, operand}) >>= conform expect else noOperator s (A.unaryOpText u.op) t noOperator :: Span -> Text -> TypeId -> Sema TExpr noOperator s opText t = do tn <- typeName t reportAt NoOperator s ("operator `" <> opText <> "` is not defined for `" <> tn <> "`") ("`" <> tn <> "` has no `" <> opText <> "`") errorExpr s -- | The user-declared operator functions of this name that fit the operands and the context, -- weighed against the predefined operator (RM 8.6): 'Nothing' means the predefined operator -- (or no operator: the caller reports it); otherwise the chosen call, or an ambiguity. -- @predefined@ gives the types whose predefined operator fits the operands, with its -- result type. A user operator whose profile is the predefined one's overrides it. userOperatorCall :: Expect -> Span -> Text -> [A.Expr] -> [(TypeId, TypeId)] -> Sema (Maybe TExpr) userOperatorCall expect s opText operands predefined = do -- (in an instance's text, the operator the generic's own text applies, RM 12.3(14): the -- predefined one, or a formal's whose actual is the predefined operator) inGeneric <- asks (Map.lookup (s, opText) . (.genericResolutions)) bound <- gets (.formalSubprograms) case inGeneric of Just ResolvedPredefined -> pure Nothing Just (ResolvedFormal k) | k `notElem` map snd bound -> pure Nothing _ -> do chosen <- userOperatorCallOf expect s opText operands predefined inGeneric when (isNothing chosen) (logPredefined (s, opText)) pure chosen userOperatorCallOf :: Expect -> Span -> Text -> [A.Expr] -> [(TypeId, TypeId)] -> Maybe GenericResolution -> Sema (Maybe TExpr) userOperatorCallOf expect s opText operands predefined inGeneric = do only <- asks ((== Just s) . (.predefinedAt)) direct <- if only then pure [] else operatorCandidates opText (length operands) -- (in Vibe, an operand's own operators, its type's primitives, as Python's `xs + ys` of a -- list or `a | b` of sets: an implicit instance's package is not used by the module) python <- asks (.python) varc <- asks (.varc) own <- if python || varc then do operandShapes <- mapM shapes operands -- (in Varc, only an implicit instance's type, whose package no use clause names) let ownTypes = nub [t | Exactly t <- concat operandShapes] types' <- if python then pure ownTypes else filterM implicitInstanceType ownTypes ds <- concat <$> mapM (primitivesNamed ("\"" <> opText <> "\"")) types' fmap catMaybes . forM (nub ds) $ \d -> entity d >>= \e -> pure case e.kind of ESubprogram info | info.kind == Function && length info.parameters == length operands -> Just (d, info) _ -> Nothing else pure [] let declared = if only then [] else direct <> [c | c@(d, _) <- own, d `notElem` map fst direct] -- (in an instance, `=` of a formal type's actual is its predefined one, unless the -- generic's text gives another: RM 4.5.2(24.1)) formalEqualities <- gets (.formalEquality) shapesNow <- if opText `elem` ["=", "/="] && not (Map.null formalEqualities) then concat <$> mapM shapes operands else pure [] candidates <- case [x | Exactly t <- shapesNow, Just x <- [Map.lookup t formalEqualities]] of (allowed, spans) : _ -> flip filterM declared \(d, _) -> do e <- entity d let within sp = sp.file == e.span.file && sp.start <= e.span.start && e.span.end <= sp.end pure (d `elem` allowed || any within spans) [] -> pure declared if null candidates then pure Nothing else do operandShapes <- mapM shapes operands usable0 <- flip filterM candidates \(_, info) -> do types <- formalTypes info fit <- and <$> zipWithM admitsAny types operandShapes resultOk <- fitsContext (fmap (.base) info.result) pure (fit && resultOk) -- a user operator with the predefined one's profile (operands and result) overrides it -- (but a use-visible one of a scalar type declared elsewhere is hidden by the type's -- predefined operator, which is directly visible, RM 8.4(9): `use Pkg` of an instance -- `"+"` of Integer's profile; one declared with its type overrides the type's, RM -- 8.3(9), `use P` of P's `"*"` of P.Int) scs <- gets (.scopes) let directly d = any (any (elem d) . Map.elems . (.names)) scs sd <- std let regions = Just sd.package : map Just (mapMaybe (.owner) scs) hidden <- flip filterM candidates \(d, info) -> do formals <- formalTypes info owner <- (.parent) <$> entity d case nub formals of [t] | not (directly d) -> do scalar <- isScalar t typeOwner <- typeDef t >>= maybe (pure Nothing) (fmap (.parent) . entity) . (.decl) -- (the type's operators directly visible: declared in Standard or in a region -- enclosing this place) if scalar && typeOwner /= owner && typeOwner `elem` regions then hiddenScalarProfile t (fmap (.base) info.result) else pure False _ -> pure False let shown = [c | c@(d, _) <- candidates, d `notElem` map fst hidden] profiles <- forM shown \(_, info) -> (,fmap (.base) info.result) <$> formalTypes info let overridden (t, r) = any (\(formals, result) -> all (== t) formals && result == Just r) profiles remaining0 <- filterM (\p -> (not (overridden p) &&) <$> fitsContext (Just (snd p))) predefined -- (where the context gives a specific type and a declared operator of it applies, the -- predefined operator of the universal types is not a rival: `X : QT := +0` with QT's -- `"+"` declared, ACATS C34014T) specific <- case expect of Expect t -> not <$> isUniversal t AnyType -> pure False remaining <- if specific && not (null usable0) then filterM (fmap not . isUniversal . fst) remaining0 else pure remaining0 let usable = [c | c@(d, _) <- usable0, d `notElem` map fst hidden] let args = [A.Argument {span = x.span, formal = Nothing, value = A.ArgExpr x, reference = Nothing} | x <- operands] rivalPredefined <- filterM (fitsContext . Just . snd) predefined noteRivals (map fst usable) (not (null rivalPredefined)) chosen <- maybe (pure []) (\r -> filterM (resolvedAs r . fst) usable) inGeneric rootRemaining <- mapM (isUniversal . fst) remaining let userCall ds = do call <- resolveCall CallFunction expect s ds args copyResolution (s, callKey) (s, opText) pure (Just call) case (usable, remaining) of _ | not (null chosen) -> userCall (map fst chosen) ([], _) -> pure Nothing (_, []) -> userCall (map fst usable) -- (the predefined operator of a root numeric type is preferred to the others, RM -- 8.6(29): `Natural'Pos (X) + 1` adds universal integers, whatever `"+"` is declared) _ | or rootRemaining -> pure Nothing _ -> do spans <- mapM (\(d, _) -> (.span) <$> entity d) usable names <- mapM (typeName . fst) remaining report (diagnostic AmbiguousName Semantic ("this use of `" <> opText <> "` is ambiguous")) { primary = Just (label s "matches more than one operator") , secondary = [Label {span = sp, text = Just "candidate"} | sp <- spans] , notes = [Note {text = "the predefined `" <> opText <> "` of `" <> n <> "` also matches", span = Nothing} | n <- names] , advice = Just "qualify the expression or an operand (`T'(...)`) to say which one is meant" } Just <$> errorExpr s where -- Direct visibility depends on the declared profile, even when both actuals are -- universal literals. Only a homograph hides a use-visible operator (RM 8.4(9)). hiddenScalarProfile t result = case operands of -- Keep component concatenation on its existing visibility path. Its result is an -- array, whose own operators can be use-visible (RM 4.5.3), not a scalar operator. [_, _] | opText == "&" -> pure True [_] | Just op <- find ((== opText) . A.unaryOpText) [minBound .. maxBound] -> (result == Just t &&) . unaryApplies op <$> fullKind t [_, _] | opText `elem` ["=", "/=", "<", "<=", ">", ">="] -> (\sd -> result == Just sd.boolean) <$> std [_, _] | Just op <- find ((== opText) . A.binaryOpText) [minBound .. maxBound] -> (result == Just t &&) . elem t <$> predefinedTypes op [Exactly t] [Exactly t] _ -> pure False fitsContext = \case Nothing -> pure False Just r -> case expect of Expect t -> compatible t r AnyType -> pure True -- | The key of a call's resolution in an instance's text (an operator's is its symbol). callKey :: Text callKey = "call" -- | The candidates of a call in an instance's text that the generic's own text could mean -- there (RM 12.3(14)): a formal subprogram's actual only where the generic named the formal, -- and otherwise what it named (all of them where the generic's view says nothing of it). asInGeneric :: (Span, Text) -> [DeclId] -> Sema [DeclId] asInGeneric key ds = asks (Map.lookup key . (.genericResolutions)) >>= \case Nothing -> pure ds Just r -> do kept <- filterM (resolvedAs r) ds pure (if null kept then ds else kept) -- | Whether a candidate in an instance's text is what the generic's text resolved to. resolvedAs :: GenericResolution -> DeclId -> Sema Bool resolvedAs r d = case r of ResolvedFormal k -> gets (elem (d, k) . (.formalSubprograms)) ResolvedDeclaredAt at -> entity d <&> \e -> e.span == at ResolvedPredefined -> pure False -- | In the generic's own view of an instance's text: what this call resolved to. logResolution :: (Span, Text) -> DeclId -> Sema () logResolution key d = gets (.resolutionLog) >>= \case Nothing -> pure () Just logged -> do bound <- gets (.formalSubprograms) r <- case lookup d bound of Just k -> pure (ResolvedFormal k) Nothing -> ResolvedDeclaredAt . (.span) <$> entity d modify' \st -> st {resolutionLog = Just (Map.insert key r logged)} logPredefined :: (Span, Text) -> Sema () logPredefined key = modify' \st -> st {resolutionLog = Map.insert key ResolvedPredefined <$> st.resolutionLog} copyResolution :: (Span, Text) -> (Span, Text) -> Sema () copyResolution from to = modify' \st -> st {resolutionLog = (\logged -> maybe logged (\r -> Map.insert to r logged) (Map.lookup from logged)) <$> st.resolutionLog} -- | In an instance's text: a call or operator whose candidates include a formal -- subprogram's actual and something else (another candidate, or the predefined operator), -- which the instance's own types cannot tell apart as the generic's could. noteRivals :: [DeclId] -> Bool -> Sema () noteRivals candidates predefinedFits = do bound <- gets (map fst . (.formalSubprograms)) when (any (`elem` bound) candidates && (predefinedFits || length candidates > 1)) $ modify' \st -> st {rivalFormals = True} -- | The operator @/=@: a user-declared one, or the negation of a user-declared @=@ (which -- implicitly declares its @/=@, RM 6.6), or 'Nothing' for the predefined one. inequalityCall :: Expect -> Span -> [A.Expr] -> [(TypeId, TypeId)] -> Sema (Maybe TExpr) inequalityCall expect s operands predefined = do direct <- userOperatorCall expect s "/=" operands predefined case direct of Just e -> pure (Just e) Nothing -> do st <- std equality <- userOperatorCall (Expect st.boolean) s "=" operands predefined forM equality \e -> case e.node of TErrorExpr -> pure e _ -> mkExpr s st.boolean (TUnaryNode TUnary {op = TNot, operand = e}) >>= conform expect -- | The types a predefined relational operator could compare these operands in, with its -- (Boolean) result. relationalTypes :: [A.Expr] -> Sema [(TypeId, TypeId)] relationalTypes operands = do st <- std ss <- mapM shapes operands let named' = nub [t | Exactly t <- concat ss] specific <- filterM (fmap not . isUniversal) named' ts <- filterM (\t -> and <$> mapM (admitsAny t) ss) (if null specific then named' else specific) pure [(t, st.boolean) | t <- ts] binary :: Expect -> Span -> A.Binary -> Sema TExpr binary expect s b0 = do python0 <- optionalsHere -- (Vibe's `x is None` and `x is not None` of a `T | None`: whether it has no value, or -- one) absence <- if python0 && b0.op `elem` [A.OpEq, A.OpNe] && b0.right.node == A.ENull then do (probe, _) <- trial (expression AnyType b0.left) optionalType probe.typeOf else pure Nothing case absence of Just o -> do x <- expression AnyType b0.left st0 <- std full <- denotingName s o.hasValue modify' \state -> state {coercions = (s, TestPresent full (b0.op == A.OpNe)) : state.coercions} present <- mkExpr s st0.boolean (TCallNode TCall {callee = o.hasValue, arguments = [x]}) tested <- if b0.op == A.OpNe then pure present else mkExpr s st0.boolean (TUnaryNode TUnary {op = TNot, operand = present}) conform expect tested -- (in Vibe, an optional operand of an operation of its element, `p + 1` after `p is not -- None`: its value; an optional value is compared as one) Nothing | python0 && b0.op `notElem` [A.OpEq, A.OpNe] -> (\l r -> A.Binary {op = b0.op, left = l, right = r}) <$> narrowed b0.left <*> narrowed b0.right >>= binaryPlain expect s | otherwise -> binaryPlain expect s b0 binaryPlain :: Expect -> Span -> A.Binary -> Sema TExpr binaryPlain expect s b00 = booleanArrayOperation s (A.binaryOpText b00.op) [b00.left, b00.right] >>= \case Just (t, x) -> expression (Expect t) x >>= conform expect Nothing -> binaryPlainOf expect s b00 -- | A logical operator of a one-dimensional array of Booleans (RM 4.5.1(2), 4.5.6(3)), -- predefined with the type unless one of its own is visible: the array of the operation -- applied to the components in order, `[for I in L'Range => L (I) and R (I - L'First + -- R'First)]`, the operands' lengths the same (a check, as Ada's Constraint_Error). booleanArrayOperation :: Span -> Text -> [A.Expr] -> Sema (Maybe (TypeId, A.Expr)) booleanArrayOperation s opText operands | opText `notElem` ["and", "or", "xor", "not"] = pure Nothing | otherwise = case operands of left : _ -> do -- (the operand's possible types first, cheaply: resolving it in full here and again -- for the scalar operator is exponential in nested `not`s, ACATS C45662B) leftShapes <- shapes left arrayLike <- fmap or . forM leftShapes $ \case Exactly t -> fullKind t <&> \case KArray _ -> True KError -> True _ -> False _ -> pure True if null leftShapes || arrayLike then logicalOf left else pure Nothing [] -> pure Nothing where logicalOf left = do (probe, problems) <- trial (expression AnyType left) kind <- fullKind probe.typeOf own <- lookupDirect ("\"" <> opText <> "\"") booleanComponents <- case kind of KArray a | [_] <- a.indices -> fullKind a.component.base <&> \case KEnumeration e -> e.isBoolean _ -> False _ -> pure False -- (operands of one constrained array type have the same length: no check) sameConstrained <- case (kind, operands) of (KArray a, [_, r]) | a.constrained -> do (other, _) <- trial (expression AnyType r) pure (other.typeOf == probe.typeOf) _ -> pure False -- (a constrained type's index subtype, by a hidden name: the aggregate's range is -- static even when the operand is itself an expression) rangeName <- case kind of KArray a | a.constrained, [ix] <- a.indices, null problems, booleanComponents -> do let hidden = "Logical'Range'" <> tshow s.start known <- lookupDirect hidden when (null known) (void (declare hidden s (ESubtype ix))) pure (Just hidden) _ -> pure Nothing -- (an index of an enumeration type, Boolean say, is shifted by its positions) positional <- case kind of KArray a | [ix] <- a.indices, null problems, booleanComponents -> fullKind ix.base >>= \case KEnumeration _ -> do let hidden = "Logical'Index_Type'" <> tshow s.start known <- lookupDirect hidden when (null known) (void (declare hidden s (ESubtype (unconstrained ix.base)))) pure (Just hidden) _ -> pure Nothing _ -> pure Nothing pure if null problems && null own && booleanComponents then Just (probe.typeOf, rewritten rangeName positional sameConstrained left) else Nothing ident t = A.Identifier {span = s, text = t} ref t = A.Expr {span = s, node = A.ENameRef (ident t)} attr x d = A.Expr {span = s, node = A.EAttribute A.AttributeRef {prefix = x, designator = ident d, arguments = []}} at x i = A.Expr {span = s, node = A.EApply A.Apply {prefix = x, arguments = [A.Argument {span = s, formal = Nothing, value = A.ArgExpr i, reference = Nothing}], bracketed = Nothing}} binop o l r = A.Expr {span = s, node = A.EBinary A.Binary {op = o, left = l, right = r}} index = "Logical'Index" attrOf x d args = A.Expr {span = s, node = A.EAttribute A.AttributeRef {prefix = x, designator = ident d, arguments = args}} rewritten rangeName positional sameLengths left = case operands of [x] -> iterated rangeName left (A.Expr {span = s, node = A.EUnary A.Unary {op = A.OpNot, operand = at x (ref index)}}) [l, r] -> let op = case opText of "and" -> A.OpAnd "or" -> A.OpOr _ -> A.OpXor shifted = case positional of Nothing -> binop A.OpAdd (binop A.OpSub (ref index) (attr l "First")) (attr r "First") Just it -> attrOf (ref it) "Val" [binop A.OpAdd (binop A.OpSub (attrOf (ref it) "Pos" [ref index]) (attrOf (ref it) "Pos" [attr l "First"])) (attrOf (ref it) "Pos" [attr r "First"])] sameLength = binop A.OpEq (attr l "Length") (attr r "Length") failed = A.Expr {span = s, node = A.ERaise A.RaiseExpr {exception = ref "Constraint_Error", message = Nothing}} whole = iterated rangeName l (binop op (at l (ref index)) (at r shifted)) in if sameLengths then whole else A.Expr {span = s, node = A.EIf A.IfExpr {condition = sameLength, thenValue = whole, elsifs = [], elseValue = Just failed}} _ -> left iterated rangeName over value = A.Expr {span = s, node = A.EAggregate A.Aggregate {bracket = True, contents = A.PlainAggregate (A.Associations [A.IteratedAssocNode A.IteratedAssoc {span = s, iterator = A.Iterator {parameter = ident index, subtype = Nothing, reverse = False, domain = A.InRange (A.DiscreteSubtype A.SubtypeIndication {span = s, notNull = False, mark = maybe (attr over "Range") ref rangeName, constraint = Nothing}), filter = Nothing, whileCondition = Nothing, alongside = []}, value}])}} binaryPlainOf :: Expect -> Span -> A.Binary -> Sema TExpr binaryPlainOf expect s b0 = do st <- std -- (Python's `+` of strings joins them: in Vibe, a string's or a text's `+` is `&`) python <- asks (.python) joined <- if python && b0.op == A.OpAdd then do (probe, _) <- trial (expression AnyType b0.left) tn <- typeName probe.typeOf pure (probe.typeOf == st.string || tn == "Text") else pure False -- (a translation writes the join as the target syntax joins: Vada's `&`, Varc's `++`) when joined $ modify' \state -> state {surfaceForms = ((s, "join"), AsOperand) : state.surfaceForms} -- (only operands that are names or aggregates are taken apart: no other is probed, as -- probing a form, `s[i]`, could fix its reading before its context does) let plainOperand x = case x.node of A.ENameRef _ -> True A.ESelected _ -> True A.EParen y -> plainOperand y A.EAggregate _ -> True _ -> False -- (Python's tuples are ordered by their items in turn, the first that differ deciding) tupleItems <- if python && b0.op `elem` [A.OpLt, A.OpLe, A.OpGt, A.OpGe] && plainOperand b0.left then do (probe, _) <- trial (expression AnyType b0.left) tn <- typeName probe.typeOf kind <- fullKind probe.typeOf pure case kind of KRecord r | tn == "Tuple" , names <- [d.name | d <- r.components] , not (null names) , map Text.toCaseFold names == [Text.toCaseFold ("Item_" <> Text.pack (show k)) | k <- [0 .. length names - 1]] -> Just names _ -> Nothing else pure Nothing -- (a record's predefined `=` composes its components' own: two records are equal when -- each component is equal by its type's `=`, a text's by its characters, RM 4.5.2(15/3)) composed <- if b0.op `elem` [A.OpEq, A.OpNe] && plainOperand b0.left && plainOperand b0.right then do (probe, _) <- trial (expression AnyType b0.left) kind <- fullKind probe.typeOf case kind of KRecord r | all (null . (.presence)) r.components, not r.limited, not (null r.components) -> do own <- primitivesNamed "\"=\"" probe.typeOf userComponents <- filterM (fmap (not . null) . primitivesNamed "\"=\"" . (.subtype.base)) r.components -- (an operand is a name, or an aggregate, whose components are its values: a -- component of another value, a call's, is not taken apart, and its equality -- stays the predefined one) let names = [c.name | c <- r.components] parts x = case x.node of A.ENameRef _ -> Just Nothing A.ESelected _ -> Just Nothing A.EParen y -> parts y A.EAggregate A.Aggregate {contents = A.PlainAggregate (A.Associations as)} | length as == length names , vs@(_ : _) <- [v | A.PositionalAssoc v <- as] , length vs == length names -> Just (Just vs) _ -> Nothing pure case (parts b0.left, parts b0.right) of (Just l, Just r') | null own, not (null userComponents) -> Just (names, l, r') _ -> Nothing _ -> pure Nothing else pure Nothing case (tupleItems, composed) of (Just names, _) -> expression expect (lexicographic names) (_, Just (names, lparts, rparts)) -> let component side x ps k n = case ps of Just vs | v : _ <- drop k vs -> v _ -> item side x k n equalities = [(k, op2 (16 * k + 2) A.OpEq (component 0 b0.left lparts k n) (component 1 b0.right rparts k n)) | (k, n) <- zip [0 ..] names] conjunction = case equalities of (_, e) : rest -> foldl (\x (k, y) -> placed (16 * k + 10) (A.EBinary A.Binary {op = A.OpAnd, left = x, right = y})) e rest [] -> at (A.ENameRef A.Identifier {span = s, text = "True"}) in expression expect if b0.op == A.OpEq then conjunction else placed 3012 (A.EUnary A.Unary {op = A.OpNot, operand = placed 3011 (A.EParen conjunction)}) _ -> binaryOperator expect s (if joined then A.Binary {op = A.OpConcat, left = b0.left, right = b0.right} else b0) where at node = A.Expr {span = s, node} -- (each generated expression at a place of no width of its own: expressions are known -- by their places, and each item, comparison and joining is its own) -- (beyond the file, at a place each comparison's own start fixes, so that no other -- expression has it) placed k node = A.Expr {span = generatedAt k, node} generatedAt k = s {start = 1000000000 + 4096 * s.start + k, end = 1000000000 + 4096 * s.start + k} index n = maybe 0 (\(k, _) -> k) (listToMaybe (reads (Text.unpack (Text.drop 5 n)) :: [(Int, String)])) item side x k n = placed (16 * k + side) (A.ESelected A.Selected {prefix = x, selector = A.SelectIdentifier A.Identifier {span = s, text = n}}) op2 k o l r = placed k (A.EParen (placed (k + 4) (A.EBinary A.Binary {op = o, left = l, right = r}))) -- `a < b`: `a.0 < b.0 or else (a.0 = b.0 and then (... a.n < b.n))`, the last item's -- comparison the operator's own (`<=` there for `<=`); `>` and `>=` the other way round (smaller, larger, strict) = case b0.op of A.OpLt -> (b0.left, b0.right, True) A.OpLe -> (b0.left, b0.right, False) A.OpGt -> (b0.right, b0.left, True) _ -> (b0.right, b0.left, False) lexicographic = \case [n] -> op2 (16 * index n + 2) (if strict then A.OpLt else A.OpLe) (item 0 smaller (index n) n) (item 1 larger (index n) n) n : rest -> let k = 16 * index n in op2 (k + 3) A.OpOrElse (op2 (k + 2) A.OpLt (item 0 smaller (index n) n) (item 1 larger (index n) n)) (op2 (k + 5) A.OpAndThen (op2 (k + 8) A.OpEq (item 0 smaller (index n) n) (item 1 larger (index n) n)) (lexicographic rest)) [] -> at (A.ENameRef A.Identifier {span = s, text = "True"}) binaryOperator :: Expect -> Span -> A.Binary -> Sema TExpr binaryOperator expect s b = do st <- std case b.op of op | op `elem` [A.OpAndThen, A.OpOrElse] -> do -- (of any boolean type, RM 4.5.1(2): the context's, else the left operand's) contextual <- case expect of Expect t -> fullKind t <&> \case KEnumeration en | en.isBoolean -> Just t _ -> Nothing AnyType -> pure Nothing leftGuess <- maybe (otherBooleanType b.left) (pure . Just) contextual leftType <- case leftGuess of Just t | t /= st.boolean -> (\(_, problems) -> if null problems then Just t else Nothing) <$> trial (expression (Expect t) b.left) other -> pure other case leftType of Just t | t /= st.boolean -> do l <- expression (Expect t) b.left lc <- mkExpr b.left.span st.boolean (TConversionNode TConversion {target = unconstrained st.boolean, operand = l, qualified = False}) r <- statically (decided op l) (underCondition (Just lc) (expression (Expect t) b.right)) mkExpr s t (TBinaryNode TBinary {op = translate op, left = l, right = r}) >>= conform expect _ -> do l <- boolean b.left r <- statically (decided op l) (underCondition (Just l) (boolean b.right)) mkExpr s st.boolean (TBinaryNode TBinary {op = translate op, left = l, right = r}) >>= conform expect | op `elem` [A.OpEq, A.OpNe, A.OpLt, A.OpLe, A.OpGt, A.OpGe] -> do predefined <- relationalTypes [b.left, b.right] user <- if op == A.OpNe then inequalityCall expect s [b.left, b.right] predefined else userOperatorCall expect s (A.binaryOpText op) [b.left, b.right] predefined maybe (comparison op) pure user | op == A.OpPow -> do ls <- shapes b.left rs <- shapes b.right predefined <- predefinedTypes op ls rs user <- userOperatorCall expect s "**" [b.left, b.right] [(t, t) | t <- predefined] maybe power pure user | otherwise -> do ls <- shapes b.left rs <- shapes b.right fixed <- fixedProduct op ls rs case fixed of Just x -> pure x Nothing -> do predefined <- predefinedTypes op ls rs user <- userOperatorCall expect s (A.binaryOpText op) [b.left, b.right] [(t, t) | t <- predefined] maybe (arithmetic op) pure user where -- fixed-point multiplication and division (RM 4.5.5): by an integer, in the fixed type; -- of two fixed values, in the fixed type the context expects (universal_fixed converted) fixedProduct op ls rs | op `notElem` [A.OpMul, A.OpDiv] = pure Nothing | otherwise = do let named xs = [t | Exactly t <- xs] let isFixed = \case KFixed _ -> True _ -> False isIntegral = \case KInteger _ -> True _ -> False fixedOf xs = filterM (\t -> isFixed <$> fullKind t) (named xs) integralOf xs = filterM (\t -> isIntegral <$> fullKind t) (named xs) lf <- fixedOf ls rf <- fixedOf rs li <- integralOf ls ri <- integralOf rs expected <- case expect of Expect t -> (\k -> if isFixed k then Just t else Nothing) <$> fullKind t AnyType -> pure Nothing st <- std let realLiteral xs = Exactly st.universalReal `elem` xs let node result l r = mkExpr s result (TBinaryNode TBinary {op = if op == A.OpMul then TMul else TDiv, left = l, right = r}) case (lf, rf, li, ri, expected) of (f : _, [], _, i : _, _) -> do l <- expression (Expect f) b.left r <- expression (Expect (integerFor i)) b.right Just <$> (node f l r >>= conform expect) ([], f : _, i : _, [], _) | op == A.OpMul -> do l <- expression (Expect (integerFor i)) b.left r <- expression (Expect f) b.right Just <$> (node f l r >>= conform expect) -- a real literal times or over an integer, in the fixed type the context expects ([], [], _, i : _, Just t) | realLiteral ls -> do l <- expression (Expect t) b.left r <- expression (Expect (integerFor i)) b.right Just <$> node t l r ([], [], i : _, [], Just t) | op == A.OpMul, realLiteral rs -> do l <- expression (Expect (integerFor i)) b.left r <- expression (Expect t) b.right Just <$> node t l r -- by a real literal: Ada allows it (RM 4.5.5(19.1)), SPARK does not (_ : _, [], _, [], Just _) | realLiteral rs -> Just <$> literalOperand ([], _ : _, [], _, Just _) | op == A.OpMul, realLiteral ls -> Just <$> literalOperand (f1 : _, f2 : _, _, _, Just t) -> do l <- expression (Expect f1) b.left r <- expression (Expect f2) b.right Just <$> node t l r _ -> pure Nothing where integerFor t = t literalOperand = do reportAt ExcludedConstruct s "a real literal as an operand of a fixed-point multiplication or division is not in Verada" "give the literal a fixed-point type, such as `Money'(0.5)`, or use an integer" errorExpr s comparison op = do st <- std (l, r) <- operandPair AnyType let t = l.typeOf kind <- fullKind t -- (an array's ordering is predefined only when its components are discrete, RM -- 4.5.2(3)) discreteComponents <- case kind of KArray a -> isDiscrete a.component.base _ -> pure False let ordered = op `notElem` [A.OpEq, A.OpNe] allowed = case kind of KRecord _ -> not ordered KArray a -> not ordered || (length a.indices == 1 && discreteComponents) KPrivate p -> not ordered && not p.limited KAccess _ -> not ordered KSubprogramAccess _ -> not ordered _ -> True -- owning access values are unique, so two can only be equal when both are null let isNullLiteral x = case x.node of TNull -> True _ -> False accessPair = case kind of KAccess _ -> True _ -> False -- a limited type has no predefined equality limited <- isLimited t holdsAccess <- if accessPair then pure False else hasAccessPart t -- (an enclave's pointers share cells, so two may be equal, F7) shared <- if accessPair then enclavePointer t else pure False if accessPair && not ordered && not shared && not (isNullLiteral l || isNullLiteral r) then do reportAt NoOperator s "access values can only be compared with `null`" "compare one of them with `null`" errorExpr s else if holdsAccess && not ordered then do tn <- typeName t reportAt NoOperator s ("`" <> tn <> "` has access components, so its values have no predefined equality") "compare the components you mean" errorExpr s else if allowed && not (limited && not ordered) then do visibleOp t mkExpr s st.boolean (TBinaryNode TBinary {op = translate op, left = l, right = r}) >>= conform expect else noOperator s (A.binaryOpText op) t power = do st <- std l0 <- expression AnyType b.left lUniversal <- isUniversal l0.typeOf l <- if lUniversal then conform expect l0 else pure l0 r <- expression (Expect st.integer) b.right kind <- fullKind l.typeOf case kind of KError -> errorExpr s k | numericKind k -> visibleOp l.typeOf >> mkExpr s l.typeOf (TBinaryNode TBinary {op = TPow, left = l, right = r}) >>= conform expect _ -> noOperator s "**" l.typeOf arithmetic op | op == A.OpConcat = concatenation arithmetic op = do (l, r) <- operandPair expect sd <- std -- (root_integer times root_real is root_real, RM 4.5.5(19): `Scale * 0.5`) let t = if op == A.OpMul && l.typeOf == sd.universalInteger && r.typeOf == sd.universalReal then r.typeOf else l.typeOf kind <- fullKind t if operatorApplies op kind then do visibleOp t result <- mkExpr s t (TBinaryNode TBinary {op = translate op, left = l, right = r}) staticCheck result l r >>= conform expect else noOperator s (A.binaryOpText op) t -- `&` (RM 4.5.3): a one-dimensional array with another, or with a component, either side concatenation = do expected <- case expect of Expect t -> fullKind t >>= \k -> pure case k of KArray a | length a.indices == 1 -> Just (t, a.component.base) _ -> Nothing AnyType -> pure Nothing -- an operand that is itself a concatenation has the type the context gives this one -- (`1 & 2 & 3` into an array of integers) -- (so has a parenthesised one, `R1 & R2 & (R1 & R2)`, and an aggregate, which has no -- type of its own: `"ABC" & (7 .. 8 => 'D')`, RM 4.5.3(3)) -- (a literal is typed here only to see what it could be: it takes its type from the -- other operand or the context below, so a String's complaint about `"Ω"` would be -- wrong where a Wide_Wide_String is wanted) let literal ast = case ast.node of A.EString _ -> True A.ECharacter _ -> True -- (Varc's string literal, a text or a string by its context) A.ESurfaceForm A.SurfaceForm {kind = A.FormLiteralText} -> True A.EParen inner -> literal inner _ -> False operand x = case (unparenthesised x, expected) of (A.EBinary inner, Just (t, _)) | inner.op == A.OpConcat -> expression (Expect t) x (A.EAggregate _, Just (t, component)) -> do (_, problems) <- trial (expression (Expect t) x) expression (Expect (if null problems then t else component)) x _ | literal x -> fst <$> trial (expression AnyType x) _ -> expression AnyType x unparenthesised x = case x.node of A.EParen y -> unparenthesised y other -> other l0 <- operand b.left r0 <- operand b.right lk <- fullKind l0.typeOf rk <- fullKind r0.typeOf let arrayOf t k = case k of KArray a | length a.indices == 1 -> Just (t, a.component.base) _ -> Nothing -- (an operand's own array type first, then the context's, then a literal's: a -- string literal is a String only when nothing else gives its type, so -- `"abc" & "def"` where a Wide_Wide_String is expected is one, RM 4.2(4)) ownType ast x k = if literal ast then Nothing else arrayOf x.typeOf k chosen = listToMaybe (catMaybes [ownType b.left l0 lk, ownType b.right r0 rk, expected, arrayOf l0.typeOf lk, arrayOf r0.typeOf rk]) case chosen of Nothing -> do -- (a literal's own complaints, which its trial left out) mapM_ (expression AnyType) [x | x <- [b.left, b.right], literal x] case (lk, rk) of (KError, _) -> errorExpr s (_, KError) -> errorExpr s _ -> noOperator s "&" l0.typeOf Just (t, component) -> do let side ast x = do asArray <- compatible t x.typeOf asComponent <- compatible component x.typeOf if | literal ast, asArray -> expression (Expect t) ast | literal ast, asComponent -> expression (Expect component) ast | asArray -> conform (Expect t) x -- (a string or character literal takes its type from the other operand, -- `W & " and "` of Wide_Wide_Strings: RM 4.2(4), 4.5.3, D163) | literal ast, not asComponent -> do (_, problems) <- trial (expression (Expect t) ast) if null problems then expression (Expect t) ast else expression (Expect component) ast | otherwise -> conform (Expect component) x l <- side b.left l0 r <- side b.right r0 visibleOp t mkExpr s t (TBinaryNode TBinary {op = TConcat, left = l, right = r}) >>= conform expect numericKind = \case KInteger _ -> True KModular _ -> True KReal _ -> True _ -> False -- both operands of one type: from the expectation, or from the first operand that is not -- universal (RM 8.6 overload resolution, simplified for predefined operators) -- operands are first typed on their own, so that an operator applied to the wrong type -- is reported as such (B2009) rather than as a mismatch with the context operandPair _ | A.ENull <- b.left.node = do r <- expression AnyType b.right l <- expression (Expect r.typeOf) b.left pure (l, r) -- (an aggregate as the left operand takes the right one's type: `(7, 8, 9) /= X`) operandPair _ | isAggregate b.left, not (isAggregate b.right) = do r <- expression AnyType b.right l <- expression (Expect r.typeOf) b.left pure (l, r) -- (a left operand of several possible types, a call of overloaded operators or -- functions, takes the one the right operand admits: `(X mod 1) /= 'G'` with a `"mod"` -- returning Character, ACATS C67002B) -- (and so for an operator of two operands of one type: `(False or X)` of a type derived -- from Boolean) operandPair expect' | b.op `elem` [A.OpEq, A.OpNe, A.OpLt, A.OpLe, A.OpGt, A.OpGe, A.OpAnd, A.OpOr, A.OpXor, A.OpAdd, A.OpSub, A.OpMod, A.OpRem] = do ls <- shapes b.left rs <- shapes b.right let leftTypes = nub [t | Exactly t <- ls] fitting <- filterM (\t -> admitsAny t rs) leftTypes case fitting of [t] | length leftTypes > 1 -> do l <- expression (Expect t) b.left r <- expression (Expect t) b.right pure (l, r) _ -> plainPair expect' operandPair expect' = plainPair expect' plainPair expect' = do l0 <- expression AnyType b.left lUniversal <- isUniversal l0.typeOf k0 <- fullKind l0.typeOf -- the right operand takes the left one's type only if the operator applies to it let relational = b.op `elem` [A.OpEq, A.OpNe, A.OpLt, A.OpLe, A.OpGt, A.OpGe] r0 <- expression (if lUniversal || not (relational || operatorApplies b.op k0) then AnyType else Expect l0.typeOf) b.right rUniversal <- isUniversal r0.typeOf -- (an integer named number and a real literal are of different universal types: no -- predefined `=`, `+` or `<` takes one of each, RM 4.5.2, 4.5.3) when (lUniversal && rUniversal && l0.typeOf /= r0.typeOf && b.op `notElem` [A.OpMul, A.OpDiv, A.OpPow]) do reportAt TypeMismatch s ("`" <> A.binaryOpText b.op <> "` takes two values of one type, and these are an integer and a real value") "an integer and a real value" case expectOperand expect' of _ | lUniversal && not rUniversal -> (,r0) <$> conform (Expect r0.typeOf) l0 Expect t | lUniversal && rUniversal -> (,) <$> conform (Expect t) l0 <*> conform (Expect t) r0 _ -> pure (l0, r0) isAggregate x = case x.node of A.EAggregate _ -> True A.EParen y -> isAggregate y _ -> False expectOperand = \case Expect t | b.op `notElem` [A.OpEq, A.OpNe, A.OpLt, A.OpLe, A.OpGt, A.OpGe] -> Expect t _ -> AnyType staticCheck result l r = case (l.static, r.static, result.static) of (Just lv, Just rv, Nothing) -> do kind <- fullKind result.typeOf case staticBinary kind (translate b.op) lv rv of Left why | why == "division by zero" -> do skipped <- asks (.unevaluated) unless skipped (reportAt StaticValueOutOfRange s "this static expression divides by zero" "division by zero") errorExpr s _ -> pure result _ -> pure result translate = \case A.OpAnd -> TAnd A.OpAndThen -> TAndThen A.OpOr -> TOr A.OpOrElse -> TOrElse A.OpXor -> TXor A.OpEq -> TEq A.OpNe -> TNe A.OpLt -> TLt A.OpLe -> TLe A.OpGt -> TGt A.OpGe -> TGe A.OpAdd -> TAdd A.OpSub -> TSub A.OpConcat -> TConcat A.OpMul -> TMul A.OpDiv -> TDiv A.OpMod -> TMod A.OpRem -> TRem A.OpPow -> TPow visibleOp = operatorVisible s (A.binaryOpText b.op) -- | Whether a type is declared in an implicit instance (Varc's `List`, `(A, B)`, LX21). implicitInstanceType :: TypeId -> Sema Bool implicitInstanceType t = do def <- typeDef t owner <- maybe (pure Nothing) (fmap (.parent) . entity) def.decl maybe (pure False) (fmap (Text.isPrefixOf "Instance_") . fullName) owner -- | What a renaming or a generic formal's default or actual names as a subprogram: a name, -- or an operator symbol, `"+"`, the operators of that name visible here (RM 8.5.4, 12.6). denoteSubprogram :: A.Expr -> Sema (Maybe Denotation) denoteSubprogram x = case x.node of A.EString t -> do let n = "\"" <> Text.toLower t <> "\"" ds <- lookupDirect n if null ds then pure Nothing else Just <$> classify x.span n ds _ -> denote x -- | The package an expanded name of an operator names, `P."+"`, whose types' predefined -- operators it denotes (RM 4.1.3(11)). operatorPackage :: A.Expr -> Sema [DeclId] operatorPackage owner = fst <$> trial (denote owner) <&> \case Just (DPackage p) -> [p] _ -> [] -- | The predefined operators of a type declared in a package are visible only inside it or -- through a use clause (RM 8.4); B1012 otherwise, with a fix-it adding `use type`. operatorVisible :: Span -> Text -> TypeId -> Sema () operatorVisible s opText t = do def <- typeDef t owner <- maybe (pure Nothing) (fmap (.parent) . entity) def.decl st <- std case owner of Just p | p /= st.package -> do ownerEntity <- entity p case ownerEntity.kind of EPackage _ -> do inside <- insideOf p usedHere <- operatorUseVisible p t -- (Vibe's values have Python's operators wherever they are: a tuple's `==` is -- its implicit instance's, which no module uses) python <- asks (.python) -- (and so do Varc's of an implicit instance, which a Varc file cannot name in a -- use clause: a tuple's, a list's, D189) varcInstance <- (&&) <$> asks (.varc) <*> (Text.isPrefixOf "Instance_" <$> fullName p) -- (and an expanded name names the operators of its package's types, `P."="`) named <- asks (elem p . (.operatorsOf)) unless (inside || usedHere || python || varcInstance || named) do pkg <- fullName p let qualified = pkg <> "." <> def.name start <- asks (.itemStart) report (diagnostic OperatorNotVisible Semantic ("operator `" <> opText <> "` of `" <> qualified <> "` is not visible here")) { primary = Just (label s "operator not visible") , notes = [Note {text = "Ada RM 8.4: the operators of a type declared in a package are visible only inside it or through a use clause", span = Nothing}] , fixes = [Fix {span = s {start = start, end = start}, replacement = Snippet ("use type " <> qualified <> ";\n"), description = "add `use type " <> qualified <> ";`"}] } _ -> pure () _ -> pure () -- | Whether a predefined adding, multiplying or logical operator exists for a type. operatorApplies :: A.BinaryOp -> TypeKind -> Bool operatorApplies op kind = case (op, kind) of (_, KError) -> True (A.OpConcat, KArray a) -> length a.indices == 1 (A.OpConcat, _) -> False (o, KEnumeration e) -> e.isBoolean && o `elem` [A.OpAnd, A.OpOr, A.OpXor] (o, KModular _) -> o /= A.OpConcat (o, KInteger _) -> o `elem` [A.OpAdd, A.OpSub, A.OpMul, A.OpDiv, A.OpMod, A.OpRem] (o, KReal _) -> o `elem` [A.OpAdd, A.OpSub, A.OpMul, A.OpDiv] (o, KFixed _) -> o `elem` [A.OpAdd, A.OpSub] _ -> False -- | Whether a type's operators are use-visible: @use P@ or @use type P.T@ in scope. operatorUseVisible :: DeclId -> TypeId -> Sema Bool operatorUseVisible p t = do scs <- gets (.scopes) pure (any (\sc -> p `elem` sc.usedPackages || t `elem` sc.usedTypes) scs) membership :: Expect -> Span -> A.Membership -> Sema TExpr membership expect s m = do -- (Varc's `x in xs` of an array or a container: whether x is one of its elements) inContainer <- case m.choices of [A.MemberExpr x] -> containerChoice x _ -> pure Nothing case inContainer of Just x -> do let f = A.SurfaceForm {kind = A.FormContains, operands = [x, m.operand]} formResolution False s f >>= \case Just r -> let found = resolvedFormExpr s r f in expression expect (if m.negated then A.Expr {span = s, node = A.EUnary A.Unary {op = A.OpNot, operand = A.Expr {span = s, node = A.EParen found}}} else found) Nothing -> errorExpr s Nothing -> plainMembership expect s m where containerChoice x = fst <$> trial (denote x) >>= \case Just (DSubtype _) -> pure Nothing _ -> do (probe, _) <- trial (expression AnyType x) (operand, _) <- trial (expression AnyType m.operand) kind <- fullKind probe.typeOf operandKind <- fullKind operand.typeOf pure case (kind, operandKind) of (KArray _, KArray _) -> Nothing (KArray _, _) -> Just x (KRecord _, k) | not (composite k) -> Just x (KPrivate _, k) | not (composite k) -> Just x _ -> Nothing composite = \case KArray _ -> True KRecord _ -> True KPrivate _ -> True _ -> False plainMembership :: Expect -> Span -> A.Membership -> Sema TExpr plainMembership expect s m = do -- (a value of a record or limited type is tested for each choice by the type's primitive -- `=` where it has one, RM 4.5.2(28.1/4); a nonlimited array's by the predefined one) (probe, _) <- trial (expression AnyType m.operand) probeKind <- fullKind probe.typeOf own <- primitivesNamed "\"=\"" probe.typeOf limited <- isLimited probe.typeOf let record = case probeKind of KRecord _ -> True _ -> False named x = case x.node of A.ENameRef _ -> True A.ESelected _ -> True A.EParen y -> named y _ -> False values = [x | A.MemberExpr x <- m.choices] denoted <- forM values \x -> fst <$> trial (denote x) let subtypes = or [True | Just (DSubtype _) <- denoted] case values of first : rest | record || limited, not (null own), named m.operand, length values == length m.choices, not subtypes -> do -- (each part its own span, from the operand to its choice: expressions are typed -- once for each span) let equal x = A.Expr {span = Span {file = s.file, start = x.span.start, end = x.span.end + 1}, node = A.EBinary A.Binary {op = A.OpEq, left = m.operand, right = x}} anyOf = foldl (\a b -> A.Expr {span = Span {file = s.file, start = m.operand.span.start - 1, end = b.span.end}, node = A.EBinary A.Binary {op = A.OpOrElse, left = a, right = equal b}}) (equal first) rest test = if m.negated then A.Expr {span = s, node = A.EUnary A.Unary {op = A.OpNot, operand = A.Expr {span = Span {file = s.file, start = s.start, end = s.end + 2}, node = A.EParen anyOf}}} else anyOf expression expect test _ -> plainMembership' expect s m plainMembership' :: Expect -> Span -> A.Membership -> Sema TExpr plainMembership' expect s m = do st <- std -- (an operand that could be of several types is of the one the choices are of, RM -- 4.5.2(3/3): `+(1/1) in Zero | One` of a type with its own `+` and `/`) -- (and of the one every choice can be of, where more than one choice could be of several: -- `2/4 in Zero | 2/1` with a `/` of Integer to a rational type, ACATS C452004) operandShapes <- shapes m.operand let operandTypes = nub [t | Exactly t <- operandShapes] exactly ss = [t | Exactly t <- ss] choiceTypes <- forM m.choices $ \case A.MemberExpr x -> fst <$> trial (denote x) >>= \case Just (DSubtype sub) -> pure [sub.base] _ -> exactly <$> shapes x -- (a range's: the types both its bounds may have, `Item in Jan .. Mar`) A.MemberRange r -> do lows <- exactly <$> shapes r.low highs <- exactly <$> shapes r.high pure (nub [t | t <- lows, null highs || t `elem` highs] <> if null lows then highs else []) fitting <- filterM (\t -> or <$> mapM (compatible t) (concat choiceTypes)) operandTypes fittingAll <- filterM (\t -> and <$> forM (filter (not . null) choiceTypes) (fmap or . mapM (compatible t))) operandTypes -- (an operand of no type of its own, a literal, is of the one type the choices are of, -- that admits it: `'Q' in ST`, RM 4.5.2(3/3)) literalType <- case (operandTypes, nub (concat choiceTypes)) of ([], [t]) -> (\ok -> if ok then Just t else Nothing) <$> admitsAny t operandShapes _ -> pure Nothing let operandExpect = case (operandTypes, fitting, fittingAll, literalType) of (_ : _ : _, [t], _, _) -> Expect t (_ : _ : _, _, [t], _) -> Expect t ([], _, _, Just t) -> Expect t _ -> AnyType operand0 <- expression operandExpect m.operand -- (a universal operand, a literal say, is of the type of the subtype it is tested for: -- compared in that type's terms, a fixed-point type's multiples of its small) universal <- isUniversal operand0.typeOf marked <- if not universal then pure Nothing else fmap (listToMaybe . catMaybes) . forM m.choices $ \case A.MemberExpr x -> fst <$> trial (denote x) >>= \case Just (DSubtype sub) -> pure (Just sub.base) _ -> pure Nothing _ -> pure Nothing operand <- maybe (pure operand0) (\t -> conform (Expect t) operand0) marked choices <- forM m.choices \case A.MemberRange r -> TChoiceRange <$> rangeOf operand.typeOf r A.MemberExpr x -> denote x >>= \case Just (DSubtype sub) -> do -- a class-wide operand is tested for a type of its class by its tag operandKind <- fullKind operand.typeOf tagTest <- case operandKind of KClassWide root -> fullKind sub.base >>= \case KClassWide other -> (||) <$> descendsFrom other root <*> eitherInterface root other _ -> (||) <$> descendsFrom sub.base root <*> eitherInterface root sub.base _ -> pure False unless tagTest (void (conform (Expect sub.base) operand)) pure (TChoiceSubtype sub) _ -> case x.node of A.EAttribute a | A.foldedName a.designator == "range" -> TChoiceRange <$> attributeRange a _ -> TChoiceValue <$> expression (Expect operand.typeOf) x mkExpr s st.boolean (TMembershipNode TMembership {negated = m.negated, operand, choices}) >>= conform expect -- * Attributes (RM 4.1.4, K.2) -- | System.Address, when package System is part of the program. systemAddressType :: Sema (Maybe TypeId) systemAddressType = do entities <- gets (.entities) pure ( headMaybe [ ti.typeId | e <- IntMap.elems entities , e.name == "Address" , EType ti <- [e.kind] , Just p <- [e.parent] , Just pe <- [IntMap.lookup (let DeclId k = p in k) entities] , pe.name == "System" , EPackage _ <- [pe.kind] ] ) attribute :: Expect -> Span -> A.AttributeRef -> Sema TExpr attribute expect s at0 = attributeOf expect s (renamedAttribute at0) -- | Attributes that are others written another way: GNAT's `'Img`, the wide widths. (Ada -- 2022's `'Enum_Rep` and `'Enum_Val` of a subtype without a representation clause are its -- `'Pos` and `'Val`, below, where the type is known.) renamedAttribute :: A.AttributeRef -> A.AttributeRef renamedAttribute at0 = case renamedTo of Just d -> A.AttributeRef {prefix = at0.prefix, designator = A.Identifier {span = at0.designator.span, text = d}, arguments = at0.arguments} Nothing -> at0 where renamedTo = case A.foldedName at0.designator of "img" -> Just "Image" "wide_width" -> Just "Width" "wide_wide_width" -> Just "Width" _ -> Nothing -- | The declaration of a Verada.Scanning function whose first parameter is of the type of this -- name (`String`, `Wide_String`, `Wide_Wide_String`), with its parameters' subtypes: the -- driver loads the unit for a unit that names an attribute that needs it. scanningFunction :: Text -> Text -> Sema (Maybe (DeclId, [Subtype])) scanningFunction name stringType = do unit <- gets (Map.lookup "verada.scanning" . (.libraryUnits)) candidates <- maybe (pure []) (`lookupInPackage` name) unit found <- forM candidates \d -> entity d >>= \case Entity {kind = ESubprogram info} -> do formals <- forM info.parameters \f -> entity f <&> \case Entity {kind = EObject o} -> Just o.subtype _ -> Nothing case sequence formals of Just subs@(first : _) -> do tn <- typeName first.base pure [(d, subs) | Text.toCaseFold tn == Text.toCaseFold stringType] _ -> pure [] _ -> pure [] pure (listToMaybe (concat found)) -- | `T'Value (S)`, `T'Wide_Value (S)`, `T'Wide_Wide_Value (S)` and `T'Valid_Value (S)`: for -- an integer, modular, enumeration or character subtype, a call of Verada.Scanning's value -- function (or its query, for `'Valid_Value`) for the string and the subtype's bounds, so -- that proof shows the string is a value of the subtype. A value of an integer type is -- converted from Verada.Scanning's integer, of an enumeration type it is the one at the -- position read. scannedValue :: Expect -> Span -> A.AttributeRef -> Text -> Sema TExpr scannedValue expect s at d = do st <- std sub <- subtypeMarkOf at.prefix kind <- fullKind sub.base case at.arguments of [x] | kind /= KError -> do -- (the string's type: the attribute's, or for `'Valid_Value` whichever the operand has) let stringTypes = case d of "wide_value" -> ["Wide_String"] "wide_wide_value" -> ["Wide_Wide_String"] "value" -> ["String"] _ -> ["String", "Wide_String", "Wide_Wide_String"] query = d == "valid_value" attr pfx n args = A.Expr {span = s, node = A.EAttribute A.AttributeRef {prefix = pfx, designator = A.Identifier {span = s, text = n}, arguments = args}} -- (`'Value`'s must be in the base range of T's type, RM 3.5(55/3): the result is the -- base type's, which the context then checks against its subtype, ACATS C34002A, -- C35504B; `'Valid_Value` asks of the subtype) base = if query then at.prefix else attr at.prefix "Base" [] bound n = case kind of KEnumeration _ -> attr at.prefix "Pos" [attr base n []] _ -> attr base n [] -- (the value function's kind, and its flag: a modular type's, or a single precision -- float's) plan = case kind of KInteger _ -> Just ("Integer", Just False) KModular _ -> Just ("Integer", Just True) KEnumeration e | e.isCharacter -> Just ("Character", Nothing) KEnumeration _ -> Just ("Enumeration", Nothing) KReal r | not r.universal -> Just ("Real", Just (maybe False (<= 6) r.digits)) KFixed _ -> Just ("Fixed", Nothing) _ -> Nothing case plan of Nothing -> do tn <- typeName sub.base reportAt WrongKindOfEntity at.prefix.span ("`'" <> at.designator.text <> "` reads a value of a scalar type, and `" <> tn <> "` is not one") "not a scalar type" errorExpr s Just (what, flag) -> do let fn = if query then "Is_" <> what else what <> "_Value" -- (the first of the string types the operand takes without errors) tried <- forM stringTypes \tn -> scanningFunction fn tn >>= \case Nothing -> pure Nothing Just (callee, formals) -> do (_, problems) <- trial (expression (Expect (firstBase formals)) x) pure (if null problems then Just (callee, formals) else Nothing) chosen <- case catMaybes tried of c : _ -> pure (Just c) -- (none without errors: the first, whose check reports them) [] -> scanningFunction fn (fromMaybe "String" (listToMaybe stringTypes)) case chosen of Nothing -> do reportAt UnknownUnit s ("`'" <> at.designator.text <> "` needs the library unit Verada.Scanning, which was not loaded") "Verada.Scanning not loaded" errorExpr s Just (callee, formals) -> do str <- expression (Expect (firstBase formals)) x let formalAt i = case drop i formals of f : _ -> f [] -> unconstrained st.errorType converted i e = mkExpr s (formalAt i).base (TConversionNode TConversion {target = formalAt i, operand = e, qualified = False}) let count i n = mkExpr s (formalAt i).base (TLiteral (StaticInteger n)) (first, last') <- case kind of -- (a fixed-point type's bounds as counts of its small: static, and when the -- subtype's are not, the counts Integer holds, its range then checked by the -- conversion to it) KFixed fx -> do let (lo, hi) = case sub.range of Just r | Just (StaticReal a) <- r.low.static, Just (StaticReal b) <- r.high.static -> (ceiling (a / fx.small), floor (b / fx.small)) _ -> (negate (2 ^ (63 :: Int)), 2 ^ (63 :: Int) - 1) (,) <$> count (boundsAt what 0) lo <*> count (boundsAt what 1) hi _ -> (,) <$> (expression AnyType (bound "First") >>= converted (boundsAt what 0)) <*> (expression AnyType (bound "Last") >>= converted (boundsAt what 1)) -- (and its small, as the numerator and denominator of a fraction) smallParts <- case kind of KFixed fx -> sequence [count 3 (numerator fx.small), count 4 (denominator fx.small)] _ -> pure [] tables <- case kind of KEnumeration e | what == "Enumeration" -> do let images = map enumerationImage e.literals ends = drop 1 (scanl (+) 0 (map (toInteger . Text.length) images)) names = A.Expr {span = s, node = A.EString (Text.concat images)} endsAggregate = A.Expr {span = s, node = A.EAggregate A.Aggregate {bracket = True, contents = A.PlainAggregate (A.Associations [A.PositionalAssoc A.Expr {span = s, node = A.EInteger n} | n <- ends])}} n <- expression (Expect (formalAt 1).base) names t <- expression (Expect (formalAt 2).base) endsAggregate pure [n, t] _ -> pure [] flags <- forM (maybe [] (: []) flag) \b -> mkExpr s st.boolean (TLiteral (fromBool b)) call <- mkExpr s (if query then st.boolean else st.universalInteger) (TCallNode TCall {callee, arguments = [str] <> tables <> [first, last'] <> smallParts <> flags}) resultType <- if query then pure st.boolean else do callee' <- entity callee pure case callee'.kind of ESubprogram info | Just r <- info.result -> r.base _ -> st.errorType let typedCall = call {typeOf = resultType} if | query -> conform expect typedCall -- (a fixed-point value: the count of smalls times the small, then in the subtype) | KFixed fx <- kind -> do small <- mkExpr s sub.base (TLiteral (StaticReal fx.small)) scaled <- mkExpr s sub.base (TBinaryNode TBinary {op = TMul, left = small, right = typedCall}) mkExpr s sub.base (TConversionNode TConversion {target = sub, operand = scaled, qualified = False}) >>= conform expect -- (of the base type: the context checks the subtype, RM 3.5(55/3)) | what `elem` ["Integer", "Real"] -> mkExpr s sub.base (TConversionNode TConversion {target = unconstrained sub.base, operand = typedCall, qualified = False}) >>= conform expect | otherwise -> mkExpr s sub.base (TAttributeNode TAttribute {prefix = OfSubtype (unconstrained sub.base), attribute = AVal, dimension = 1, arguments = [typedCall]}) >>= conform expect [_] -> errorExpr s _ -> do reportAt MisplacedAttribute s ("`'" <> at.designator.text <> "` takes one argument, the string") "one argument" errorExpr s where firstBase formals = case formals of f : _ -> f.base [] -> TypeId 0 -- (the positions of First and Last among the value function's parameters) boundsAt what k = if what == "Enumeration" then 3 + k else 1 + k enumerationImage l = if "'" `Text.isPrefixOf` l then l else Text.toUpper l -- | `X'Wide_Image` and `X'Wide_Wide_Image` (and of a subtype, with the value): the image -- widened by Verada.Scanning's `Wide` or `Widened`. widenedImage :: Expect -> Span -> A.AttributeRef -> Bool -> Sema TExpr widenedImage expect s at wide = do let image = A.Expr {span = s, node = A.EAttribute A.AttributeRef {prefix = at.prefix, designator = A.Identifier {span = at.designator.span, text = "Image"}, arguments = at.arguments}} img <- expression AnyType image scanningFunction (if wide then "Wide" else "Widened") "String" >>= \case Nothing -> do reportAt UnknownUnit s ("`'" <> at.designator.text <> "` needs the library unit Verada.Scanning, which was not loaded") "Verada.Scanning not loaded" errorExpr s Just (callee, _) -> do result <- entity callee <&> \case Entity {kind = ESubprogram info} | Just r <- info.result -> Just r.base _ -> Nothing case result of Just r -> mkExpr s r (TCallNode TCall {callee, arguments = [img]}) >>= conform expect Nothing -> errorExpr s attributeOf :: Expect -> Span -> A.AttributeRef -> Sema TExpr attributeOf expect s at = do let designatorSpan = at.designator.span attrOf pfx d args = A.Expr {span = s, node = A.EAttribute A.AttributeRef {prefix = pfx, designator = A.Identifier {span = designatorSpan, text = d}, arguments = args}} case A.foldedName at.designator of -- `T'Mod (X)`: X reduced modulo T's modulus, a value of T (RM 3.5.4(16.1/2)) -- (where the modulus is beyond X's type, X mod T'Modulus is X itself or the modulus plus -- X, so it is written without the modulus as a value of X's type: `T'Mod (Initiator)` of -- an Integer for a 64-bit T) "mod" | [x] <- at.arguments -> do ((value, modulus), _) <- trial ((,) <$> expression AnyType x <*> expression AnyType (attrOf at.prefix "Modulus" [])) beyond <- case modulus.static of Just (StaticInteger m) -> fullKind value.typeOf <&> \case KInteger it -> not it.universal && m > it.baseLast KModular xm -> m >= xm.modulus _ -> False _ -> pure False let at' = x.span ex n = A.Expr {span = at', node = n} converted v = ex (A.EApply A.Apply {prefix = at.prefix, arguments = [A.Argument {span = at', formal = Nothing, value = A.ArgExpr v, reference = Nothing}], bracketed = Nothing}) operation op l r = ex (A.EBinary A.Binary {op, left = l, right = r}) paren = ex . A.EParen expression expect $ if beyond then ex (A.EParen (ex (A.EIf A.IfExpr { condition = operation A.OpGe (paren x) (ex (A.EInteger 0)) , thenValue = converted (paren x) , elsifs = [] , elseValue = Just (operation A.OpSub (attrOf (attrOf at.prefix "Base" []) "Last" []) (converted (ex (A.EUnary A.Unary {op = A.OpMinus, operand = paren (operation A.OpAdd (paren x) (ex (A.EInteger 1)))})))) }))) else converted (operation A.OpMod x (attrOf at.prefix "Modulus" [])) -- `S'First_Valid`, `S'Last_Valid` (RM 3.5.5(7.2/3)): of a subtype without a static -- predicate, its bounds d | d `elem` ["first_valid", "last_valid"], null at.arguments -> do sub <- subtypeMarkOf at.prefix unless (null sub.predicates) (reportAt WrongKindOfEntity s ("`'" <> at.designator.text <> "` of a subtype with a predicate is the first value that satisfies it: write it out") "a predicate") expression expect (attrOf at.prefix (if d == "first_valid" then "First" else "Last") []) -- `T'Value (S)` and its wide forms (RM 3.5): a call of Verada.Scanning's value function, -- whose precondition proof discharges; `T'Valid_Value (S)` (GNAT's, for every scalar -- type in Verada): its query (D197) d | d `elem` ["value", "wide_value", "wide_wide_value", "valid_value"] -> scannedValue expect s at d -- `X'Wide_Image`, `X'Wide_Wide_Image`: the image, widened character for character d | d `elem` ["wide_image", "wide_wide_image"] -> widenedImage expect s at (d == "wide_image") -- `X'Constrained` (RM 3.7.2(3)): whether X's discriminants are fixed, which Verada knows "constrained" | null at.arguments -> do x <- expression AnyType at.prefix -- (whether the type's discriminants have defaults is the type's, whatever view of it -- is visible here: a private type's full view says) let anyView t = typeDef t >>= \d -> case d.kind of KPrivate p | Just full <- p.fullView -> anyView full k -> pure k kind <- anyView x.typeOf sub <- subtypeOfExpr x variable <- isVariable x let defaulted = case kind of KRecord r -> not (null r.discriminants) && all (isJust . (.initial)) (discriminantComponents r) _ -> False constrained = not defaulted || not (null sub.discriminantValues) || not variable -- (of an `out` or `in out` parameter that could be either: its actual decides, whose -- caller passes the flag, D199) byActual <- case x.node of TObject d -> entity d <&> \e -> case e.kind of EObject info -> info.mode `elem` [Just ModeOut, Just ModeInOut] _ -> False _ -> pure False st' <- std -- (a variable that could be either: Lower decides, from its subtype or its caller's -- flag, D199) if (byActual || variable) && not constrained then mkExpr s st'.boolean (TAttributeNode TAttribute {prefix = OfObject x, attribute = AConstrained, dimension = 1, arguments = []}) >>= conform expect else expression expect A.Expr {span = s, node = A.ENameRef A.Identifier {span = s, text = if constrained then "True" else "False"}} -- `X'Valid_Scalars` (GNAT): every scalar part of X is valid "valid_scalars" | null at.arguments -> do x <- expression AnyType at.prefix kind <- fullKind x.typeOf st <- std let true' = A.Expr {span = s, node = A.ENameRef A.Identifier {span = s, text = "True"}} conj = foldr (\a b -> A.Expr {span = s, node = A.EBinary A.Binary {op = A.OpAndThen, left = a, right = b}}) true' case kind of KRecord r -> expression (Expect st.boolean) (conj [attrOf A.Expr {span = s, node = A.ESelected A.Selected {prefix = at.prefix, selector = A.SelectIdentifier A.Identifier {span = s, text = c.name}}} "Valid_Scalars" [] | c <- r.components]) KArray _ -> let e' = A.Identifier {span = s, text = "Valid_Scalars'Element"} in expression (Expect st.boolean) A.Expr {span = s, node = A.EQuantified A.Quantified {quantifier = A.ForAll, iterator = A.Iterator {parameter = e', subtype = Nothing, reverse = False, domain = A.OfContainer at.prefix, filter = Nothing, whileCondition = Nothing, alongside = []}, predicate = attrOf A.Expr {span = s, node = A.ENameRef e'} "Valid_Scalars" []}} _ -> expression expect (attrOf at.prefix "Valid" []) "old" -> do post <- asks (.inPostcondition) if post then do -- (`A'Old (I)`: a component of the value on entry, as `F'Result (I)`; `'Old` takes no -- arguments of its own, RM 6.1.1) inner <- expression (if null at.arguments then expect else AnyType) at.prefix -- a copy of a value that owns access values would alias it: only a function -- call (a fresh value) may be the prefix (SPARK RM 3.10(13)) owning <- hasOwningPart inner.typeOf let fresh = case inner.node of TCallNode _ -> True _ -> False when (owning && not fresh) do tn <- typeName inner.typeOf reportAt AliasingOld at.prefix.span ("`'Old` would copy a value of `" <> tn <> "`, which owns access values") "a copy would alias it" -- the prefix is evaluated on entry: it cannot use what the postcondition binds -- (a quantified variable), `'Result` or another `'Old` (RM 6.1.1(24)) bad <- oldPrefixProblem inner forM_ bad \(sp, what) -> reportAt MisplacedAttribute sp ("the prefix of `'Old` cannot use " <> what) "known only at the end" -- in a part that might not be evaluated, the prefix must name an object, or every -- condition deciding whether it is evaluated must be known on entry (RM 6.1.1(27)) guards <- asks (.conditions) known <- and <$> mapM (maybe (pure False) knownOnEntry) guards when (isNothing bad && not (null guards) && not known && not (staticallyNamesObject inner)) do reportAt ConditionalOld at.prefix.span "`'Old` of an expression in a part of the postcondition that might not be evaluated" "might not be evaluated" old <- mkExpr s inner.typeOf (TOld inner) if null at.arguments then pure old else indexWith expect s at.designator.span old [A.Argument {span = x.span, formal = Nothing, value = A.ArgExpr x, reference = Nothing} | x <- at.arguments] else misplaced "`'Old` is only allowed in a postcondition" "result" -> asks (.subprogram) >>= \case Just f -> do post <- asks (.inPostcondition) fe <- entity f case fe.kind of -- `F'Result (I)`: a component of an array result ESubprogram info | post, Just r <- info.result, not (null at.arguments) -> do result <- mkExpr s r.base (TResult f) indexWith expect s at.designator.span result [A.Argument {span = x.span, formal = Nothing, value = A.ArgExpr x, reference = Nothing} | x <- at.arguments] ESubprogram info | post, Just r <- info.result -> mkExpr s r.base (TResult f) >>= conform expect _ -> misplaced "`'Result` is only allowed in the postcondition of a function" Nothing -> misplaced "`'Result` is only allowed in the postcondition of a function" "reduce" -> reduction expect s at -- (Verada's extension: each position's reduction of the elements up to it, as Ada 2022 -- writes it) -- (Varc's `for x in a` resolved first, as an aggregate's is) "scan" -> do prefix <- case at.prefix.node of A.EAggregate agg | A.PlainAggregate (A.Associations [assoc@(A.IteratedAssocNode _)]) <- agg.contents -> do resolved <- resolvedDomain assoc pure A.Expr {span = at.prefix.span, node = A.EAggregate A.Aggregate {bracket = agg.bracket, contents = A.PlainAggregate (A.Associations [resolved])}} _ -> pure at.prefix case at.arguments of [reducer, initial] | Just x <- scanExpansion s prefix reducer initial -> expression expect x [_, _] -> do notYetSupported at.prefix.span "a scan of a value sequence with a `while`, sources in step, or a filter in reverse order" T35 errorExpr s _ -> do reportAt MisplacedAttribute s "`'Scan` takes a reducer and an initial value, as `'Reduce` does" "two arguments" errorExpr s -- (D144: a float sum with a running correction, AP21: in eight lanes; of an integer -- type, the plain sum) d | d `elem` ["compensated_sum", "lane_sum"] -> do let plus = A.Expr {span = s, node = A.EString "+"} sumFrom zero = reduction expect s A.AttributeRef {prefix = at.prefix, designator = at.designator, arguments = [plus, A.Expr {span = s, node = zero}]} -- (from 0.0 when the values are floats, else from 0) (_, asFloat) <- trial (sumFrom (A.EReal 0)) x <- sumFrom (if null asFloat then A.EReal 0 else A.EInteger 0) floating <- fullKind x.typeOf >>= \case KReal _ -> pure True _ -> pure False unless floating (modify' \st -> st {plainSums = Set.insert s st.plainSums}) pure case x.node of TReduceNode r | floating -> TExpr {span = x.span, typeOf = x.typeOf, static = x.static, node = TReduceNode TReduce {label = r.label, accumulator = r.accumulator, initial = r.initial, scheme = r.scheme, step = r.step, summation = if d == "lane_sum" then LaneSum else CompensatedSum}} _ -> x -- the longest image of the values of a scalar subtype (RM 3.5(39)), static "width" -> do prefix <- attributePrefix at.prefix st <- std case prefix of OfSubtype sub -> do bounds <- staticBounds sub kind <- fullKind sub.base let width = case (bounds, kind) of (Just (lo, hi), _) | hi < lo -> 0 (Just (lo, hi), KEnumeration e) -- (Character's images: `'c'`, or a name for a character that is not -- graphic, `RESERVED_128` the longest; a wider type's above 255 in hex) | e.isCharacter, e.characters == 256 -> foldr max 0 [Text.length (characterImage (fromInteger k)) | k <- [max 0 lo .. min 255 hi]] | e.isCharacter -> foldr max 0 ([3 | lo < 256] <> [8 | hi > 255, lo < 65536] <> [10 | hi > 65535, lo < 16777216] <> [12 | hi > 16777215]) | otherwise -> foldr max 0 [Text.length l | l <- take (fromInteger (hi - lo + 1)) (drop (fromInteger lo) e.literals)] (Just (lo, hi), _) -> max (imageLength lo) (imageLength hi) -- a sign or a space, a digit, the point, Digits - 1 more (at least one), `E`, -- the exponent's sign and its digits: two for single precision (to 38), -- three for double (to 308), as the run time writes them (RM 3.5(39.4)) _ | Just (lo, hi) <- realBounds, hi < lo -> 0 (_, KReal r) -> let d = fromMaybe 15 r.digits in 5 + fromInteger (max 1 (d - 1)) + (if d <= 6 then 2 else 3) -- a sign or a space, the integer part of the largest magnitude, the point -- and Aft digits (RM 3.5(39.4), 3.5.10(5)) (_, KFixed fx) | Just (lo, hi) <- realBounds -> let aft = head' [n | n <- [1 .. 30 :: Integer], fx.delta * 10 ^ n >= 1] scale = 10 ^ aft :: Integer integral = roundHalfAway (max (abs lo) (abs hi) * fromInteger scale) `div` scale in 2 + length (show integral) + fromInteger aft _ -> 0 imageLength v = length (show (abs v)) + 1 realBounds = case sub.range of Just r | Just (StaticReal lo) <- r.low.static, Just (StaticReal hi) <- r.high.static -> Just (lo, hi) _ -> Nothing head' = fromMaybe 30 . listToMaybe discrete = \case KInteger _ -> True KModular _ -> True KEnumeration _ -> True _ -> False case (bounds, kind) of -- a discrete subtype whose bounds are known only at run time: computed from them (Nothing, k) | discrete k, isJust sub.range -> mkExpr s st.universalInteger (TAttributeNode TAttribute {prefix, attribute = AWidth, dimension = 1, arguments = []}) >>= conform expect _ -> mkExpr s st.universalInteger (TLiteral (StaticInteger (toInteger width))) >>= \x -> conform expect x {static = Just (StaticInteger (toInteger width))} _ -> misplaced "`'Width` applies to a scalar subtype" "loop_entry" -> do loops <- asks (.loops) target <- case at.arguments of [] -> pure ((.label) <$> headMaybe loops) [n] -> denote n >>= \case Just (DLabel d) | d `elem` map (.label) loops -> pure (Just d) _ -> Nothing <$ reportAt MisplacedAttribute n.span "`'Loop_Entry (L)` names an enclosing loop" "not an enclosing loop" _ -> pure Nothing case target of Just loopLabel -> do inner <- expression expect at.prefix mkExpr s inner.typeOf (TLoopEntry LoopEntry {label = loopLabel, value = inner}) Nothing -> misplaced "`'Loop_Entry` is only allowed inside a loop" -- `T'Small`, `T'Delta` and `T'Aft` of a fixed-point type: static; and GNAT's -- `T'Small_Numerator` and `T'Small_Denominator`, the small as a fraction in lowest terms -- (which a generic over fixed-point types computes exactly with, Text_IO's Fixed_IO) name | name `elem` ["small", "delta", "aft", "small_numerator", "small_denominator"] -> do sub <- subtypeMarkOf at.prefix st <- std fullKind sub.base >>= \case KFixed fx -> case name of "small" -> mkExpr s st.universalReal (TLiteral (StaticReal fx.small)) >>= conform expect "delta" -> mkExpr s st.universalReal (TLiteral (StaticReal fx.delta)) >>= conform expect "small_numerator" -> mkExpr s st.universalInteger (TLiteral (StaticInteger (numerator fx.small))) >>= conform expect "small_denominator" -> mkExpr s st.universalInteger (TLiteral (StaticInteger (denominator fx.small))) >>= conform expect _ -> mkExpr s st.universalInteger (TLiteral (StaticInteger (fixedAft fx.delta))) >>= conform expect _ -> do reportAt WrongKindOfEntity s ("`'" <> at.designator.text <> "` applies to fixed-point types") "not a fixed-point type" errorExpr s -- `T'Fore` of a fixed-point subtype (RM 3.5.10(4)): the characters before the point of -- the widest value's image, a sign or space among them, at least two; static of a static -- subtype "fore" -> do sub <- subtypeMarkOf at.prefix st <- std kind <- fullKind sub.base case (kind, sub.range) of (KFixed _, Just TRange {low = TExpr {static = Just (StaticReal lo)}, high = TExpr {static = Just (StaticReal hi)}}) -> let widest = floor (max (abs lo) (abs hi)) :: Integer in mkExpr s st.universalInteger (TLiteral (StaticInteger (max 2 (toInteger (length (show widest)) + 1)))) >>= conform expect (KFixed _, _) -> do reportAt WrongKindOfEntity s "`'Fore` here applies to a fixed-point subtype with static bounds" "bounds known only at run time" errorExpr s _ -> do reportAt WrongKindOfEntity s "`'Fore` applies to fixed-point types" "not a fixed-point type" errorExpr s -- `T'Digits` of a floating-point or decimal fixed-point type (RM 3.5.8, 3.5.10): static "digits" -> do sub <- subtypeMarkOf at.prefix st <- std fullKind sub.base >>= \case KReal r | Just d <- r.digits -> mkExpr s st.universalInteger (TLiteral (StaticInteger d)) >>= conform expect KFixed fx | Just d <- fx.decimalDigits -> mkExpr s st.universalInteger (TLiteral (StaticInteger (fromMaybe d sub.digits))) >>= conform expect _ -> do reportAt WrongKindOfEntity s "`'Digits` applies to floating-point and decimal fixed-point types" "not a floating-point or decimal type" errorExpr s -- the static attributes of a floating-point type (RM A.5.3, D192): its machine numbers -- are IEEE binary32 up to 6 digits, binary64 beyond (as Lower makes them), its model -- numbers the normal ones among them (as GNAT has them) constantName | Just which <- lookup constantName floatConstants -> do sub <- subtypeMarkOf at.prefix st <- std fullKind sub.base >>= \case KReal r | not r.universal -> do let single = fromMaybe 15 r.digits <= 6 (mantissa, emax, emin) = if single then (24, 128, -125) else (53, 1024, -1021) :: (Integer, Integer, Integer) largest = (2 - 2 ^^ (1 - mantissa)) * 2 ^^ (emax - 1) :: Rational asInt v = mkExpr s st.universalInteger (TLiteral (StaticInteger v)) >>= conform expect asReal v = mkExpr s st.universalReal (TLiteral (StaticReal v)) >>= conform expect asBool b = mkExpr s st.boolean (TLiteral (StaticEnum (if b then 1 else 0))) >>= conform expect case which of "machine_radix" -> asInt 2 "machine_mantissa" -> asInt mantissa "machine_emax" -> asInt emax "machine_emin" -> asInt emin "model_mantissa" -> asInt mantissa "model_emin" -> asInt emin "safe_emax" -> asInt emax "model_epsilon" -> asReal (2 ^^ (1 - mantissa)) "model_small" -> asReal (2 ^^ (emin - 1)) "safe_first" -> asReal (negate largest) "safe_last" -> asReal largest "denorm" -> asBool True "signed_zeros" -> asBool True "machine_rounds" -> asBool True _ -> asBool False _ -> do reportAt WrongKindOfEntity s ("`'" <> at.designator.text <> "` applies to floating-point types") "not a floating-point type" errorExpr s -- `T'Scale` of a decimal type (RM 3.5.10(11)): N where its delta is 10 ** (-N), static "scale" -> do sub <- subtypeMarkOf at.prefix st <- std fullKind sub.base >>= \case KFixed fx | isJust fx.decimalDigits -> mkExpr s st.universalInteger (TLiteral (StaticInteger (decimalScale fx.delta))) >>= conform expect _ -> do reportAt WrongKindOfEntity s "`'Scale` applies to decimal fixed-point types" "not a decimal type" errorExpr s -- `T'Round (X)` of a decimal type (RM 3.5.10(12)): X, of any real type, rounded to the -- nearest value of T, halves away from zero (the conversion truncates toward zero, so a -- half of T's delta is added to the magnitude first) "round" -> do sub <- subtypeMarkOf at.prefix st <- std fullKind sub.base >>= \case KFixed fx | isJust fx.decimalDigits -> case at.arguments of [arg] -> do -- (a product of decimal values is universal_fixed, RM 4.5.5(18): typed exactly, -- in a decimal type of the product's delta and digits, then rounded) exact <- exactProductType arg x <- expression (maybe AnyType Expect exact) arg real <- fullKind x.typeOf <&> \case KReal _ -> True KFixed _ -> True KError -> True _ -> False universal <- isUniversal x.typeOf case x.static of _ | not real -> do reportAt TypeMismatch arg.span "`'Round` takes a value of a real type" "not a real value" errorExpr s Just (StaticReal v) | universal -> mkExpr s sub.base (TLiteral (StaticReal (fromInteger (roundHalfAway (v / fx.delta)) * fx.delta))) >>= conform expect _ -> do let lit v = TExpr {span = arg.span, typeOf = x.typeOf, static = Just (StaticReal v), node = TLiteral (StaticReal v)} shifted op r = TExpr {span = arg.span, typeOf = x.typeOf, static = Nothing, node = TBinaryNode TBinary {op, left = x, right = r}} converted v = TExpr {span = s, typeOf = sub.base, static = Nothing, node = TConversionNode TConversion {target = sub, operand = v, qualified = False}} nonNegative = TExpr {span = arg.span, typeOf = st.boolean, static = Nothing, node = TBinaryNode TBinary {op = TGe, left = x, right = lit 0}} mkExpr s sub.base (TIfNode TIfExpr {branches = [TBranch {condition = nonNegative, value = converted (shifted TAdd (lit (fx.delta / 2)))}], elseValue = Just (converted (shifted TSub (lit (fx.delta / 2))))}) >>= conform expect _ -> do reportAt WrongArguments s "`'Round` takes one argument, the value to round" "not one argument" errorExpr s _ -> do reportAt WrongKindOfEntity s "`'Round` applies to decimal fixed-point types" "not a decimal type" errorExpr s "range" -> do reportAt MisplacedAttribute s "`'Range` denotes a range and is only allowed where a range is expected" "use `'First` and `'Last` here" errorExpr s name | Just attr <- lookup name supported -> do prefix <- attributePrefix at.prefix typed attr prefix -- `X'Access`: an observer or a borrower of an object (SPARK RM 3.10), of the anonymous -- access type its context gives "access" -> case expect of Expect t -> denote at.prefix >>= \case Just (DOverloaded ds) -> subprogramAccess s t ds _ -> do object <- expression AnyType at.prefix kind <- fullKind t def <- typeDef t case kind of KAccess a | isNothing def.decl, a.designated.base == object.typeOf -> do writable <- isVariable object unless a.toConstant (markWritten object) unless (a.toConstant || writable) do reportAt NotAVariable at.prefix.span "only a variable can be borrowed" "not a variable" pure TExpr {span = s, typeOf = t, static = Nothing, node = TBorrowNode TBorrow {object, observe = a.toConstant}} -- a named general access type (SPARK RM 3.10, G6): the value designates an aliased -- object named directly, which it takes for good (the object is moved to it, and is -- never used again but through it); the object lives at least as long as the type KAccess a | a.general, isJust def.decl, a.designated.base == object.typeOf -> do aliased <- gets (.aliasedObjects) levels <- gets (.accessLevels) case object.node of TObject d | Just objectLevel <- Map.lookup d aliased -> do writable <- isVariable object unless (a.toConstant || writable) do reportAt NotAVariable at.prefix.span "only a variable can be designated by an access-to-variable value" "not a variable" forM_ (Map.lookup t levels) \typeLevel -> when (objectLevel > typeLevel) do tn <- typeName t reportAt GeneralAccessOwnership at.prefix.span ("this object is declared deeper than `" <> tn <> "`, so a value of it could outlive the object") "would dangle" unless a.toConstant (markWritten object) pure TExpr {span = s, typeOf = t, static = Nothing, node = TBorrowNode TBorrow {object, observe = a.toConstant}} TObject _ -> do reportAt GeneralAccessOwnership at.prefix.span "`'Access` of a general access type designates an object declared `aliased`" "not declared aliased" errorExpr s _ -> do reportAt GeneralAccessOwnership at.prefix.span "`'Access` of a general access type designates a whole object named directly (a part of one, or what an access value designates, would alias its owner)" "not an object's name" errorExpr s KError -> errorExpr s _ -> do reportAt TypeMismatch s "`'Access` gives an observer or a borrower: an object of an anonymous access type to the prefix's type" "not such an object" errorExpr s AnyType -> do reportAt TypeMismatch s "the type of `'Access` comes from its context, which gives none here" "type not known" errorExpr s name | name `elem` ["unchecked_access", "unrestricted_access"] -> do reportExcluded s ("`'" <> at.designator.text <> "` is not in Verada: it escapes ownership") uncheckedAccessReplacement errorExpr s _ | Just (what, r) <- excludedAttribute at.designator.text -> do reportExcluded s ("`'" <> at.designator.text <> "` (" <> what <> ") is not in Verada") r errorExpr s -- `T'Class (X)`: a conversion to the class-wide type "class" | [x] <- at.arguments -> do root <- subtypeMarkOf at.prefix target <- tagInfoOf root.base >>= \case Just ti -> pure (unconstrained ti.classWide) Nothing -> pure root conversion expect s target [A.Argument {span = x.span, formal = Nothing, value = A.ArgExpr x, reference = Nothing}] -- the address of an object, a System.Address (D107) "address" -> do prefix <- attributePrefix at.prefix systemAddress <- systemAddressType case (prefix, systemAddress) of (OfObject x, Just t) | TObject _ <- x.node -> mkExpr s t (TAttributeNode TAttribute {prefix, attribute = AAddress, dimension = 1, arguments = []}) >>= conform expect (OfObject x, Just _) -> do reportAt WrongKindOfEntity x.span "`'Address` here applies to an object named directly" "not an object's name" errorExpr s (_, Nothing) -> do reportAt WrongKindOfEntity s "`'Address` gives a System.Address: name System in a `with` clause" "System is not known here" errorExpr s _ -> do reportAt WrongKindOfEntity s "`'Address` applies to an object" "not an object" errorExpr s "class" -> do reportAt WrongKindOfEntity s "`'Class` applies to a tagged type, not to an object" "an object" errorExpr s _ -> do let suggestion = closest at.designator.text (map (titleCase . fst) supported <> ["Old", "Result", "Range"]) report (diagnostic UnknownAttribute Semantic ("unknown attribute `'" <> at.designator.text <> "`")) { primary = Just (label at.designator.span (maybe "not an attribute Verada knows" (\c -> "did you mean `'" <> c <> "`?") suggestion)) , fixes = [Fix {span = at.designator.span, replacement = Verbatim c, description = "write `'" <> c <> "`"} | Just c <- [suggestion]] } errorExpr s where misplaced why = do reportAt MisplacedAttribute s why "not allowed here" errorExpr s -- (a static discrete value's position, and the value of a type at a position) position = \case StaticInteger n -> Just n StaticEnum p -> Just (toInteger p) _ -> Nothing valueAt kind n = case kind of KEnumeration en | n >= 0, n < toInteger (length en.literals) || en.isCharacter -> Just (StaticEnum (fromInteger n)) KEnumeration _ -> Nothing KInteger _ -> Just (StaticInteger n) KModular _ -> Just (StaticInteger n) _ -> Nothing supported = [ ("first", AFirst) , ("last", ALast) , ("length", ALength) , ("pos", APos) , ("val", AVal) , ("succ", ASucc) , ("pred", APred) , ("image", AImage) , ("min", AMin) , ("max", AMax) , ("modulus", AModulus) , ("size", ASize) , ("valid", AValid) , ("initialized", AInitialized) , ("floor", AFloor) , ("ceiling", ACeiling) , ("rounding", ARounding) , ("truncation", ATruncation) , ("copy_sign", ACopySign) , ("adjacent", AAdjacent) , ("machine", AMachine) , ("model", AModel) , ("unbiased_rounding", AUnbiasedRounding) , ("machine_rounding", AMachineRounding) , ("scaling", AScaling) , ("exponent", AExponent) , ("fraction", AFraction) , ("compose", ACompose) , ("leading_part", ALeadingPart) , ("remainder", ARemainder) , ("object_size", AObjectSize) , ("alignment", AAlignment) , ("component_size", AComponentSize) , ("position", APosition) , ("first_bit", AFirstBit) , ("last_bit", ALastBit) , ("max_size_in_storage_elements", AMaxSizeInStorageElements) , ("enum_rep", AEnumRep) , ("enum_val", AEnumVal) ] titleCase t = Text.toUpper (Text.take 1 t) <> Text.drop 1 t hasCodes = \case KEnumeration en -> isJust en.codes _ -> False floatConstants = [(n, n) | n <- ["machine_radix", "machine_mantissa", "machine_emax", "machine_emin", "model_mantissa", "model_emin", "safe_emax", "model_epsilon", "model_small", "safe_first", "safe_last", "denorm", "signed_zeros", "machine_rounds", "machine_overflows"]] typed attr prefix = do st <- std let prefixType = case prefix of OfSubtype sub -> sub.base OfObject e -> e.typeOf kind <- fullKind prefixType let scalarPrefix = case kind of KArray _ -> False KRecord _ -> False _ -> True withArgs n f = if length at.arguments == n then f else wrongArity n node args = TAttributeNode TAttribute {prefix, attribute = attr, dimension = 1, arguments = args} nodeIn dim args = TAttributeNode TAttribute {prefix, attribute = attr, dimension = fromInteger dim, arguments = args} -- (a subtype with a bound known only at run time is not static, nor its values) staticPrefix x = case prefix of OfSubtype sub | maybe True (\r -> isJust r.low.static && isJust r.high.static) sub.range -> x _ -> Nothing case attr of _ | kind == KError -> errorExpr s AFirst -> bound prefix kind prefixType node nodeIn ALast -> bound prefix kind prefixType node nodeIn ALength -> case kind of KArray a -> dimensionArg (length a.indices) >>= \case Just dim -> mkExpr s st.universalInteger (nodeIn dim []) >>= conform expect Nothing -> errorExpr s _ -> notArray -- (of static operands and a static subtype, static values: RM 4.9(8)) APos | scalarPrefix -> withArgs 1 do v <- expression (Expect prefixType) (argAt 0) e <- mkExpr s st.universalInteger (node [v]) conform expect e {static = staticPrefix (StaticInteger <$> (position =<< v.static))} AVal | scalarPrefix -> withArgs 1 do v <- expression AnyType (argAt 0) e <- mkExpr s prefixType (node [v]) conform expect e {static = staticPrefix (valueAt kind =<< position =<< v.static)} _ | attr `elem` [ASucc, APred], scalarPrefix -> withArgs 1 do v <- expression (Expect prefixType) (argAt 0) e <- mkExpr s prefixType (node [v]) let step = if attr == ASucc then 1 else -1 -- (of a static value at the end of the base range: no value, and illegal, RM 4.9(34)) baseBounds <- staticBounds (unconstrained prefixType) skipped <- asks (.unevaluated) case (position =<< v.static, baseBounds, kind) of (Just p, Just (lo, hi), k) | not skipped, not (modularKind k), p + step < lo || p + step > hi -> do tn <- typeName prefixType reportAt StaticValueOutOfRange s ("`" <> tn <> "'" <> (if attr == ASucc then "Succ" else "Pred") <> "` of the static value at the end of `" <> tn <> "`'s range has no value") "fails a range check" _ -> pure () conform expect e {static = staticPrefix ((\p -> valueAt kind (p + step)) =<< position =<< v.static)} _ | attr `elem` [AMin, AMax], scalarPrefix -> withArgs 2 do vs <- mapM (expression (Expect prefixType)) at.arguments e <- mkExpr s prefixType (node vs) let chosen = case mapM (\x -> x.static >>= \sv -> (sv,) <$> position sv) vs of Just [(a, pa), (b, pb)] -> Just (if (attr == AMin) == (pa <= pb) then a else b) _ -> Nothing conform expect e {static = staticPrefix chosen} -- (of a record or an array too, Ada 2022, RM 4.10: its components' images, D196) -- (the image of an access value, or of a composite holding one, would be an -- address: not in Verada, D262) AImage -> imageIsAddress prefixType >>= \case True -> do reportExcluded s "the `'Image` of an access value is not in Verada" accessImageReplacement errorExpr s False -> case (prefix, at.arguments) of (OfObject _, []) -> mkExpr s st.string (node []) >>= conform expect (OfSubtype _, [_]) -> do v <- expression (Expect prefixType) (argAt 0) mkExpr s st.string (node [v]) >>= conform expect _ -> wrongArity 1 AModulus -> case kind of KModular m -> mkExpr s st.universalInteger (TLiteral (StaticInteger m.modulus)) >>= conform expect _ -> do reportAt WrongKindOfEntity s "`'Modulus` applies to modular types" "not a modular type" errorExpr s -- (a scalar or array type's `Size` a clause gives, RM 13.3(41)) ASize -> gets (Map.lookup prefixType . (.specifiedSizes)) >>= \case Just n -> mkExpr s st.universalInteger (TLiteral (StaticInteger n)) >>= conform expect Nothing -> mkExpr s st.universalInteger (node []) >>= conform expect -- (an enumeration's code: of an object, or of the subtype's argument; and back; -- of a subtype without codes, its `'Pos` and `'Val`) _ | attr `elem` [AEnumRep, AEnumVal], OfSubtype _ <- prefix, not (hasCodes kind) -> expression expect A.Expr {span = s, node = A.EAttribute A.AttributeRef {prefix = at.prefix, designator = A.Identifier {span = at.designator.span, text = if attr == AEnumRep then "Pos" else "Val"}, arguments = at.arguments}} AEnumRep | scalarPrefix, OfObject _ <- prefix -> withArgs 0 (mkExpr s st.universalInteger (node []) >>= conform expect) AEnumRep | scalarPrefix -> withArgs 1 do v <- expression (Expect prefixType) (argAt 0) mkExpr s st.universalInteger (node [v]) >>= conform expect AEnumVal | scalarPrefix, OfSubtype _ <- prefix -> withArgs 1 do v <- expression AnyType (argAt 0) mkExpr s prefixType (node [v]) >>= conform expect -- (the representation attributes: universal integers from the layout, D196) _ | attr `elem` [AObjectSize, AAlignment, AMaxSizeInStorageElements] -> withArgs 0 (mkExpr s st.universalInteger (node []) >>= conform expect) AComponentSize | KArray _ <- kind -> withArgs 0 (mkExpr s st.universalInteger (node []) >>= conform expect) -- (of a record component, `R.C'Position`) _ | attr `elem` [APosition, AFirstBit, ALastBit], OfObject TExpr {node = TComponentNode _} <- prefix -> withArgs 0 (mkExpr s st.universalInteger (node []) >>= conform expect) _ | attr `elem` [APosition, AFirstBit, ALastBit] -> do reportAt WrongKindOfEntity s ("`'" <> at.designator.text <> "` applies to a component of a record object") "not a record component" errorExpr s AValid | scalarPrefix -> mkExpr s st.boolean (node []) >>= conform expect AInitialized | OfObject _ <- prefix -> mkExpr s st.boolean (node []) >>= conform expect _ | attr `elem` [AFloor, ACeiling, ARounding, ATruncation, AMachine, AModel, AUnbiasedRounding, AMachineRounding, AFraction], KReal _ <- kind, OfSubtype _ <- prefix -> withArgs 1 do v <- expression (Expect prefixType) (argAt 0) mkExpr s prefixType (node [v]) >>= conform expect -- (RM A.5.3: two values of the type) _ | attr `elem` [ACopySign, AAdjacent, ARemainder], KReal _ <- kind, OfSubtype _ <- prefix -> withArgs 2 do vs <- mapM (expression (Expect prefixType)) at.arguments mkExpr s prefixType (node vs) >>= conform expect -- (a value of the type and a universal integer, an exponent or a count of digits) _ | attr `elem` [AScaling, ACompose, ALeadingPart], KReal _ <- kind, OfSubtype _ <- prefix -> withArgs 2 do v <- expression (Expect prefixType) (argAt 0) n <- expression (Expect st.integer) (argAt 1) mkExpr s prefixType (node [v, n]) >>= conform expect AExponent | KReal _ <- kind, OfSubtype _ <- prefix -> withArgs 1 do v <- expression (Expect prefixType) (argAt 0) mkExpr s st.universalInteger (node [v]) >>= conform expect _ -> do reportAt WrongKindOfEntity s ("`'" <> at.designator.text <> "` applies to scalar types") "not a scalar" errorExpr s argAt n = fromMaybe (A.Expr {span = s, node = A.ENull}) (headMaybe (drop n at.arguments)) wrongArity n = do reportAt WrongArguments s ("`'" <> at.designator.text <> "` takes " <> tshow (n :: Int) <> " argument" <> (if n == 1 then "" else "s")) "wrong number of arguments" errorExpr s notArray = do reportAt WrongKindOfEntity s ("`'" <> at.designator.text <> "` applies to arrays") "not an array" errorExpr s -- (an array attribute's dimension, `A'First (N)`: a static integer from 1 to the -- array's rank, RM 3.6.2(3)) dimensionArg rank = case at.arguments of [] -> pure (Just 1) [x] -> staticInteger x >>= \case Just n | n >= 1 && n <= toInteger rank -> pure (Just n) Just n -> Nothing <$ reportAt WrongArguments x.span ("the array has " <> tshow rank <> (if rank == 1 then " dimension" else " dimensions") <> ", numbered from 1") ("dimension " <> tshow n) -- (B2003 reported by `staticInteger`) Nothing -> pure Nothing _ -> Nothing <$ reportAt WrongArguments s "an array attribute takes at most one argument, its dimension" "too many arguments" -- 'First / 'Last: of a scalar subtype (static when its bounds are) or of an array bound prefix kind prefixType node nodeIn = case kind of KArray a -> dimensionArg (length a.indices) >>= \case Just dim | ix : _ <- drop (fromInteger dim - 1) a.indices -> do -- (of a statically constrained array subtype: static, RM 4.9(14), D262) known <- case prefix of OfSubtype x | r : _ <- drop (fromInteger dim - 1) x.indices -> pure ((,) <$> r.low.static <*> r.high.static) | null x.indices, a.constrained -> do ik <- fullKind ix.base fmap (\(lo, hi) -> (positionValue ik lo, positionValue ik hi)) <$> staticBounds ix _ -> pure Nothing e <- mkExpr s ix.base (nodeIn dim []) let isFirst = A.foldedName at.designator == "first" conform expect e {static = (if isFirst then fst else snd) <$> known} _ -> errorExpr s KRecord _ -> do reportAt WrongKindOfEntity s "`'First` and `'Last` apply to scalar types and arrays" "not scalar" errorExpr s _ -> do let sub = case prefix of OfSubtype x -> x OfObject _ -> unconstrained prefixType bounds <- staticBounds sub let isFirst = A.foldedName at.designator == "first" value = fmap (\(lo, hi) -> if isFirst then lo else hi) bounds -- (of a real subtype: its static bounds, or a floating-point type's without a -- range, its format's largest finite values, RM 3.5.7(8), 4.9(26)) realValue = case (kind, sub.range) of (KReal _, Just r) -> mfilter isReal (if isFirst then r.low.static else r.high.static) (KFixed _, Just r) -> mfilter isReal (if isFirst then r.low.static else r.high.static) (KReal rt, Nothing) | not rt.universal, Just d <- rt.digits -> Just (StaticReal ((if isFirst then negate else id) (largestFinite d))) _ -> Nothing isReal = \case StaticReal _ -> True _ -> False e <- mkExpr s prefixType (node []) conform expect e {static = (positionValue kind <$> value) <|> realValue <|> e.static} -- (the largest finite value of the IEEE format a floating-point type of these digits has: -- binary32 up to 6, binary64 beyond) largestFinite d | d <= 6 = (2 - 2 ^^ (-23 :: Int)) * 2 ^ (127 :: Int) | otherwise = (2 - 2 ^^ (-52 :: Int)) * 2 ^ (1023 :: Int) :: Rational positionValue kind v = case kind of KEnumeration _ -> StaticEnum (fromInteger v) _ -> StaticInteger v -- | The prefix of an attribute: a subtype mark or an object. -- | `X'Reduce (R, I)` (RM 4.5.10): X an array (its components, in order) or a value -- sequence `[for ... => V]`; the accumulator of the type the context gives, else the initial -- value's (else the values', when that is universal); each value V that the iteration and -- its filter give makes the accumulator `R (Accumulator, V)`, a call of the reducer, a -- function or an operator named by its string (`"+"`). reduction :: Expect -> Span -> A.AttributeRef -> Sema TExpr reduction expect s at = case at.arguments of [reducer, initialValue] -> withScope LoopScope Nothing False do (scheme, valueAst) <- case at.prefix.node of A.EAggregate A.Aggregate {bracket = True, contents = A.PlainAggregate (A.Associations [A.IteratedAssocNode ia])} -> do scheme <- forScheme ia.iterator pure (scheme, ia.value) _ -> do -- (an array's components, by a name the program cannot write) let element = A.Identifier {span = at.prefix.span, text = "Reduce'Element"} scheme <- forScheme A.Iterator {parameter = element, subtype = Nothing, reverse = False, domain = A.OfContainer at.prefix, filter = Nothing, whileCondition = Nothing, alongside = []} pure (scheme, A.Expr {span = at.prefix.span, node = A.ENameRef element}) accumulatorType <- case expect of Expect t -> pure t AnyType -> do start <- fst <$> trial (expression AnyType initialValue) universal <- isUniversal start.typeOf if universal then (.typeOf) . fst <$> trial (expression AnyType valueAst) else pure start.typeOf initial <- expression (Expect accumulatorType) initialValue let accumulatorName = A.Identifier {span = s, text = "Reduce'Accumulator"} named x = A.Argument {span = x.span, formal = Nothing, value = A.ArgExpr x, reference = Nothing} accumulator <- declare accumulatorName.text s (EObject ObjectInfo {subtype = unconstrained accumulatorType, constant = False, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Nothing}) let accumulatorRef = A.Expr {span = s, node = A.ENameRef accumulatorName} -- (an operator named by its string is the operator, user-defined or predefined) operator = case reducer.node of -- (Varc's string literal is a surface form around it) A.ESurfaceForm A.SurfaceForm {kind = A.FormLiteralText, operands = [A.Expr {node = A.EString t}]} -> listToMaybe [o | o <- [minBound .. maxBound], o `notElem` [A.OpAndThen, A.OpOrElse], A.binaryOpText o == Text.toLower t] A.EString t -> listToMaybe [o | o <- [minBound .. maxBound], o `notElem` [A.OpAndThen, A.OpOrElse], A.binaryOpText o == Text.toLower t] _ -> Nothing stepAst = case (operator, reducer.node) of (Just op, _) -> A.Expr {span = s, node = A.EBinary A.Binary {op, left = accumulatorRef, right = valueAst}} -- (an attribute function, `Integer'Max`, takes its operands as an attribute's arguments) (Nothing, A.EAttribute a) | null a.arguments -> A.Expr {span = s, node = A.EAttribute A.AttributeRef {prefix = a.prefix, designator = a.designator, arguments = [accumulatorRef, valueAst]}} _ -> A.Expr {span = s, node = A.EApply A.Apply {prefix = reducer, arguments = [named accumulatorRef, named valueAst], bracketed = Nothing}} step <- expression (Expect accumulatorType) stepAst loopLabel <- newEntity Entity {name = "", span = s, parent = Nothing, kind = ELabel} -- (its type, for a plain-Ada translation that writes it as a function) spelledType accumulatorType >>= \n -> modify' \st -> st {plainShapes = (s, PlainValue n) : st.plainShapes} mkExpr s accumulatorType (TReduceNode TReduce {label = loopLabel, accumulator, initial, scheme, step, summation = PlainSum}) _ -> do reportAt MisplacedAttribute s "`'Reduce` takes a reducer and an initial value: `X'Reduce (\"+\", 0)`" "two arguments" errorExpr s attributePrefix :: A.Expr -> Sema AttributePrefix attributePrefix p = denote p >>= \case Just (DSubtype sub) -> pure (OfSubtype sub) -- an access value to an array stands for the array (RM 4.1(9)) _ -> do x <- expression AnyType p fullKind x.typeOf >>= \case KAccess a -> fullKind a.designated.base >>= \case KArray _ -> OfObject <$> implicitDereference x _ -> pure (OfObject x) _ -> pure (OfObject x) -- | @A'Range@ or @T'Range@ as bounds. attributeRange :: A.AttributeRef -> Sema TRange attributeRange a = do prefix <- attributePrefix a.prefix st <- std let prefixType = case prefix of OfSubtype sub -> sub.base OfObject e -> e.typeOf kind <- fullKind prefixType -- `A'Range (N)`: the range of the Nth dimension dim <- case (a.arguments, kind) of ([x], KArray arr) -> staticInteger x >>= \case Just n | n >= 1 && n <= toInteger (length arr.indices) -> pure n Just n -> 1 <$ reportAt WrongArguments x.span ("the array has " <> tshow (length arr.indices) <> (if length arr.indices == 1 then " dimension" else " dimensions") <> ", numbered from 1") ("dimension " <> tshow n) -- (B2003 reported by `staticInteger`) Nothing -> pure 1 ([x], _) -> fromMaybe 1 <$> staticInteger x _ -> pure 1 let indexType = case kind of KArray arr -> maybe st.errorType (.base) (headMaybe (drop (fromInteger dim - 1) arr.indices)) _ -> prefixType boundOf attr = TExpr {span = a.designator.span, typeOf = indexType, static = Nothing, node = TAttributeNode TAttribute {prefix, attribute = attr, dimension = fromInteger dim, arguments = []}} case prefix of OfSubtype sub | not (isArrayKind kind) -> do bounds <- staticBounds sub pure case bounds of Just (lo, hi) -> TRange {low = (boundOf AFirst) {static = Just (asValue kind lo)}, high = (boundOf ALast) {static = Just (asValue kind hi)}} Nothing -> TRange {low = boundOf AFirst, high = boundOf ALast} _ -> pure TRange {low = boundOf AFirst, high = boundOf ALast} where isArrayKind = \case KArray _ -> True _ -> False asValue kind v = case kind of KEnumeration _ -> StaticEnum (fromInteger v) _ -> StaticInteger v -- * Ranges and subtypes -- | Bounds of a range in a context whose type is known. rangeOf :: TypeId -> A.RangeExpr -> Sema TRange rangeOf t r = do low <- expression (Expect t) r.low high <- expression (Expect t) r.high pure TRange {low, high} -- | A discrete range (loop, index, quantifier): its subtype and bounds. Bounds that are -- both universal integers give a range of @Integer@ (RM 3.6(18)). discreteRange :: A.DiscreteRange -> Sema (Subtype, TRange) discreteRange = \case A.DiscreteBounds r -> do -- (a bound of several possible types takes the one the other bound has: `'A' .. -- Enum'(Z)`, `False .. E'(True)`, RM 3.6.1(4), 8.6) ls <- shapes r.low hs <- shapes r.high let lowTypes = nub [t | Exactly t <- ls] highTypes = nub [t | Exactly t <- hs] common = [t | t <- lowTypes, t `elem` highTypes] -- (a universal type is never chosen so: two universal bounds make a range of Integer) chosen0 <- case (lowTypes, highTypes) of _ | [t] <- common, length lowTypes > 1 || length highTypes > 1 -> pure (Just t) (_, [t]) | length lowTypes /= 1, not (null ls) -> (\ok -> if ok then Just t else Nothing) <$> admitsAny t ls ([t], _) | length highTypes /= 1, not (null hs) -> (\ok -> if ok then Just t else Nothing) <$> admitsAny t hs _ -> pure Nothing chosen <- case chosen0 of Just t -> (\u -> if u then Nothing else Just t) <$> isUniversal t Nothing -> pure Nothing checked <- case chosen of Just t -> (\(_, problems) -> if null problems then Just t else Nothing) <$> trial ((,) <$> expression (Expect t) r.low <*> expression (Expect t) r.high) Nothing -> pure Nothing case checked of Just t -> do low <- expression (Expect t) r.low high <- expression (Expect t) r.high let range = TRange {low, high} pure (Subtype {base = t, range = Just range, indices = [], discriminantValues = [], predicates = [], excludesNull = False, name = Nothing, digits = Nothing}, range) Nothing -> plainBounds r A.DiscreteSubtype ind -> case ind.mark.node of A.EAttribute a | A.foldedName a.designator == "range" -> do range <- attributeRange a pure (Subtype {base = range.low.typeOf, range = Just range, indices = [], discriminantValues = [], predicates = [], excludesNull = False, name = Nothing, digits = Nothing}, range) _ -> do sub <- subtypeIndication ind range <- maybe (wholeRange sub) pure sub.range pure (sub, range) where plainBounds r = do st <- std low0 <- expression AnyType r.low lowUniversal <- isUniversal low0.typeOf high0 <- expression (if lowUniversal then AnyType else Expect low0.typeOf) r.high highUniversal <- isUniversal high0.typeOf let t | not lowUniversal = low0.typeOf | not highUniversal = high0.typeOf | otherwise = st.integer low <- conform (Expect t) low0 high <- conform (Expect t) high0 discrete <- isDiscrete t unless discrete do tn <- typeName t reportAt TypeMismatch r.span ("a discrete range is required, but this range is of type `" <> tn <> "`") "not discrete" let range = TRange {low, high} pure (Subtype {base = t, range = Just range, indices = [], discriminantValues = [], predicates = [], excludesNull = False, name = Nothing, digits = Nothing}, range) -- | The bounds of a subtype without an explicit constraint, as attribute references -- (static when the type's bounds are). wholeRange :: Subtype -> Sema TRange wholeRange sub = do bounds <- staticBounds sub kind <- fullKind sub.base let bound attr v = TExpr { span = Span {file = FileId (-1), start = 0, end = 0} , typeOf = sub.base , static = (\x -> case kind of KEnumeration _ -> StaticEnum (fromInteger x); _ -> StaticInteger x) <$> v , node = TAttributeNode TAttribute {prefix = OfSubtype sub, attribute = attr, dimension = 1, arguments = []} } pure TRange {low = bound AFirst (fst <$> bounds), high = bound ALast (snd <$> bounds)} -- | The static bounds of a scalar subtype as positions (integers or enumeration positions). staticBounds :: Subtype -> Sema (Maybe (Integer, Integer)) staticBounds sub = case sub.range of Just r -> pure ((,) <$> (position =<< r.low.static) <*> (position =<< r.high.static)) Nothing -> fullKind sub.base >>= \case KEnumeration e | e.isCharacter -> pure (Just (0, e.characters - 1)) | otherwise -> pure (Just (0, toInteger (length e.literals) - 1)) KInteger i | not i.universal -> pure (Just (i.baseFirst, i.baseLast)) KModular m -> pure (Just (0, m.modulus - 1)) _ -> pure Nothing where position = \case StaticInteger v -> Just v StaticEnum p -> Just (toInteger p) _ -> Nothing -- | @[not null] Mark [constraint]@. subtypeIndication :: A.SubtypeIndication -> Sema Subtype subtypeIndication ind = do marked <- subtypeMarkOf ind.mark sub <- if ind.notNull then fullKind marked.base >>= \case KAccess _ -> pure marked {excludesNull = True, name = Nothing} KSubprogramAccess _ -> pure marked {excludesNull = True, name = Nothing} KError -> pure marked _ -> do reportAt TypeMismatch ind.span "only access subtypes can exclude `null`" "not an access type" pure marked else pure marked case ind.constraint of Nothing -> pure sub Just (A.RangeConstraint spec) -> do scalar <- isScalar sub.base unless scalar do tn <- typeName sub.base reportAt TypeMismatch ind.span ("a range constraint needs a scalar type, and `" <> tn <> "` is not one") "not scalar" range <- rangeSpec sub spec compatibleRange ind.span sub range pure sub {range = Just range, name = Nothing} Just (A.ParenConstraint args) -> do kind <- fullKind sub.base case kind of KArray a | a.constrained -> do tn <- typeName sub.base reportAt TypeMismatch ind.span ("`" <> tn <> "` is already constrained") "an index constraint needs an unconstrained array type" pure sub | length args /= length a.indices -> do reportAt WrongArguments ind.span ("this array type has " <> tshow (length a.indices) <> " index" <> (if length a.indices == 1 then "" else "es") <> ", but the constraint gives " <> tshow (length args)) "wrong number of ranges" pure sub | otherwise -> do ranges <- zipWithM indexRange a.indices args pure sub {indices = ranges, name = Nothing} -- a partial view takes no index constraint (RM 3.2.2): only where the full view, an -- array type, is visible KPrivate p | Just full <- p.fullView -> do known <- gets (Map.member sub.base . (.partialDiscriminants)) fullDef <- typeDef full case fullDef.kind of -- a discriminant constraint of a partial view with known discriminants KRecord r | known -> do values <- discriminantConstraint ind.span r args pure sub {discriminantValues = values, name = Nothing} _ -> do tn <- typeName sub.base unknown <- gets (Set.member sub.base . (.unknownDiscriminants)) if unknown then reportAt TypeMismatch ind.span ("`" <> tn <> "` has unknown discriminants `(<>)` here, so it takes no constraint: its objects take their discriminants from their initial values") "constraint on a partial view" else reportAt TypeMismatch ind.span ("`" <> tn <> "` is private here, so it takes no index constraint") "constraint on a partial view" pure sub KRecord r | not (null r.discriminants) -> do values <- discriminantConstraint ind.span r args pure sub {discriminantValues = values, name = Nothing} _ -> do tn <- typeName sub.base reportAt TypeMismatch ind.span ("`" <> tn <> "` takes no constraint in parentheses") "neither an unconstrained array nor a record with discriminants" pure sub Just (A.DigitsConstraint c) -> fullKind sub.base >>= \case -- of a decimal fixed-point subtype (RM 3.5.9(16-19)): the digits it gives, no more than -- the subtype's, and its range, or else the range those digits give KFixed fx | Just typeDigits <- fx.decimalDigits -> do st <- std given <- expression (Expect st.universalInteger) c.precision let markDigits = fromMaybe typeDigits sub.digits case given.static of Just (StaticInteger n) | n >= 1 && n <= markDigits -> do let bound = fromInteger (10 ^ n - 1) * fx.delta range <- maybe (pure (staticRange sub.base (StaticReal (negate bound)) (StaticReal bound))) (rangeSpec sub) c.range compatibleRange ind.span sub range pure sub {range = Just range, name = Nothing, digits = Just n} | otherwise -> do tn <- typeName sub.base reportAt StaticValueOutOfRange c.precision.span ("this subtype of `" <> tn <> "` has " <> tshow markDigits <> " digits, so a digits constraint on it gives from 1 to " <> tshow markDigits) "out of range" pure sub _ -> do reportAt NotStatic c.precision.span "the digits of a digits constraint must be a static integer" "not static" pure sub -- of a floating-point subtype: Annex J.3's reduced accuracy subtype _ -> obsolescentConstraint "a `digits` constraint on a floating-point subtype" Just (A.DeltaConstraint _) -> obsolescentConstraint "a `delta` constraint in a subtype indication" where rangeSpec sub = \case A.Bounds r -> rangeOf sub.base r A.RangeAttribute e -> case e.node of A.EAttribute a | A.foldedName a.designator == "range" -> attributeRange a _ -> do reportAt TypeMismatch e.span "a range is required here" "write `Low .. High` or `X'Range`" x <- errorExpr e.span pure TRange {low = x, high = x} obsolescentConstraint what = do report (diagnostic ObsolescentClause Semantic (what <> " is obsolescent")) { primary = Just (label ind.span "Annex J.3 form") , advice = Just "declare a subtype with a `range` constraint instead" } st <- std pure (unconstrained st.errorType) -- | A range constraint on a subtype is compatible with it (RM 3.2.2(11), 3.5(8)): the range -- is null or both its bounds belong to the subtype. Static bounds that do not are an error -- here; others are checked where the declaration is elaborated (the check goes before it). compatibleRange :: Span -> Subtype -> TRange -> Sema () compatibleRange at mark range = forM_ mark.range \within -> case (number range.low, number range.high, number within.low, number within.high) of (Just l, Just h, Just wl, Just wh) | l > h || (l >= wl && h <= wh) -> pure () | otherwise -> do n <- markName report (diagnostic StaticValueOutOfRange Semantic ("this range is not within `" <> n <> "`, the subtype it constrains")) { primary = Just (label at ("outside `" <> n <> "`")) , notes = [Note {text = "a constraint narrows a subtype: its bounds must belong to the subtype, unless the range is empty (RM 3.2.2)", span = Nothing}] } _ -> do n <- markName from <- gets (.compatibilityFrom) let own = or [k >= from | e <- [range.low, range.high, within.low, within.high], TExpr {node = TObject (DeclId k)} <- universe e] universe e = e : concatMap universe (subExpressions e) let check = TCompatibility {at, given = range, within, mark = n} collecting <- gets (isJust . (.compatibilityChecks)) -- (before the declaration or statement, or else in the expression that has it, where -- its bounds are known: a contract's, or one naming a quantifier's variable) if collecting && not own then modify' \st -> st {compatibilityChecks = (check :) <$> st.compatibilityChecks} else modify' \st -> st {expressionChecks = check : st.expressionChecks} where number x = case x.static of Just (StaticInteger v) -> Just (toRational v) Just (StaticEnum p) -> Just (toRational p) Just (StaticReal r) -> Just r _ -> Nothing markName = maybe (typeName mark.base) (fmap (.name) . entity) mark.name -- | A record's components that names reach: not its hidden discriminants (D254). namedComponents :: RecordType -> [(Int, ComponentDef)] namedComponents r = [(k, c) | (k, c) <- zip [0 ..] r.components, not (hiddenField r k)] -- | A discriminant constraint (RM 3.7.1): a value for every discriminant, positionally or -- by name. discriminantConstraint :: Span -> RecordType -> [A.Argument] -> Sema [TExpr] discriminantConstraint at r args = do let discs = visibleDiscriminants r (positional, named) = span (isNothing . (.formal)) args byPosition <- zipWithM (\d a -> (folded d.name,) <$> argumentValue (Expect d.subtype.base) a) discs positional byName <- fmap catMaybes . forM named $ \a -> case a.formal of Just f | Just d <- find (\x -> folded x.name == A.foldedName f) discs -> Just . (folded d.name,) <$> argumentValue (Expect d.subtype.base) a Just f -> do reportAt UnknownComponent f.span ("no discriminant `" <> f.text <> "`") "not a discriminant" pure Nothing Nothing -> pure Nothing let given = byPosition <> byName when (length positional > length discs) (reportAt WrongArguments at "too many discriminant values" "too many values") values <- forM discs \d -> case lookup (folded d.name) given of Just v -> pure v Nothing -> do reportAt WrongArguments at ("no value for discriminant `" <> d.name <> "`") "missing discriminant" errorExpr at -- (the storage's discriminants, the hidden ones implied, D254) pure (storageDiscriminantValues r values id) -- | A range for an index of an array (in an index constraint or a slice): `Low .. High`, a -- discrete subtype, or `X'Range`. indexRange :: Subtype -> A.Argument -> Sema TRange indexRange ix a = case a.value of A.ArgRange r -> rangeOf ix.base r A.ArgExpr e -> case e.node of A.EAttribute at | A.foldedName at.designator == "range" -> attributeRange at _ -> denote e >>= \case Just (DSubtype sub) -> do bounds <- subtypeRange e.span sub case bounds of Just r -> pure r Nothing -> do reportAt TypeMismatch e.span "a discrete subtype with bounds is needed here" "not a discrete subtype" x <- errorExpr e.span pure TRange {low = x, high = x} _ -> do reportAt TypeMismatch e.span "a range is required here" "write `Low .. High`, a subtype or `X'Range`" x <- errorExpr e.span pure TRange {low = x, high = x} A.ArgBox -> do x <- errorExpr a.span pure TRange {low = x, high = x} -- | The bounds of a discrete subtype (its constraint, or its type's range). subtypeRange :: Span -> Subtype -> Sema (Maybe TRange) subtypeRange at sub = case sub.range of Just r -> pure (Just r) Nothing -> do bounds <- staticBounds sub kind <- fullKind sub.base let value v = case kind of KEnumeration _ -> StaticEnum (fromInteger v) _ -> StaticInteger v literal v = TExpr {span = at, typeOf = sub.base, static = Just (value v), node = TLiteral (value v)} pure ((\(lo, hi) -> TRange {low = literal lo, high = literal hi}) <$> bounds) -- | The subtype of an expression where it is known (objects, conversions), else its type. subtypeOfExpr :: TExpr -> Sema Subtype subtypeOfExpr e = case e.node of TObject d -> entity d >>= \x -> pure case x.kind of EObject o -> o.subtype _ -> unconstrained e.typeOf TConversionNode c -> pure c.target -- (a record component's nominal subtype, when its constraint is static: so a case over -- `R.S`, with `S : Shape`, covers `Shape`'s values, RM 5.4(7)) TComponentNode c -> do def <- typeDef c.prefix.typeOf pure case def.kind of KRecord r | Just comp <- listToMaybe (drop c.component r.components) , comp.subtype.base == e.typeOf , maybe True (\rg -> isJust rg.low.static && isJust rg.high.static) comp.subtype.range -> comp.subtype _ -> unconstrained e.typeOf _ -> pure (unconstrained e.typeOf) -- | A static integer expression's value (B2003 when it is not static). staticInteger :: A.Expr -> Sema (Maybe Integer) staticInteger x = do e <- expression AnyType x case e.static of Just (StaticInteger v) -> pure (Just v) _ | e.node == TErrorExpr -> pure Nothing _ -> do reportAt NotStatic x.span "a static integer expression is required here" "not static" pure Nothing -- * Choices and coverage (RM 3.8.1) -- | @others@ stands alone in the last alternative of a case statement or expression or a -- variant part, and in the last association of an aggregate (RM 3.8.1(4), 4.3.1(4), -- 4.3.3(4), 5.4(4)): the choice lists in their order, with the code to report under. othersPlacement :: DiagCode -> [[A.Choice]] -> Sema () othersPlacement code lists = do let numbered = zip [1 :: Int ..] lists final = length lists forM_ numbered \(k, cs) -> forM_ [sp | A.ChoiceOthers sp <- cs] \sp -> if | length cs > 1 -> reportAt code sp "`others` must be the only choice of its alternative" "not alone" | k /= final -> reportAt code sp "`others` must be the last choice" "choices follow it" | otherwise -> pure () choice :: TypeId -> A.Choice -> Sema TChoice choice t = \case A.ChoiceOthers _ -> pure TChoiceOthers A.ChoiceRange r -> TChoiceRange <$> rangeOf t r A.ChoiceExpr x -> denote x >>= \case Just (DSubtype sub) -> pure (TChoiceSubtype sub) _ -> case x.node of A.EAttribute a | A.foldedName a.designator == "range" -> TChoiceRange <$> attributeRange a _ -> TChoiceValue <$> expression (Expect t) x -- | The first item of each key, in order. nubOn :: Eq k => (a -> k) -> [a] -> [a] nubOn key = go [] where go _ [] = [] go seen (x : rest) | key x `elem` seen = go seen rest | otherwise = x : go (key x : seen) rest -- | Case choices must be static and cover the selector's subtype exactly once, unless -- @others@ is given (RM 5.4). checkCoverage :: Span -> Subtype -> [(Span, [TChoice])] -> Sema () checkCoverage s selector alternatives = do let hasOthers = any (any isOthers . snd) alternatives intervals <- fmap concat . forM alternatives $ \(altSpan, cs) -> forM (filter (not . isOthers) cs) \c -> (altSpan,) <$> choiceInterval c let static = [(sp, iv) | (sp, Just iv) <- intervals] nonStatic = [sp | (sp, Nothing) <- intervals] forM_ (nub nonStatic) \sp -> reportAt CaseCoverage sp "case choices must be static" "not static" -- duplicates: each choice that covers a value an earlier choice (in the text) covers, -- reported where it repeats it let sorted = sortOn (fst . snd) static overlaps = [ (sb, max blo alo) | (k, (sb, (blo, bhi))) <- zip [0 :: Int ..] static , blo <= bhi , (alo, _) <- take 1 [(alo, ahi) | (_, (alo, ahi)) <- take k static, alo <= ahi, alo <= bhi, blo <= ahi] ] forM_ (nubOn fst overlaps) \(sb, v) -> do shown <- describe v reportAt CaseCoverage sb ("value " <> shown <> " is covered by more than one choice") "covered again here" -- (with a static selector subtype, a choice covers only its values, `others` or not, RM -- 5.4(7/4), 3.8.1(10/4)) selectorBounds <- staticBounds selector forM_ selectorBounds \(lo, hi) -> forM_ (take 1 [(sp, iv) | (sp, iv@(a, b)) <- static, a <= b, a < lo || b > hi]) \(sp, (a, b)) -> do shown <- describeInterval (if a < lo then (a, min b (lo - 1)) else (max a (hi + 1), b)) reportAt CaseCoverage sp ("the choice " <> shown <> " is outside the selector's subtype") "outside the subtype" unless (hasOthers || not (null nonStatic)) do domain <- staticBounds selector case domain of Nothing -> pure () Just (lo, hi) -> do let gaps = missingIntervals lo hi (map snd sorted) unless (null gaps) do shown <- mapM describeInterval (take 4 gaps) kind <- fullKind selector.base let tooMany = case kind of KInteger _ -> True KModular _ -> True _ -> length gaps > 4 -- (the catch-all in the unit's own syntax: Varc's match arm, Vibe's case clause) varc <- asks (.varc) python <- asks (.python) let catchAll | varc = "a final `_ =>` arm" | python = "a final `case _:`" | otherwise = "a final `when others =>`" report (diagnostic CaseCoverage Semantic ("case choices do not cover " <> Text.intercalate ", " shown <> (if length gaps > 4 then ", ..." else ""))) { primary = Just (label s "missing choices") , advice = Just (if tooMany then "add the missing choices or " <> catchAll else "add the missing choices") } where isOthers = \case TChoiceOthers -> True _ -> False position = \case Just (StaticInteger v) -> Just v Just (StaticEnum p) -> Just (toInteger p) _ -> Nothing choiceInterval = \case TChoiceValue v -> pure ((\x -> (x, x)) <$> position v.static) TChoiceRange r -> pure ((,) <$> position r.low.static <*> position r.high.static) TChoiceSubtype sub -> staticBounds sub TChoiceOthers -> pure Nothing missingIntervals lo hi ivs = go lo (sortOn fst ivs) where go next [] = [(next, hi) | next <= hi] go next ((a, b) : rest) | b < a = go next rest | a > next = (next, min hi (a - 1)) : go (max next (b + 1)) rest | otherwise = go (max next (b + 1)) rest describeInterval (a, b) = if a == b then describe a else rangeText <$> describe a <*> describe b describe v = fullKind selector.base >>= \case KEnumeration e | e.isCharacter && v >= 0 && v < min e.characters 0x110000 -> pure (tshow (chr (fromInteger v))) | otherwise -> pure (maybe (tshow v) (\l -> "`" <> l <> "`") (headMaybe (drop (fromInteger v) e.literals))) _ -> pure (tshow v) -- * Aggregates (RM 4.3) -- | The associations of an aggregate whose @others@ is misplaced are reported once, before -- its type is known. aggregateOthers :: A.Aggregate -> Sema () aggregateOthers ag = case ag.contents of A.PlainAggregate cs -> components cs A.ExtensionAggregateContents e -> components e.components A.DeltaAggregateContents _ -> pure () where components = \case A.Associations assocs -> othersPlacement InvalidAggregate [n.choices | A.NamedAssocNode n <- assocs] A.NullRecordComponents -> pure () aggregate :: Expect -> Span -> A.Aggregate -> Sema TExpr aggregate expect s ag = aggregateOthers ag >> case expect of AnyType -> do reportAt InvalidAggregate s "the type of this aggregate cannot be determined" "qualify it: `T'(...)`" errorExpr s Expect t -> do kind <- fullKind t container <- gets (lookup t . (.aggregateOps)) case (kind, ag.contents) of (KError, _) -> errorExpr s -- a container aggregate (T25b): `[A, B]`, `[]` or `[for X of S [when C] => V]` (_, A.PlainAggregate (A.Associations assocs)) | ag.bracket, Just (emptyFn, addProc) <- container -> do addEntity <- entity addProc let elementType = case addEntity.kind of ESubprogram info | [_, x] <- info.parameters -> Just x _ -> Nothing et <- case elementType of Just x -> (\xe -> case xe.kind of EObject o -> o.subtype.base; _ -> t) <$> entity x Nothing -> pure t empty <- mkExpr s t (TCallNode TCall {callee = emptyFn, arguments = []}) -- (the type's `Length`, a function of one parameter of the type, declared with Empty) emptyEntity <- entity emptyFn siblings <- gets (\st -> [d | (d, x) <- IntMap.toList st.entities, x.parent == emptyEntity.parent, Text.toLower x.name == "length"]) lengthFn <- fmap listToMaybe . flip filterM (map DeclId siblings) $ \d -> (\x -> case x.kind of ESubprogram info -> info.kind == Function && length info.parameters == 1; _ -> False) <$> entity d object <- newEntity Entity {name = "Aggregate'Object", span = s, parent = Nothing, kind = EObject ObjectInfo {subtype = unconstrained t, constant = False, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Nothing}} case assocs of [A.IteratedAssocNode it] -> withScope LoopScope Nothing False do scheme <- forScheme it.iterator value <- expression (Expect et) it.value loopLabel <- newEntity Entity {name = "", span = s, parent = Nothing, kind = ELabel} shape <- PlainContainer <$> spelledType t <*> spelledEntity emptyFn <*> spelledEntity addProc modify' \st -> st {plainShapes = (s, shape) : st.plainShapes} mkExpr s t (TAggregateNode (TContainerNode TContainerAggregate {object, empty, add = addProc, length = lengthFn, values = [], iterated = Just (loopLabel, scheme, value)})) _ | all isPositional assocs -> do values <- mapM (\case A.PositionalAssoc x -> expression (Expect et) x; other -> errorExpr (assocSpan other)) assocs mkExpr s t (TAggregateNode (TContainerNode TContainerAggregate {object, empty, add = addProc, length = lengthFn, values, iterated = Nothing})) _ -> do reportAt InvalidAggregate s "a container aggregate is positional, `[A, B]`, or iterated, `[for X of S => V]`" "Verada does not take named associations (`Add_Named`) in container aggregates" errorExpr s (KRecord r, A.PlainAggregate (A.Associations assocs)) -> recordAggregate t r assocs (KRecord r, A.PlainAggregate A.NullRecordComponents) | null r.components -> mkExpr s t (TAggregateNode (TRecordAggregate [])) (KRecord _, A.PlainAggregate A.NullRecordComponents) -> do reportAt InvalidAggregate s "`(null record)` is only for records without components" "this record has components" errorExpr s (KArray a, A.PlainAggregate (A.Associations assocs)) -> arrayAggregate t a 0 s assocs (KRecord r, A.ExtensionAggregateContents x) -> extensionAggregate t r x (_, A.ExtensionAggregateContents _) -> do tn <- typeName t reportAt InvalidAggregate s ("an extension aggregate is of a type extension, and `" <> tn <> "` is not one") "not a record extension" errorExpr s (KRecord r, A.DeltaAggregateContents d) -> do base <- expression (Expect t) d.base updates <- concat <$> forM d.associations \case A.NamedAssocNode n -> concat <$> forM n.choices \case A.ChoiceExpr (A.Expr {node = A.ENameRef i}) | Just (k, c) <- find ((== A.foldedName i) . folded . (.name) . snd) (zip [0 ..] r.components) -> do v <- assocValueNamed c n pure [(k, v)] other -> do reportAt InvalidAggregate (choiceSpan other) "a delta aggregate names components of the record" "not a component" pure [] other -> do reportAt InvalidAggregate (assocSpan other) "a delta aggregate gives components by name" "not named" pure [] mkExpr s t (TAggregateNode (TRecordDeltaNode TRecordDelta {base, updates})) (KArray a, A.DeltaAggregateContents d) | [ix] <- a.indices -> do base <- expression (Expect t) d.base updates <- concat <$> forM d.associations \case A.NamedAssocNode n -> do cs <- mapM (choice ix.base) n.choices v <- case n.value of A.AssocExpr x -> expression (Expect a.component.base) x A.AssocBox -> do reportAt InvalidAggregate n.span "a delta aggregate gives new values, not `<>`" "`<>` here" errorExpr n.span pure [TNamedValue {choices = cs, value = v}] other -> do reportAt InvalidAggregate (assocSpan other) "a delta aggregate gives components by index" "not named" pure [] mkExpr s t (TAggregateNode (TArrayDeltaNode TArrayDelta {base, updates})) _ -> do tn <- typeName t reportAt InvalidAggregate s ("an aggregate cannot be of type `" <> tn <> "`") "not a record or array" errorExpr s where -- `(Ancestor with Components)` (RM 4.3.2): the ancestor's components from its value (or, -- for a subtype mark, their defaults), then the extension's from the associations extensionAggregate t r x = do ancestor <- denote x.ancestor >>= \case Just (DSubtype sub) -> pure (Left sub.base) _ -> Right <$> expression AnyType x.ancestor let ancestorType = either id (.typeOf) ancestor related <- descendsFrom t ancestorType ancestorRecord <- recordOfTagged ancestorType case ancestorRecord of Just ar | related, ancestorType /= t -> do let k = length ar.components inherited = take k r.components -- (the type's own discriminants stored in the ancestor's part: those a derivation -- after the ancestor declared, renaming the ancestor's, RM 4.3.2(6); the aggregate -- gives them, and the ancestor part must have them, RM 4.3.2(8), D254) declaredAt = [p | p <- visibleDiscriminantFields r, p < k, fmap (.span) (listToMaybe (drop p r.components)) /= fmap (.span) (listToMaybe (drop p ar.components))] n = length declaredAt hiddenInAncestor = [(p, imp) | (p, imp) <- maybe [] (.implied) r.discriminantView, p < k] ownIndex p = if p < k then elemIndex p declaredAt else Just (p - k + n) objectAt p = lookup p (zip (discriminantFields r) r.discriminants) shifted c = ComponentDef {name = c.name, span = c.span, subtype = c.subtype, initial = c.initial, presence = [Presence {discriminant = i, choices = q.choices, negated = q.negated} | q <- c.presence, Just i <- [ownIndex q.discriminant]]} ownPlaces = declaredAt <> [p | p <- discriminantFields r, p >= k] ownVisible = mapMaybe ownIndex [p | p <- visibleDiscriminantFields r, p `elem` ownPlaces] ownFields = mapMaybe ownIndex ownPlaces own = RecordType { components = [c | p <- declaredAt, c <- take 1 (drop p r.components)] <> map shifted (drop k r.components) , discriminants = mapMaybe objectAt ownPlaces , discriminantPlaces = ownFields , discriminantView = if ownVisible == ownFields then Nothing else Just DiscriminantView {visible = ownVisible, implied = []} , limited = r.limited , finalizer = r.finalizer , tag = r.tag , layout = Nothing } ownPart <- case x.components of A.Associations assocs -> recordAggregate t own assocs A.NullRecordComponents -> mkExpr s t (TAggregateNode (TRecordAggregate [])) case ownPart.node of TAggregateNode (TRecordAggregate values) -> do let given = zip declaredAt (take n values) -- (each of the ancestor's discriminants as the aggregate has it) constraintAt p = case lookup p given of Just v -> v Nothing -> case lookup p hiddenInAncestor of Just (ImpliedValue e) -> Just e Just (SameAs j) -> join (lookup j given) Nothing -> Nothing constrained = n > 0 || not (null hiddenInAncestor) parentValues <- case ancestor of Right value0 -> do -- (the ancestor part converted to the ancestor's subtype these discriminants -- give: a discriminant check, Constraint_Error where it fails) value <- if constrained then do constraint <- forM (discriminantFields ar) \p -> case constraintAt p of Just v -> pure v Nothing -> mkExpr value0.span (maybe value0.typeOf (.subtype.base) (listToMaybe (drop p ar.components))) (TComponentNode TComponent {prefix = value0, component = p}) mkExpr value0.span value0.typeOf (TConversionNode TConversion {target = (unconstrained value0.typeOf) {discriminantValues = constraint}, operand = value0, qualified = True}) else pure value0 forM (zip [0 ..] inherited) \(i, c) -> Just <$> mkExpr value.span c.subtype.base (TComponentNode TComponent {prefix = value, component = i}) Left _ -> forM (zip [0 ..] inherited) \(i, c) -> case (constraintAt i, c.initial) of (Just v, _) -> pure (Just v) (Nothing, Just dflt) -> pure (Just dflt) (Nothing, Nothing) -> do reportAt InvalidAggregate x.ancestor.span ("the ancestor part gives `" <> c.name <> "` its default, and it has none") "no default" Just <$> errorExpr s mkExpr s t (TAggregateNode (TRecordAggregate (parentValues <> drop n values))) _ -> errorExpr s _ -> do tn <- typeName t an <- typeName ancestorType reportAt InvalidAggregate x.ancestor.span ("the ancestor part must be of a tagged type `" <> tn <> "` extends, and `" <> an <> "` is not one") "not an ancestor" errorExpr s recordAggregate t r assocs = do -- (the components as the program names and orders them: the discriminants the type -- declares first, in their order, then the others; not hidden ones, D254) let storage = zip [0 :: Int ..] r.components components = [(k, c) | k <- visibleDiscriminantFields r, c <- take 1 (drop k r.components)] <> otherComponents r (positional, rest) = span isPositional assocs -- (a value by position is of the next component that exists for the discriminant values -- given before it: `(False, 3, 7)` of a variant record skips the components of the -- variants False does not select, RM 4.3.1(13)) positionalValues <- positionalOf r components positional [] -- `others` stands for the components given neither by position nor by name let named' = [A.foldedName i | A.NamedAssocNode n <- rest, A.ChoiceExpr (A.Expr {node = A.ENameRef i}) <- n.choices] byPosition = map (folded . fst) positionalValues remaining = [(k, c) | (k, c) <- components, folded c.name `notElem` (named' <> byPosition)] named <- forM rest \case A.NamedAssocNode n -> do targets <- fmap concat . forM n.choices $ \case A.ChoiceOthers _ -> pure [c | (_, c) <- remaining] A.ChoiceExpr (A.Expr {node = A.ENameRef i}) -> case find ((== A.foldedName i) . folded . (.name) . snd) components of Just (_, c) -> pure [c] Nothing -> do let suggestion = closest i.text (map (.name) r.components) reportAt UnknownComponent i.span ("no component `" <> i.text <> "` in this record") (maybe "no such component" (\c -> "did you mean `" <> c <> "`?") suggestion) pure [] other -> do reportAt InvalidAggregate (choiceSpan other) "a record aggregate names components" "not a component name" pure [] forM targets \c -> (c.name,) <$> assocValueNamed c n other -> do reportAt InvalidAggregate (assocSpan other) "positional components must come before named ones" "out of order" pure [] let given0 = positionalValues <> concat named -- (with the hidden discriminants' values, those the declared ones imply, D254) componentName k = maybe "" (.name) (listToMaybe (drop k r.components)) impliedValue = \case ImpliedValue x -> Just x SameAs j -> lookupFolded (componentName j) given0 given = given0 <> [(componentName k, x) | (k, imp) <- maybe [] (.implied) r.discriminantView, Just x <- [impliedValue imp]] -- in a variant record, the components of the variant the discriminants select presentAll <- forM storage \(_, c) -> isPresent r given c let present = [fromMaybe (Just True) (lookup k (zip (map fst storage) presentAll)) | (k, _) <- components] let absentGiven = [c | ((_, c), Just False) <- zip components present, isJust (lookupFolded c.name given)] wanted = [(k, c) | ((k, c), p) <- zip components present, p /= Just False] when (any isNothing present) do reportAt NotStatic s "the discriminants of an aggregate of a variant record must be static" "not static" forM_ absentGiven \c -> reportAt InvalidAggregate s ("component `" <> c.name <> "` does not exist for these discriminant values") "not in this variant" let counts = [(c.name, length [() | (n, _) <- given, folded n == folded c.name]) | (_, c) <- wanted] forM_ [n | (n, k) <- counts, k > 1] \n -> reportAt InvalidAggregate s ("component `" <> n <> "` is given more than once") "duplicate component" let missing = [n | (n, 0) <- counts] unknownNames = length [() | A.NamedAssocNode n <- rest, A.ChoiceExpr (A.Expr {node = A.ENameRef i}) <- n.choices, A.foldedName i `notElem` map (folded . (.name) . snd) components] -- a misspelt component name is reported once, not again as a missing component unless (null missing || unknownNames > 0) do reportAt InvalidAggregate s ("this aggregate has no value for " <> Text.intercalate ", " ["`" <> n <> "`" | n <- missing]) "missing components" if length positional > length positionalValues then do reportAt InvalidAggregate s "too many components in this aggregate" "too many values" errorExpr s else do values <- forM (zip storage presentAll) \((_, c), p) -> if p == Just False then pure Nothing else Just <$> maybe (errorExpr s) pure (lookupFolded c.name given) mkExpr s t (TAggregateNode (TRecordAggregate values)) positionalOf r cs as given = case (as, cs) of (a : more, (_, c) : cs') -> do present <- isPresent r (reverse given) c if present == Just False then positionalOf r cs' as given else do v <- assocValue c.subtype.base a positionalOf r cs' more ((c.name, v) : given) _ -> pure (reverse given) -- whether a component exists for the discriminant values given (Nothing: not static) isPresent r given c = do checks <- forM c.presence \p -> case drop p.discriminant r.components of d : _ -> case lookupFolded d.name given >>= (.static) of Just v -> Just . (/= p.negated) . or <$> mapM (choiceHolds (position v)) p.choices Nothing -> pure Nothing [] -> pure (Just True) pure (and <$> sequence checks) position = \case StaticInteger v -> v StaticEnum k -> toInteger k _ -> 0 choiceHolds v = \case TChoiceValue x -> pure ((position <$> x.static) == Just v) TChoiceRange rg -> pure (maybe False (\(lo, hi) -> lo <= v && v <= hi) (liftA2 (,) (position <$> rg.low.static) (position <$> rg.high.static))) TChoiceSubtype sub -> maybe False (\(lo, hi) -> lo <= v && v <= hi) <$> staticBounds sub TChoiceOthers -> pure False lookupFolded n given = case [v | (m, v) <- given, folded m == folded n] of v : _ -> Just v [] -> Nothing isPositional = \case A.PositionalAssoc _ -> True _ -> False assocValue t = \case A.PositionalAssoc x -> expression (Expect t) x other -> errorExpr (assocSpan other) assocValueNamed c n = case n.value of A.AssocExpr x -> expression (Expect c.subtype.base) x -- `<>`: the component's default value A.AssocBox -> case c.initial of Just dflt -> pure dflt Nothing -> do -- (a type that initialises itself, as a container does: its default value) initialised <- defaultInitialised c.subtype.base if initialised then pure TExpr {span = n.span, typeOf = c.subtype.base, static = Nothing, node = TDefaultValue} else do reportAt InvalidAggregate n.span ("`<>` needs a default value for `" <> c.name <> "`") "give the component a default in the record type, or write the value" errorExpr n.span assocSpan = \case A.PositionalAssoc x -> x.span A.NamedAssocNode n -> n.span A.IteratedAssocNode i -> i.span choiceSpan = \case A.ChoiceExpr x -> x.span A.ChoiceRange r -> r.span A.ChoiceOthers sp -> sp -- array aggregates; for a multidimensional array the components of dimension d are -- subaggregates for dimension d+1 arrayAggregate t a dim sp written = do assocs <- mapM resolvedDomain written let lastDim = dim == length a.indices - 1 indexType = maybe t (.base) (headMaybe (drop dim a.indices)) element x = if lastDim then expression (Expect a.component.base) x else case x.node of A.EAggregate inner | A.PlainAggregate (A.Associations innerAssocs) <- inner.contents -> arrayAggregate t a (dim + 1) x.span innerAssocs A.EParen inner -> element inner -- (a string literal as the subaggregate of the last dimension, of characters: -- the positional aggregate of its characters, RM 4.3.3(7), D262) A.EString str | dim == length a.indices - 2 , not (Text.null str) -> arrayAggregate t a (dim + 1) x.span [A.PositionalAssoc A.Expr {span = x.span, node = A.ECharacter c} | c <- Text.unpack str] -- (Varc's string literal, a text only where a text is wanted) A.ESurfaceForm A.SurfaceForm {kind = A.FormLiteralText, operands = [inner]} -> element inner _ -> do reportAt InvalidAggregate x.span "a component of a multidimensional aggregate must itself be an aggregate" "expected `(...)`" errorExpr x.span if all isPositional assocs then do values <- mapM (\case A.PositionalAssoc x -> element x; other -> errorExpr (assocSpan other)) assocs mkExpr sp t (TAggregateNode (TArrayPositional TPositional {values, others = Nothing})) else if any isIterated assocs then case assocs of -- `[for X of A [when C] => V]` (T25b), `[for I in R when C => V]` of an -- unconstrained type, and an iteration with a `while` or sources in step (whose -- count is known only once it ends): collected in one pass [A.IteratedAssocNode it] | isNothing (rangeDomain it.iterator.domain) || (isJust it.iterator.filter && not a.constrained) || isJust it.iterator.whileCondition || not (null it.iterator.alongside) , lastDim , [ix] <- a.indices -> withScope LoopScope Nothing False do scheme <- forScheme it.iterator value <- expression (Expect a.component.base) it.value shape <- PlainArray <$> spelledType t <*> maybe (spelledType ix.base) spelledEntity ix.name modify' \st -> st {plainShapes = (sp, shape) : st.plainShapes} st <- std let hidden n = A.Identifier {span = sp, text = n} nameAst n = A.Expr {span = sp, node = A.ENameRef (hidden n)} arg x = A.Argument {span = sp, formal = Nothing, value = A.ArgExpr x, reference = Nothing} plus x y = A.Expr {span = sp, node = A.EBinary A.Binary {op = A.OpAdd, left = x, right = y}} firstOf x = A.Expr {span = sp, node = A.EAttribute A.AttributeRef {prefix = x, designator = hidden "First", arguments = []}} buffer <- declare "Collect'Buffer" sp (EObject ObjectInfo {subtype = unconstrained t, constant = False, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Nothing}) count <- declare "Collect'Count" sp (EObject ObjectInfo {subtype = unconstrained st.integer, constant = False, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Nothing}) slot <- expression AnyType A.Expr {span = sp, node = A.EApply A.Apply {prefix = nameAst "Collect'Buffer", arguments = [arg (plus (firstOf (nameAst "Collect'Buffer")) (nameAst "Collect'Count"))], bracketed = Nothing}} counter <- expression AnyType (nameAst "Collect'Count") next <- expression (Expect st.integer) (plus (nameAst "Collect'Count") A.Expr {span = sp, node = A.EInteger 1}) loopLabel <- newEntity Entity {name = "", span = sp, parent = Nothing, kind = ELabel} mkExpr sp t (TAggregateNode (TArrayCollectNode TCollect {label = loopLabel, buffer, count, scheme, writes = [(slot, value), (counter, next)]})) -- `(for X of A => V)` for a dimension before the last, A an array of one -- dimension (B7005-32, D192): over A's range, X naming its component there [A.IteratedAssocNode it] | A.OfContainer source <- it.iterator.domain , not lastDim , isNothing it.iterator.filter && isNothing it.iterator.whileCondition && null it.iterator.alongside -> withScope LoopScope Nothing False do array <- expression AnyType source fullKind array.typeOf >>= \case KArray sa | [six] <- sa.indices -> do domain <- arrayRange array sa six index <- newEntity Entity {name = it.iterator.parameter.text <> "'Index", span = it.iterator.parameter.span, parent = Nothing, kind = EObject ObjectInfo {subtype = six, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}} at <- mkExpr it.iterator.parameter.span six.base (TObject index) component <- mkExpr it.iterator.parameter.span sa.component.base (TIndexedNode TIndexed {prefix = array, indices = [at]}) _ <- declare it.iterator.parameter.text it.iterator.parameter.span (EObject ObjectInfo {subtype = sa.component, constant = True, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Just component}) value <- element it.value mkExpr sp t (TAggregateNode (TArrayIteratedNode TIterated {parameter = index, domain, filter = Nothing, value, others = Nothing})) KError -> errorExpr sp _ -> notYetSupported sp "an iterated association over a container's elements, or over a multidimensional array's components, for a dimension of a multidimensional array" T35 >> errorExpr sp -- `(for I in R [when C] => V[, others => W])` A.IteratedAssocNode it : rest | Just dr <- rangeDomain it.iterator.domain , isNothing it.iterator.whileCondition , null it.iterator.alongside , lastDim || null rest , Just othersValue <- case rest of [] -> Just Nothing [A.NamedAssocNode n] | [A.ChoiceOthers _] <- n.choices, A.AssocExpr w <- n.value -> Just (Just w) _ -> Nothing -> do others <- traverse element othersValue withScope BlockScope Nothing False do (sub, domain) <- discreteRange dr -- with `others`, the range is static (RM 4.3.3(17)) when (isJust others && (isNothing domain.low.static || isNothing domain.high.static)) do reportAt InvalidAggregate it.span "an iterated association with `others` needs a static range" "not static" parameter <- declare it.iterator.parameter.text it.iterator.parameter.span (EObject ObjectInfo {subtype = sub, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}) kept <- traverse boolean it.iterator.filter -- (of a dimension before the last: the aggregate of the dimensions after it) value <- if lastDim then expression (Expect a.component.base) it.value else element it.value mkExpr sp t (TAggregateNode (TArrayIteratedNode TIterated {parameter, domain, filter = kept, value, others})) -- iterated associations over ranges beside named ones (B7005-31, D192): their -- choices are static (RM 4.3.3(17)), and the aggregate is one iterated over the -- range they span, each position's value a case on it _ | lastDim , length assocs > 1 , any isIterated assocs , all besideOthers assocs -> mixedAggregate t a indexType sp assocs | length assocs > 1 -> notYetSupported sp "an iterated association beside other associations in an array aggregate, other than `others` after one over a range" T35 >> errorExpr sp | otherwise -> notYetSupported sp "an iterated association over an array's components or a container's elements, or with a `while`, for a dimension of a multidimensional array" T35 >> errorExpr sp else do let (positional, named) = span isPositional assocs values <- mapM (\case A.PositionalAssoc x -> element x; other -> errorExpr (assocSpan other)) positional namedValues <- forM named \case A.NamedAssocNode n -> do cs <- mapM (choice indexType) n.choices v <- case n.value of A.AssocExpr x -> element x A.AssocBox -> boxValue n.span a.component pure TNamedValue {choices = cs, value = v} other -> do reportAt InvalidAggregate (assocSpan other) "positional components must come before named ones" "out of order" v <- errorExpr (assocSpan other) pure TNamedValue {choices = [], value = v} case (values, namedValues) of ([], _) -> do -- a choice that is not static must be the only one (RM 4.3.3(17)) let choicesAll = concatMap (.choices) namedValues dynamic = \case TChoiceValue x -> isNothing x.static TChoiceRange r -> isNothing r.low.static || isNothing r.high.static _ -> False when (length choicesAll > 1) do forM_ [c | c <- choicesAll, dynamic c] \c -> case c of TChoiceValue x -> reportAt InvalidAggregate x.span "a choice that is not static must be the only choice of its aggregate" "not static" TChoiceRange r -> reportAt InvalidAggregate r.low.span "a choice that is not static must be the only choice of its aggregate" "not static" _ -> pure () mkExpr sp t (TAggregateNode (TArrayNamed namedValues)) (_, [TNamedValue {choices = [TChoiceOthers], value = v}]) -> mkExpr sp t (TAggregateNode (TArrayPositional TPositional {values, others = Just v})) _ -> do reportAt InvalidAggregate sp "an array aggregate is either positional (with an optional final `others`) or named" "mixed positional and named" errorExpr sp isIterated = \case A.IteratedAssocNode _ -> True _ -> False besideOthers = \case A.NamedAssocNode _ -> True A.IteratedAssocNode it | Just (A.DiscreteBounds _) <- rangeDomain it.iterator.domain -> isNothing it.iterator.filter && isNothing it.iterator.whileCondition && null it.iterator.alongside _ -> False mixedAggregate t a indexType sp assocs = do parts <- fmap catMaybes . forM assocs $ \case A.NamedAssocNode n -> do cs <- mapM (choice indexType) n.choices pure (Just (n.span, cs, Left n)) A.IteratedAssocNode it | Just (A.DiscreteBounds r) <- rangeDomain it.iterator.domain -> do rg <- rangeOf indexType r pure (Just (it.span, [TChoiceRange rg], Right it)) _ -> pure Nothing -- (the range the choices span: each bound static) boundsOf <- fmap concat . forM [c | (_, cs, _) <- parts, c <- cs] $ \case TChoiceValue x -> pure [(x, x)] TChoiceRange rg -> pure [(rg.low, rg.high)] TChoiceSubtype sub -> (\rg -> [(rg.low, rg.high)]) <$> maybe (wholeRange sub) pure sub.range TChoiceOthers -> pure [] let placeOf x = x.static >>= \case StaticInteger v -> Just v StaticEnum k -> Just (toInteger k) _ -> Nothing lows = [(v, x) | (x, _) <- boundsOf, Just v <- [placeOf x]] highs = [(v, x) | (_, x) <- boundsOf, Just v <- [placeOf x]] dynamic = [x | (l, h) <- boundsOf, x <- [l, h], isNothing (placeOf x)] forM_ (take 1 dynamic) \x -> reportAt InvalidAggregate x.span "a choice that is not static must be the only choice of its aggregate" "not static" case (sortOn fst lows, sortOn (negate . fst) highs) of ((_, lo) : _, (_, hi) : _) | null dynamic -> withScope BlockScope Nothing False do let hull = TRange {low = lo, high = hi} within rg = Subtype {base = indexType, range = Just rg, indices = [], discriminantValues = [], predicates = [], excludesNull = False, name = Nothing, digits = Nothing} index <- declare "Aggregate'Index" sp (EObject ObjectInfo {subtype = within hull, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}) at <- mkExpr sp indexType (TObject index) alternatives <- forM parts \(_, cs, part) -> case part of Left n -> do v <- case n.value of A.AssocExpr x -> expression (Expect a.component.base) x A.AssocBox -> boxValue n.span a.component pure TCaseValue {choices = cs, value = v} Right it -> withScope BlockScope Nothing False do let rg = case cs of [TChoiceRange r] -> r _ -> hull _ <- declare it.iterator.parameter.text it.iterator.parameter.span (EObject ObjectInfo {subtype = within rg, constant = True, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Just at}) v <- expression (Expect a.component.base) it.value pure TCaseValue {choices = cs, value = v} checkCoverage sp (within hull) [(s', cs) | (s', cs, _) <- parts] value <- mkExpr sp a.component.base (TCaseNode TCaseExpr {selector = at, alternatives}) let others = listToMaybe [x.value | x <- alternatives, TChoiceOthers `elem` x.choices] mkExpr sp t (TAggregateNode (TArrayIteratedNode TIterated {parameter = index, domain = hull, filter = Nothing, value, others})) _ -> errorExpr sp -- * Code strings (apl-variant.md 5) -- | APL text: read, each name classed by what it denotes here (an array or a function), and -- its mistakes reported at the glyph. Its meaning comes with T32b's next step. codeString :: Expect -> Span -> A.CodeString -> Sema TExpr codeString AnyType s c = do -- (where nothing expects a type, an array the text names is the likely one: its type is -- tried first, as an aggregate's would be given; Varc's `b.sorted()` is such a text) arrayTypes <- fmap (nub . catMaybes) . forM (namesInApl c) $ \n -> do ds <- lookupDirect n es <- mapM entity ds case [o | EObject o <- map (.kind) es] of o : _ -> fullKind o.subtype.base >>= \case KArray _ -> pure (Just o.subtype.base) _ -> pure Nothing [] -> pure Nothing case arrayTypes of [t] -> do (_, problems) <- trial (codeStringIn (Expect t) s c) if any Diagnostics.isError problems then codeStringIn AnyType s c else codeStringIn (Expect t) s c _ -> codeStringIn AnyType s c codeString expect s c = codeStringIn expect s c codeStringIn :: Expect -> Span -> A.CodeString -> Sema TExpr codeStringIn expect s c | Text.toCaseFold c.language /= "apl" = do reportAt MalformedCodeString s ("`" <> c.language <> "` is not a language Verada reads") "unknown language" errorExpr s | otherwise = do let names = namesInApl c classes <- fmap Map.fromList . forM names $ \n -> (n,) <$> classOf n -- (each host name's rank or overloads, each array's component type, and where the -- expected array's index starts) arrays <- fmap catMaybes . forM [n | (n, Just ArrayName) <- Map.toList classes] $ \n -> fmap (n,) <$> rankOf n functions <- forM [n | (n, Just FunctionName) <- Map.toList classes] \n -> (n,) <$> overloadRanks n elements <- fmap catMaybes . forM (map fst arrays) $ \n -> fmap (n,) <$> elementOf n first <- case expect of Expect t -> fullKind t >>= \case KArray a | ix : _ <- a.indices -> fmap fst <$> staticBounds ix _ -> pure Nothing AnyType -> pure Nothing selected <- asks (.aplScopeAt) let inspecting = maybe False (\at -> at.file == s.file && s.start <= at.start && at.start < s.end) selected scope <- if inspecting then lexicalScope else pure [] scopeContext <- if inspecting then do enclosing <- reverse <$> (ownerNames 16 =<< asks (.subprogram)) expectedType <- case expect of Expect t -> Just <$> typeName t; AnyType -> pure Nothing pure (Just ScopeContext {enclosing, expectedType}) else pure Nothing let hosts = Hosts {arrays, functions, elements = [(n, t) | (n, (t, _)) <- elements], floats = nub [t | (_, (t, True)) <- elements], first, scope, scopeContext} modify' \st -> st {codeStrings = (s, hosts) : st.codeStrings} originSelection <- asks (.aplOriginSelection) let ordinary = case readApl False hosts c of Left (sp, why) -> reportAt MalformedCodeString sp why "here" >> errorExpr s Right x -> case if isJust selected then AplTrace.generatedBudget x else Right () of Left why -> reportAt WorkbenchExpansionBudget s why "tooling expansion budget" >> errorExpr s Right () -> expression expect x unavailable why = modify' (\state -> state {aplOriginFailure = Just why}) >> ordinary case originSelection of Just (low, high) | inspecting -> if low < 0 || high <= low || high > ByteString.length (encodeUtf8 c.code) then unavailable "The selected origin is outside this APL payload." else case readAplWithOrigins False hosts c of Left (_, why) -> unavailable why Right traced -> do let sites = [site | site <- traced.sites, site.source.start - c.codeSpan.start == low, site.source.end - c.codeSpan.start == high] targets = [AplOriginTarget {generated = written, embedding = s, payloadBase = c.codeSpan.start, site} | site <- sites, Just written <- [AplTrace.originExpression traced site]] if null sites then unavailable "This source value has no separate element computation after lowering; it may be fused or unused." else if length (take 129 sites) > 128 then unavailable "This source value exceeds the 128 generated-site observation limit." else if length targets /= length sites then unavailable "A generated origin path cannot be resolved." else local (\context -> context {aplOriginTargets = Map.fromListWith (<>) [(target.generated.span, [target]) | target <- targets]}) (expression expect traced.expression) _ -> ordinary where ownerNames :: Int -> Maybe DeclId -> Sema [Text] ownerNames depth owner = case owner of Just d | depth > 0 -> do e <- entity d if e.parent == Nothing && e.name == "Standard" then pure [] else (e.name :) <$> ownerNames (depth - 1) e.parent _ -> pure [] lexicalScope = do visible <- visibleNames direct <- gets (concatMap (Map.keys . (.names)) . (.scopes)) scs <- gets (.scopes) typePackages <- catMaybes <$> mapM (\t -> do def <- typeDef t maybe (pure Nothing) (fmap (.parent) . entity) def.decl) (nub (concatMap (.usedAllTypes) scs)) imported <- concat <$> mapM (\p -> entity p >>= \e -> case e.kind of EPackage info -> do inside <- privateVisibleFor p exported <- mapM entity (info.visible <> if inside then info.private <> info.body else []) pure (map (.name) exported <> map fst info.renamings) _ -> pure []) (nub (typePackages <> concatMap (.usedPackages) scs)) let candidates = Map.elems (Map.fromList [(folded n, n) | n <- direct <> map fst visible <> imported]) catMaybes <$> mapM scopeName candidates scopeName n = do let bytes = encodeUtf8 n simple = case lexApl s.file bytes 0 (ByteString.length bytes) of Right [AplToken {kind = TokName actual}] -> actual == n _ -> False if not simple then pure Nothing else do ds <- lookupDirect n -- (ghost entities are for contracts, never an APL expression's: not offered) es <- filter (not . ghostEntity) <$> mapM entity ds case es of [e@Entity {kind = EObject o}] -> do r <- rankOf n t <- typeName o.subtype.base component <- elementOf n pure (Just ScopeName {name = n, kind = "value", typ = t, rank = r, overloads = [], element = component, declarations = [e.span]}) _ | any (isFunction . (.kind)) es -> do overloads <- filter (\ps -> length ps `elem` [1, 2]) <$> overloadRanks n let resultNames = [r.base | e <- es, ESubprogram info <- [e.kind], info.kind == Function, Just r <- [info.result]] results <- nub <$> mapM typeName resultNames pure (Just ScopeName {name = n, kind = "function", typ = Text.intercalate " / " results, rank = Nothing, overloads, element = Nothing, declarations = map (.span) es}) _ -> pure Nothing classOf n = do ds <- lookupDirect n es <- mapM entity ds pure case [e.kind | e <- es] of ks | any isFunction ks -> Just FunctionName k : _ | isObject k -> Just ArrayName _ -> Nothing isFunction = \case ESubprogram info -> info.kind == Function _ -> False ghostEntity e = case e.kind of ESubprogram info -> info.ghost EObject o -> o.ghost _ -> False isObject = \case EObject _ -> True _ -> False -- (each overload of a function: its parameters' ranks) overloadRanks n = do ds <- lookupDirect n es <- mapM entity ds -- (of the overloads whose results are scalars: each parameter's rank, and an array's -- first index, where static) overloads <- forM [info | ESubprogram info <- map (.kind) es, info.kind == Function] \info -> do scalarResult <- case info.result of Just r -> fullKind r.base >>= \case KArray _ -> pure False _ -> pure True Nothing -> pure False ps <- forM info.parameters \d -> entity d >>= \e -> case e.kind of EObject o -> fullKind o.subtype.base >>= \case KArray a -> do first <- case a.indices of ix : _ -> fmap fst <$> staticBounds ix [] -> pure Nothing pure (length a.indices, first) _ -> pure (0, Nothing) _ -> pure (0, Nothing) pure [ps | scalarResult] pure (concat overloads) -- (an object's rank: its array type's number of indices, 0 for a scalar) rankOf n = do ds <- lookupDirect n es <- mapM entity ds case [o | EObject o <- map (.kind) es] of o : _ -> fullKind o.subtype.base >>= \case KArray a -> pure (Just (length a.indices)) _ -> pure (Just 0) [] -> pure Nothing -- (an array object's component type's name, and whether it is a float type) elementOf n = do ds <- lookupDirect n es <- mapM entity ds case [o | EObject o <- map (.kind) es] of o : _ -> fullKind o.subtype.base >>= \case KArray a -> do t <- typeName a.component.base fullKind a.component.base >>= \case KReal _ -> pure (Just (t, True)) _ -> pure (Just (t, False)) _ -> pure Nothing [] -> pure Nothing -- * Conditional and quantified expressions (RM 4.5.7, 4.5.8) ifExpression :: Expect -> Span -> A.IfExpr -> Sema TExpr ifExpression expect s i = do st <- std first <- boolean i.condition later <- underCondition (Just first) (mapM (boolean . (.condition)) i.elsifs) let conditions = first : later valueExprs = i.thenValue : map (.value) i.elsifs -- (a branch after a static True condition, or of a static False one, is not evaluated; -- nor is the else branch after a static True) let truth c = toBool =<< c.static chosen = [maybe False not (truth c) || any ((== Just True) . truth) (take k conditions) | (k, c) <- zip [0 ..] conditions] elseSkipped = any ((== Just True) . truth) conditions (values, t) <- foldr (underCondition . Just) (branchValues expect (zip chosen valueExprs <> maybe [] (pure . (elseSkipped,)) i.elseValue)) conditions let branchValuesOnly = take (length valueExprs) values elseTyped = if isJust i.elseValue then headMaybe (drop (length valueExprs) values) else Nothing when (isNothing i.elseValue) do isBool <- isBooleanType t unless isBool do reportAt TypeMismatch s "an `if` expression without `else` must be Boolean" "add an `else` branch" mkExpr s (if isNothing i.elseValue then st.boolean else t) (TIfNode TIfExpr {branches = zipWith (\c v -> TBranch {condition = c, value = v}) conditions branchValuesOnly, elseValue = elseTyped}) -- | Check a part of an expression as statically unevaluated, when it is. statically :: Bool -> Sema a -> Sema a statically skip = if skip then local \ctx -> ctx {unevaluated = True} else id -- | Whether a short circuit's static left operand decides it, so that the right operand is -- not evaluated. decided :: A.BinaryOp -> TExpr -> Bool decided op l = case (op, toBool =<< l.static) of (A.OpAndThen, Just False) -> True (A.OpOrElse, Just True) -> True _ -> False -- | Whether a choice covers a static value (others: not by itself). covers :: StaticValue -> TChoice -> Sema Bool covers v = \case TChoiceValue x -> pure (x.static == Just v) TChoiceRange r -> pure (inside r.low.static r.high.static) TChoiceSubtype sub -> staticBounds sub <&> maybe True (\(lo, hi) -> maybe True (\p -> lo <= p && p <= hi) (position v)) TChoiceOthers -> pure False where position = \case StaticInteger n -> Just n StaticEnum p -> Just (toInteger p) _ -> Nothing inside lo hi = case (position =<< lo, position =<< hi, position v) of (Just a, Just b, Just p) -> a <= p && p <= b _ -> True -- | Values of several branches with one type: the expected type, or the first branch whose -- type is not universal. -- (each with whether it is statically unevaluated) branchValues :: Expect -> [(Bool, A.Expr)] -> Sema ([TExpr], TypeId) branchValues expect branches = do st <- std case expect of Expect t -> do vs <- mapM (\(skip, x) -> statically skip (expression (Expect t) x)) branches pure (vs, t) AnyType -> do -- (a raise expression takes the type of the other values: checked after them) first <- mapM (\(skip, x) -> if isRaise x then pure Nothing else Just <$> statically skip (expression AnyType x)) branches let typed = catMaybes first specific <- filterMs (fmap not . isUniversal . (.typeOf)) typed let t = maybe (maybe st.errorType (.typeOf) (headMaybe typed)) (.typeOf) (headMaybe specific) vs <- forM (zip branches first) \case ((skip, _), Just v) -> statically skip (conform (Expect t) v) ((skip, x), Nothing) -> statically skip (expression (Expect t) x) pure (vs, t) where isRaise x = case x.node of A.ERaise _ -> True A.EParen y -> isRaise y _ -> False filterMs p = foldM (\acc x -> p x >>= \keep -> pure (if keep then acc <> [x] else acc)) [] -- | What a case statement or expression selects by: the selector, or a record's only -- discriminant when the selector is a record with one (Varc's `match` of a data enum, by its -- kind); a translation writes the discriminant. caseSelector :: A.Expr -> Sema A.Expr caseSelector x = do (probe, _) <- trial (expression AnyType x) kind <- fullKind probe.typeOf case kind of -- (by its component's name: a derived type's discriminant renames its parent's, D248) KRecord r | [d] <- visibleDiscriminants r -> do modify' \state -> state {surfaceForms = ((x.span, "discriminant"), AsComponent d.name) : state.surfaceForms} pure A.Expr {span = x.span, node = A.ESelected A.Selected {prefix = x, selector = A.SelectIdentifier A.Identifier {span = x.span, text = d.name}}} _ -> pure x -- | A case selector, expected to be of any discrete type (RM 5.4(4)): of several possible -- types, the one discrete one (`case Zero is` with a `Zero` of Float and one of Short). selectorExpression :: A.Expr -> Sema TExpr selectorExpression x0 = do x <- caseSelector x0 ss <- shapes x discrete <- filterM isDiscrete (nub [t | Exactly t <- ss]) -- (shapes are a first guess, by the expression's place: the guess is kept only when it -- checks) fitting <- case discrete of [t] -> (\(_, problems) -> if null problems then Just t else Nothing) <$> trial (expression (Expect t) x) _ -> pure Nothing expression (maybe AnyType Expect fitting) x caseExpression :: Expect -> Span -> A.CaseExpr -> Sema TExpr caseExpression expect s c = 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) choices <- forM c.alternatives \alt -> mapM (choice selector.typeOf) alt.choices -- (with a static selector, only the alternative that covers it is evaluated) covering <- forM choices \cs -> case selector.static of Just v -> fmap or (mapM (covers v) cs) Nothing -> pure True let othersChosen = not (or [x | (x, cs) <- zip covering choices, TChoiceOthers `notElem` cs]) skipped = [not (if TChoiceOthers `elem` cs then othersChosen || x else x) | (x, cs) <- zip covering choices] (values, t) <- underCondition (Just selector) (branchValues expect (zip skipped (map (.value) c.alternatives))) selectorSubtype <- subtypeOfExpr selector checkCoverage s selectorSubtype (zip (map (fromMaybe s . choiceSpanOf) c.alternatives) choices) mkExpr s t (TCaseNode TCaseExpr {selector, alternatives = zipWith (\cs v -> TCaseValue {choices = cs, value = v}) choices values}) where choiceSpanOf alt = case alt.choices of A.ChoiceExpr x : _ -> Just x.span A.ChoiceRange r : _ -> Just r.span A.ChoiceOthers sp : _ -> Just sp [] -> Nothing quantified :: Expect -> Span -> A.Quantified -> Sema TExpr quantified expect s q = do st <- std domain <- iterationDomain q.iterator.domain -- sources in step (D192): ranges and arrays of one dimension, beside a range or such an -- array, the values quantified over ending with the shortest let inStep = case q.iterator.alongside of l : _ | isJust q.iterator.whileCondition -> Left l _ -> Right () unsupportedInStep l = notYetSupported l.parameter.span "sources in step in a quantified expression with `while`, over a container or over a multidimensional array" T25b stepped = do steps <- mapM stepSource q.iterator.alongside case [l | (l, x) <- zip q.iterator.alongside steps, isJust x.over || not (null x.further)] of l : _ -> unsupportedInStep l >> pure [] [] -> pure steps either unsupportedInStep pure inStep case domain of -- `for all E of A`: over A'Range, with E naming A (Index) A.OfContainer container -> do array <- expression AnyType container kind <- fullKind array.typeOf case kind of -- (a multidimensional array's: one quantifier for each dimension, the filter innermost) KArray a | not (null a.indices) -> withScope LoopScope Nothing False do indices <- forM (zip [1 ..] a.indices) \(k, ix) -> do range <- arrayRangeOf k array a ix index <- newEntity Entity {name = q.iterator.parameter.text <> "'Index" <> (if k == 1 then "" else "_" <> tshow k), span = q.iterator.parameter.span, parent = Nothing, kind = EObject ObjectInfo {subtype = ix, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}} ref <- mkExpr q.iterator.parameter.span ix.base (TObject index) pure (index, range, ref) element <- mkExpr q.iterator.parameter.span a.component.base (TIndexedNode TIndexed {prefix = array, indices = [ref | (_, _, ref) <- indices]}) _ <- declare q.iterator.parameter.text q.iterator.parameter.span (EObject ObjectInfo {subtype = a.component, constant = True, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Just element}) steps <- case (indices, q.iterator.alongside) of (_, []) -> pure [] ([_], _) -> stepped (_, l : _) -> unsupportedInStep l >> pure [] kept <- traverse boolean q.iterator.filter stopping <- traverse boolean q.iterator.whileCondition predicate <- underCondition Nothing (boolean q.predicate) let universal = q.quantifier == A.ForAll stop = stopping <&> \c -> TStop {condition = c, indices = [(index, range) | (index, range, _) <- indices], reverse = q.iterator.reverse} wrap (index, range, _) (inner, innerFilter, innerStop) = (TExpr {span = s, typeOf = st.boolean, static = Nothing, node = TQuantifiedNode TQuantified {universal, parameter = index, domain = range, filter = innerFilter, stop = innerStop, lockstep = steps, predicate = inner}}, Nothing, Nothing) (whole, _, _) = foldr wrap (predicate, kept, stop) indices conform expect whole KError -> errorExpr s _ -> iterationOf array.typeOf >>= \case -- over a container with `Iterable`: its cursors that have an element Just iteration -> withScope LoopScope Nothing False do forM_ (take 1 q.iterator.alongside) unsupportedInStep cursor <- newEntity Entity {name = q.iterator.parameter.text <> "'Cursor", span = q.iterator.parameter.span, parent = Nothing, kind = EObject ObjectInfo {subtype = unconstrained iteration.cursor, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}} element <- elementAt q.iterator.parameter.span array iteration cursor _ <- declare q.iterator.parameter.text q.iterator.parameter.span (EObject ObjectInfo {subtype = unconstrained iteration.elementType, constant = True, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Just element}) kept <- traverse boolean q.iterator.filter -- (a stop needs the elements before the one that ends the iteration: the -- cursors are integers visited in increasing order, which is proved, B5122) stop <- traverse boolean q.iterator.whileCondition predicate <- underCondition Nothing (boolean q.predicate) mkExpr s st.boolean (TCursorQuantifiedNode TCursorQuantified {universal = q.quantifier == A.ForAll, cursor, container = array, iteration, filter = kept, stop, predicate}) >>= conform expect Nothing -> do reportAt WrongKindOfEntity container.span "`for ... of` iterates over the components of an array, or the elements of a container whose type has `Iterable`" "not an array or an iterable container" errorExpr s A.InRange dr -> do (sub, range) <- discreteRange dr withScope LoopScope Nothing False do param <- declare q.iterator.parameter.text q.iterator.parameter.span (EObject ObjectInfo {subtype = sub, constant = True, mode = Nothing, value = Nothing, loopParameter = True, ghost = False, renames = Nothing}) steps <- stepped kept <- traverse boolean q.iterator.filter stopping <- traverse boolean q.iterator.whileCondition let stop = stopping <&> \c -> TStop {condition = c, indices = [(param, range)], reverse = q.iterator.reverse} predicate <- underCondition Nothing (boolean q.predicate) mkExpr s st.boolean (TQuantifiedNode TQuantified {universal = q.quantifier == A.ForAll, parameter = param, domain = range, filter = kept, stop, lockstep = steps, predicate}) >>= conform expect A.InNamed _ -> errorExpr s tshow :: (Show a) => a -> Text tshow = Text.pack . show -- | `T'Aft` (RM 3.5.10(5)): the digits after the point that the delta needs, at least one. fixedAft :: Rational -> Integer fixedAft d = go 1 where go n = if d * 10 ^ n >= 1 || n >= 30 then n else go (n + 1) -- | Whether this is a multiplication or division of two fixed-point values (RM 4.5.5(18)). fixedOperands :: A.Expr -> Sema Bool fixedOperands e = case e.node of A.EParen inner -> fixedOperands inner -- (`"*" (X, Y)` and `Standard."*" (X, Y)` are the product too) A.EApply ap | Just call <- operatorCall ap -> fixedOperands A.Expr {span = e.span, node = call} | A.ESelected A.Selected {selector = A.SelectOperator op} <- ap.prefix.node , Just call <- operatorCall A.Apply {prefix = A.Expr {span = ap.prefix.span, node = A.EString op}, arguments = ap.arguments, bracketed = ap.bracketed} -> fixedOperands A.Expr {span = e.span, node = call} A.EBinary b | b.op `elem` [A.OpMul, A.OpDiv] -> do let fixedShape = \case Exactly t -> isFixedKind <$> fullKind t _ -> pure False anyFixed x = shapes x >>= fmap or . mapM fixedShape st <- std let realLiteral x = elem (Exactly st.universalReal) <$> shapes x lf <- anyFixed b.left rf <- anyFixed b.right lr <- realLiteral b.left rr <- realLiteral b.right pure ((lf && (rf || rr)) || (lr && rf && b.op == A.OpMul)) _ -> pure False where isFixedKind = \case KFixed _ -> True _ -> False -- | Checking under one more condition (for `'Old`, RM 6.1.1(27)). underCondition :: Maybe TExpr -> Sema a -> Sema a underCondition c = local \ctx -> ctx {conditions = c : ctx.conditions} -- | Whether a value is known when the subprogram is entered (RM 6.1.1(20)): static, an `in` -- parameter or a constant, an `'Old`, or an operation of such values. knownOnEntry :: TExpr -> Sema Bool knownOnEntry e | isJust e.static = pure True | otherwise = case e.node of TOld _ -> pure True TObject d -> ( \x -> case x.kind of EObject o -> not o.loopParameter && (o.mode == Just ModeIn || (isNothing o.mode && o.constant)) _ -> False ) <$> entity d TBinaryNode b -> (&&) <$> knownOnEntry b.left <*> knownOnEntry b.right TUnaryNode u -> knownOnEntry u.operand TConversionNode c -> knownOnEntry c.operand TComponentNode c -> knownOnEntry c.prefix _ -> pure False -- | Whether an expression statically names an object: a whole object, or a component of -- one (no index, no dereference). staticallyNamesObject :: TExpr -> Bool staticallyNamesObject e = case e.node of TObject _ -> True TComponentNode c -> staticallyNamesObject c.prefix _ -> False -- | What the prefix of `'Old` uses that is known only when the postcondition is evaluated: -- a quantified variable bound outside the prefix, `'Result` or another `'Old`. oldPrefixProblem :: TExpr -> Sema (Maybe (Span, Text)) oldPrefixProblem prefix = go [] prefix where go bound e = case e.node of TResult _ -> pure (Just (e.span, "`'Result`")) TOld _ | e /= prefix -> pure (Just (e.span, "another `'Old`")) TObject d | d `notElem` bound -> do x <- entity d -- (a variable the postcondition binds is declared in it, after the subprogram's -- name; an enclosing loop's parameter, before it, is known on entry, D262) owner <- asks (.subprogram) >>= traverse entity let inContract' = case owner of Just o -> x.span.file /= o.span.file || x.span.start >= o.span.start Nothing -> True pure case x.kind of EObject o | o.loopParameter, inContract' -> Just (e.span, "`" <> x.name <> "`, which the postcondition binds") _ -> Nothing _ -> do let inner = case e.node of TQuantifiedNode q -> q.parameter : map (.position) q.lockstep <> bound TAggregateNode (TArrayIteratedNode it) -> it.parameter : bound _ -> bound firstJust <$> mapM (go inner) (subExpressions e) firstJust = \case Just x : _ -> Just x Nothing : rest -> firstJust rest [] -> Nothing -- | A declare expression (Ada 2022, RM 4.5.9): constants and object renamings, visible in its -- value only. declareExpression :: Expect -> Span -> A.DeclareExpr -> Sema TExpr declareExpression expect s d = withScope BlockScope Nothing False do declared <- concat <$> forM d.items \item -> do sub <- subtypeIndication item.subtype case item.value of A.Initialised v -> do unless item.constant do reportAt WrongKindOfEntity item.span "a declare expression declares constants and renamings, not variables" "a variable" value <- expression (Expect sub.base) v forM item.names \n -> do o <- declare n.text n.span (EObject ObjectInfo {subtype = sub, constant = True, mode = Nothing, value = value.static, loopParameter = False, ghost = False, renames = Nothing}) pure TDeclared {object = o, value, renames = False} A.Renames r -> do target <- expression (Expect sub.base) r unless (isObjectName target) do reportAt WrongKindOfEntity r.span "a renaming names an object or a component of one" "not a name" forM item.names \n -> do o <- declare n.text n.span (EObject ObjectInfo {subtype = sub, constant = True, mode = Nothing, value = Nothing, loopParameter = False, ghost = False, renames = Just target}) pure TDeclared {object = o, value = target, renames = True} body <- expression expect d.body pure TExpr {span = s, typeOf = body.typeOf, static = Nothing, node = TDeclareNode TDeclare {declared, value = body}} where isObjectName x = case x.node of TObject _ -> True TIndexedNode _ -> True TComponentNode _ -> True TDereference _ -> True TErrorExpr -> True _ -> False -- | The exception and message of a `raise` statement or expression. raising :: A.Expr -> Maybe A.Expr -> Sema (Maybe TRaising) raising name message = do st <- std msg <- traverse (expression (Expect st.string)) message denote name >>= \case Just (DException d) -> pure (Just TRaising {exception = d, message = msg}) Just DNone -> pure Nothing _ -> do reportAt WrongKindOfEntity name.span "`raise` needs an exception name" "not an exception" pure Nothing -- | A raise expression (Ada 2012): it has the type its context expects, and must be proved -- unreachable (language 5.5). raiseExpression :: Expect -> Span -> A.RaiseExpr -> Sema TExpr raiseExpression expect s r = do raised <- raising r.exception r.message case (expect, raised) of (Expect t, Just x) -> pure TExpr {span = s, typeOf = t, static = Nothing, node = TRaiseExpr x} (AnyType, Just _) -> do reportAt TypeMismatch s "the type of a raise expression comes from its context, which gives none here" "type not known" errorExpr s (_, Nothing) -> errorExpr s -- | The index range of an array value: its type's when the type is constrained, else the -- value's own bounds (`A'First .. A'Last`), as `for E of A` iterates. arrayRange :: TExpr -> ArrayType -> Subtype -> Sema TRange arrayRange = arrayRangeOf 1 -- | The range of one dimension of an array (1 the first). arrayRangeOf :: Int -> TExpr -> ArrayType -> Subtype -> Sema TRange arrayRangeOf dimension array a ix -- (a slice's are its own, not its type's) | a.constrained, not sliced = wholeRange ix | otherwise = pure TRange {low = bound AFirst, high = bound ALast} where sliced = case array.node of TSliceNode _ -> True _ -> False bound attr = TExpr {span = array.span, typeOf = ix.base, static = Nothing, node = TAttributeNode TAttribute {prefix = OfObject array, attribute = attr, dimension, arguments = []}} -- | `<>` for an array component: the default value of its subtype, which Verada requires to -- exist (a record whose components all have defaults), so that no component is left -- uninitialised. boxValue :: Span -> Subtype -> Sema TExpr boxValue s sub = do kind <- fullKind sub.base scalarDefault <- declaredDefault (.defaultValues) sub.base componentDefault <- declaredDefault (.defaultComponentValues) sub.base case kind of -- (a scalar with `Default_Value`, an array with `Default_Component_Value`: that value) _ | isJust scalarDefault || isJust componentDefault -> pure TExpr {span = s, typeOf = sub.base, static = Nothing, node = TDefaultValue} KRecord r | null r.discriminants, Just values <- mapM (.initial) r.components -> pure TExpr {span = s, typeOf = sub.base, static = Nothing, node = TAggregateNode (TRecordAggregate (map Just values))} KError -> errorExpr s _ -> do tn <- typeName sub.base reportAt InvalidAggregate s ("`<>` needs a default value, and `" <> tn <> "` has none") "give the type defaults for all its components, or write the value" errorExpr s -- | `F'Access` for an access-to-subprogram type (SPARK RM 3.10): a library-level subprogram -- whose profile is the type's (B1019 for a nested one). That its contract implies the type's -- is proved where it is lowered (B5114). subprogramAccess :: Span -> TypeId -> [DeclId] -> Sema TExpr subprogramAccess s t ds = do kind <- fullKind t case kind of KSubprogramAccess sa -> do profile <- entity sa.profile matching <- filterM (sameShape profile) ds case matching of d : _ -> do nested <- isNested d when nested do reportExcluded s "designating a subprogram declared in another subprogram is not in Verada" nestedSubprogramReplacement pure TExpr {span = s, typeOf = t, static = Nothing, node = TSubprogramAccess d} [] -> do reportAt WrongArguments s "no subprogram of this name has the profile of the access type" "profile differs" errorExpr s KError -> errorExpr s _ -> do reportAt TypeMismatch s "`'Access` of a subprogram gives a value of an access-to-subprogram type, which the context does not expect" "not an access-to-subprogram type" errorExpr s where -- the same parameter modes and types, and the same result type sameShape profile d = do e <- entity d case (profile.kind, e.kind) of (ESubprogram p, ESubprogram f) | p.kind == f.kind, length p.parameters == length f.parameters, fmap (.base) p.result == fmap (.base) f.result -> do ps <- mapM entity p.parameters fs <- mapM entity f.parameters pure (and [same a b | (a, b) <- zip ps fs]) _ -> pure False same a b = case (a.kind, b.kind) of (EObject x, EObject y) -> x.mode == y.mode && x.subtype.base == y.subtype.base _ -> False -- declared in a subprogram (its parents reach a subprogram before a package) isNested d = do e <- entity d case e.parent of Nothing -> pure False Just p -> do pe <- entity p case pe.kind of ESubprogram _ -> pure True _ -> pure False -- * Containers (T25) -- | How a container type is iterated, when it (or a type it derives from) has `Iterable`. iterationOf :: TypeId -> Sema (Maybe Iteration) iterationOf t = do known <- gets (.iterables) case lookup t known of Just i -> pure (Just i) Nothing -> do def <- typeDef t case def.parent of Just p | p /= t -> iterationOf p _ -> pure Nothing -- | `Element (C, Cursor)`: what the iteration variable names. elementAt :: Span -> TExpr -> Iteration -> DeclId -> Sema TExpr elementAt s container iteration cursor = do cursorRef <- mkExpr s iteration.cursor (TObject cursor) mkExpr s iteration.elementType (TCallNode TCall {callee = iteration.element, arguments = [container, cursorRef]}) -- | A call in prefix notation of an operator named by its symbol (RM 6.4, 6.6): @"=" (A, B)@, -- @"not" (X)@, @"-" (Right => D)@, its letters in any case; the operator applied to its -- operands (named ones by the predefined operators' names, @Left@ and @Right@), so it -- resolves as the operator does, user-defined or predefined. operatorCall :: A.Apply -> Maybe A.ExprNode operatorCall ap = case (ap.prefix.node, ap.bracketed) of -- (Varc's `operator==(a, b)` is a call, not an index) (A.EString symbol, bracketed) | bracketed /= Just True, Just operands <- traverse operand ap.arguments -> case ordered operands of [x] | Just op <- lookup (Text.toLower symbol) unaries -> Just (A.EUnary A.Unary {op, operand = x}) [l, r] | Just op <- lookup (Text.toLower symbol) binaries -> Just (A.EBinary A.Binary {op, left = l, right = r}) _ -> Nothing _ -> Nothing where operand a = case a.value of A.ArgExpr x -> Just (fmap A.foldedName a.formal, x) _ -> Nothing -- (`Right => R, Left => L` is `L op R`) ordered xs | all (isJust . fst) xs = [x | n <- ["left", "right"], (Just m, x) <- xs, m == n] <> [x | (Just m, x) <- xs, m `notElem` ["left", "right"]] | otherwise = map snd xs unaries = [(A.unaryOpText o, o) | o <- [minBound .. maxBound]] binaries = [(A.binaryOpText o, o) | o <- [minBound .. maxBound], o `notElem` [A.OpAndThen, A.OpOrElse]] -- | The names of an operator symbol's call, `"abs" (Right => X)`, are the formals of the -- operator chosen: `Left` and `Right` of a predefined one, a declared one's own (RM 6.4(4)). -- (A declared homograph hides the predefined operator, so a name only the predefined one has -- is not a call of either, ACATS B83032B.) namedOperands :: A.Apply -> TExpr -> Sema () namedOperands ap r = do formals <- case r.node of TCallNode c -> entity c.callee >>= \ce -> case ce.kind of ESubprogram info -> Just <$> mapM (fmap (folded . (.name)) . entity) info.parameters _ -> pure Nothing TErrorExpr -> pure Nothing _ -> pure (Just (if length ap.arguments == 1 then ["right"] else ["left", "right"])) forM_ formals \names -> forM_ [f | a <- ap.arguments, Just f <- [a.formal], A.foldedName f `notElem` names] \f -> reportAt WrongArguments f.span ("the operator chosen here has no parameter named `" <> f.text <> "`") "not a parameter of the operator" -- | The type a product of two decimal fixed-point values has exactly (RM 4.5.5(18)): a decimal -- type whose delta is the product of the operands' and whose digits their sum, when that is -- within Verada's 18 digits. exactProductType :: A.Expr -> Sema (Maybe TypeId) exactProductType e = case e.node of A.EParen inner -> exactProductType inner A.EBinary b | b.op == A.OpMul -> do (l, lp) <- trial (expression AnyType b.left) (r, rp) <- trial (expression AnyType b.right) lk <- fullKind l.typeOf rk <- fullKind r.typeOf case (lk, rk) of (KFixed lf, KFixed rf) | null lp , null rp , Just ld <- lf.decimalDigits , Just rd <- rf.decimalDigits , ld + rd <= 18 -> do let delta = lf.delta * rf.delta Just <$> newType TypeDef {name = "universal_fixed", decl = Nothing, parent = Nothing, kind = KFixed FixedType {delta, small = delta, decimalDigits = Just (ld + rd)}} _ -> pure Nothing _ -> pure Nothing -- | Whether values of a type are, or hold, access values (whose image would be an address). imageIsAddress :: TypeId -> Sema Bool imageIsAddress t = fullKind t >>= \case KSubprogramAccess _ -> pure True KClassWide root -> hasAccessPart root _ -> hasAccessPart t