-- | Pipelines (stream-combinators.md 3.4, D138) as Vada spells them: a reduction of a value -- sequence or of an array, a quantified expression or an aggregate. Front ends parse @'Reduce@ -- into a 'Pipeline' and print a pipeline back as Vada's form; Sema reads a pipeline through -- the same form. module Verada.Syntax.Pipeline ( extensionUses , extensionsAllowed , pipelineNode , pipelineOver , reducePipeline , scanExpansion , stageFunction , substituteName ) where import Verada.Source (Span) import Verada.Syntax.AST.Expr ( Aggregate (..) , AggregateContents (..) , Apply (..) , Argument (..) , ArgumentValue (..) , AttributeRef (..) , Binary (..) , BinaryOp (..) , CodeString (..) , ComponentAssoc (..) , Constraint (..) , Components (..) , DiscreteRange (..) , Expr (..) , ExprNode (..) , Identifier (..) , IteratedAssoc (..) , IterationDomain (..) , Iterator (..) , Lockstep (..) , PipeConsumer (..) , PipeSource (..) , PipeStage (..) , Pipeline (..) , Pragma (..) , Quantified (..) , Quantifier (..) , RangeExpr (..) , RangeSpec (..) , SubtypeIndication (..) , StageFn (..) , Unary (..) , UnaryOp (..) , foldedName ) import Verada.Syntax.AST.Unit (ContextItem (..)) import Verada.Syntax.Generic (everythingWith, everywhereOn) import Data.Data (Data, cast) import Data.Maybe (maybeToList) import Data.Text qualified as Text -- | @Prefix'Reduce (Reducer, Initial)@ as a pipeline: a value sequence's iterator is the -- source, its filter and value the stages; any other prefix is an array or container -- iterated whole. Nothing for other arguments (Sema reports them). reducePipeline :: Expr -> [Expr] -> Maybe Pipeline reducePipeline prefix = \case [reducer, initial] -> Just (pipelineOver prefix (ConsumeReduce reducer initial)) _ -> Nothing -- | A value sequence (or an array or container) and a consumer of it, as a pipeline. pipelineOver :: Expr -> PipeConsumer -> Pipeline pipelineOver prefix consumer = Pipeline {source, stages, consumer, piped = False} where (source, stages) = case prefix.node of EAggregate Aggregate {bracket = True, contents = PlainAggregate (Associations [IteratedAssocNode ia])} -> let it = ia.iterator fn = StageFn it.parameter in ( PipeSource {domain = it.domain, reverse = it.reverse, subtype = it.subtype, alongside = it.alongside} , [StageFilter (fn c) | Just c <- [it.filter]] <> [StageTakeWhile (fn c) | Just c <- [it.whileCondition]] <> [StageMap (fn ia.value)] ) _ -> (PipeSource {domain = OfContainer prefix, reverse = False, subtype = Nothing, alongside = []}, []) -- | A pipeline as Vada writes it, the expression it means: a reduction (an array or -- container with no stages reduced directly), a quantified expression or an aggregate, each -- over the first stage's parameter, whose filter is every filter's condition and whose value -- is every map, each applied to the stages before it. pipelineNode :: Span -> Pipeline -> ExprNode pipelineNode s p = case p.consumer of ConsumeReduce reducer initial -> EAttribute AttributeRef {prefix = reduced, designator = Identifier {span = s, text = "Reduce"}, arguments = [reducer, initial]} ConsumeCompensatedSum -> EAttribute AttributeRef {prefix = reduced, designator = Identifier {span = s, text = "Compensated_Sum"}, arguments = []} ConsumeLaneSum -> EAttribute AttributeRef {prefix = reduced, designator = Identifier {span = s, text = "Lane_Sum"}, arguments = []} ConsumeScan reducer initial -> EAttribute AttributeRef {prefix = reduced, designator = Identifier {span = s, text = "Scan"}, arguments = [reducer, initial]} -- (over sources in step, which quantified expressions do not take: the reduction by `and` -- or `or` of the predicate's values) ConsumeQuantified quantifier predicate | not (null p.source.alongside) -> let truth = Expr {span = s, node = ENameRef Identifier {span = s, text = if quantifier == ForAll then "True" else "False"}} each = Aggregate {bracket = True, contents = PlainAggregate (Associations [IteratedAssocNode IteratedAssoc {span = s, iterator, value = substituteName predicate.binder value predicate.body}])} in EAttribute AttributeRef {prefix = Expr {span = s, node = EAggregate each}, designator = Identifier {span = s, text = "Reduce"}, arguments = [Expr {span = s, node = EString (if quantifier == ForAll then "and" else "or")}, truth]} ConsumeQuantified quantifier predicate -> EQuantified Quantified {quantifier, iterator, predicate = substituteName predicate.binder value predicate.body} ConsumeCollect -> EAggregate sequence' where reduced = case (p.source, p.stages) of (PipeSource {domain = OfContainer a, reverse = False, subtype = Nothing, alongside = []}, []) -> a _ -> Expr {span = s, node = EAggregate sequence'} sequence' = Aggregate {bracket = True, contents = PlainAggregate (Associations [IteratedAssocNode IteratedAssoc {span = s, iterator, value}])} iterator = Iterator {parameter = binder, subtype = p.source.subtype, reverse = p.source.reverse, domain = p.source.domain, filter = condition, whileCondition = continuing, alongside = p.source.alongside} binder = case (p.stages, p.consumer) of (st : _, _) -> (stageFunction st).binder ([], ConsumeQuantified _ predicate) -> predicate.binder ([], _) -> Identifier {span = s, text = "E"} -- (Vada's `when` comes before its `while`: a filter after a `while` keeps every element -- the `while` stops at, so that the `while` still sees it, `when not W or else F`) (conditions, stops, value) = foldl step ([], [], Expr {span = binder.span, node = ENameRef binder}) p.stages step (cs, ws, v) = \case StageFilter f -> case conjoined ws of Nothing -> (cs <> [substituteName f.binder v f.body], ws, v) Just w -> (cs <> [Expr {span = s, node = EBinary Binary {op = OpOrElse, left = paren (Expr {span = s, node = EUnary Unary {op = OpNot, operand = paren w}}), right = paren (substituteName f.binder v f.body)}}], ws, v) StageTakeWhile f -> (cs, ws <> [substituteName f.binder v f.body], v) StageMap f -> (cs, ws, substituteName f.binder v f.body) conjoined = \case [] -> Nothing c : cs -> Just (foldl (\l r -> Expr {span = s, node = EBinary Binary {op = OpAndThen, left = l, right = r}}) c cs) condition = conjoined conditions continuing = conjoined stops paren e = Expr {span = s, node = EParen e} -- | Every use of a name replaced by an expression (a stage's parameter by the element it -- stands for). Stage functions are small expressions; a quantifier inside one that reuses -- the name is not told apart. substituteName :: Data a => Identifier -> Expr -> a -> a substituteName name by = everywhereOn \(e :: Expr) -> case e.node of ENameRef n | foldedName n == foldedName name -> by _ -> e -- | A stage's function, whatever the stage. stageFunction :: PipeStage -> StageFn stageFunction = \case StageFilter f -> f StageMap f -> f StageTakeWhile f -> f -- | Where a tree uses Verada's extensions of Ada's syntax (a `while` clause, 6.3), which Vada -- takes only under `pragma Extensions_Allowed (On)`. extensionUses :: Data a => a -> [Expr] extensionUses = everythingWith use where use :: forall d. (Data d) => d -> [Expr] use y | Just (it :: Iterator) <- cast y = maybeToList it.whileCondition | Just (StageTakeWhile f) <- cast y = [f.body] | Just (l :: Lockstep) <- cast y = [Expr {span = l.parameter.span, node = ENameRef l.parameter}] | Just (c :: CodeString) <- cast y = [Expr {span = c.codeSpan, node = ECodeString c}] | Just e@Expr {node = EPipeline Pipeline {consumer}} <- cast y, consumer `elem` [ConsumeCompensatedSum, ConsumeLaneSum] || scanning consumer = [e] -- (an array's own: Varc's `V::Compensated_Sum`) | Just e@Expr {node = EAttribute a} <- cast y, Text.toCaseFold a.designator.text `elem` ["compensated_sum", "lane_sum", "scan"] = [e] | otherwise = [] scanning = \case ConsumeScan _ _ -> True _ -> False -- | @Prefix'Scan (Reducer, Initial)@ as Ada 2022 writes it: an aggregate whose component at -- each position is the reduction of the prefix up to it (the elements of a slice of the -- array, or of the range up to the position; in reverse, of as many from the last). Nothing -- for a prefix with a `while`, sources in step, a filter in reverse order, or of more than one -- dimension's array (Sema reports it). The reductions are written each in full: the meaning, which a loop computes once. scanExpansion :: Span -> Expr -> Expr -> Expr -> Maybe Expr scanExpansion s prefix reducer initial = case prefix.node of EAggregate Aggregate {bracket = True, contents = PlainAggregate (Associations [IteratedAssocNode ia])} | Iterator {filter = Nothing, whileCondition = Nothing, alongside = [], reverse = False, subtype = Nothing} <- ia.iterator -> case ia.iterator.domain of OfContainer a -> Just (over (first a) (lastOf a) \i -> reduced (sequenceOf ia.iterator.parameter (OfContainer (slice a (first a) i)) ia.value)) InRange (DiscreteBounds r) -> Just (over r.low r.high \i -> reduced (sequenceOf ia.iterator.parameter (InRange (DiscreteBounds RangeExpr {span = s, low = r.low, high = i})) ia.value)) -- (`for I in T range L .. H`: the subtype kept, its range cut at the position) InRange (DiscreteSubtype ind) | Just (RangeConstraint (Bounds r)) <- ind.constraint -> let within hi = InRange (DiscreteSubtype ind {constraint = Just (RangeConstraint (Bounds RangeExpr {span = s, low = r.low, high = hi}))}) in Just (sequenceOf index (within r.high) (reduced (sequenceOf ia.iterator.parameter (within (at' (ENameRef index))) ia.value))) _ -> Nothing -- (a filtered sequence: the running values of the elements kept, one for each, at the -- positions the filter keeps) | Iterator {filter = Just keep, whileCondition = Nothing, alongside = [], reverse = False, subtype = Nothing} <- ia.iterator -> case ia.iterator.domain of OfContainer a -> let component i = at'' (EApply Apply {prefix = a, arguments = [Argument {span = s, formal = Nothing, value = ArgExpr i, reference = Nothing}], bracketed = Nothing}) in Just (overKept (first a) (lastOf a) (\i -> substituteName ia.iterator.parameter (component i) keep) \i -> reduced (filtered ia.iterator.parameter (OfContainer (slice a (first a) i)) keep ia.value)) InRange (DiscreteBounds r) -> Just (overKept r.low r.high (\i -> substituteName ia.iterator.parameter i keep) \i -> reduced (filtered ia.iterator.parameter (InRange (DiscreteBounds RangeExpr {span = s, low = r.low, high = i})) keep ia.value)) _ -> Nothing -- (in reverse: at each position, the reduction of as many elements from the last, walked -- backwards in step with the positions up to it, D192) | Iterator {filter = Nothing, whileCondition = Nothing, alongside = [], reverse = True, subtype = Nothing} <- ia.iterator -> case ia.iterator.domain of OfContainer a -> Just (over (first a) (lastOf a) \i -> reduced (backwards ia.iterator.parameter (OfContainer a) (first a) i ia.value)) InRange (DiscreteBounds r) -> Just (over r.low r.high \i -> reduced (backwards ia.iterator.parameter (InRange (DiscreteBounds r)) r.low i ia.value)) _ -> Nothing | otherwise -> Nothing EAggregate _ -> Nothing _ -> Just (over (first prefix) (lastOf prefix) \i -> reduced (slice prefix (first prefix) i)) where at' node = Expr {span = s, node} attr a d = at' (EAttribute AttributeRef {prefix = a, designator = Identifier {span = s, text = d}, arguments = []}) first a = attr a "First" lastOf a = attr a "Last" slice a lo hi = at' (EApply Apply {prefix = a, arguments = [Argument {span = s, formal = Nothing, value = ArgRange RangeExpr {span = s, low = lo, high = hi}, reference = Nothing}], bracketed = Nothing}) reduced x = at' (EAttribute AttributeRef {prefix = x, designator = Identifier {span = s, text = "Reduce"}, arguments = [reducer, initial]}) sequenceOf parameter domain value = at' (EAggregate Aggregate {bracket = True, contents = PlainAggregate (Associations [IteratedAssocNode IteratedAssoc {span = s, iterator = Iterator {parameter, subtype = Nothing, reverse = False, domain, filter = Nothing, whileCondition = Nothing, alongside = []}, value}])}) index = Identifier {span = s, text = "Scan_Index"} backwards parameter domain lo hi value = at' (EAggregate Aggregate {bracket = True, contents = PlainAggregate (Associations [IteratedAssocNode IteratedAssoc {span = s, iterator = Iterator {parameter, subtype = Nothing, reverse = True, domain, filter = Nothing, whileCondition = Nothing, alongside = [Lockstep {parameter = Identifier {span = s, text = "Scan_Step"}, domain = InRange (DiscreteBounds RangeExpr {span = s, low = lo, high = hi})}]}, value}])}) over lo hi f = sequenceOf index (InRange (DiscreteBounds RangeExpr {span = s, low = lo, high = hi})) (f (at' (ENameRef index))) at'' node = Expr {span = s, node} filtered parameter domain keep value = at' (EAggregate Aggregate {bracket = True, contents = PlainAggregate (Associations [IteratedAssocNode IteratedAssoc {span = s, iterator = Iterator {parameter, subtype = Nothing, reverse = False, domain, filter = Just keep, whileCondition = Nothing, alongside = []}, value}])}) overKept lo hi keepAt f = let i = at' (ENameRef index) in at' (EAggregate Aggregate {bracket = True, contents = PlainAggregate (Associations [IteratedAssocNode IteratedAssoc {span = s, iterator = Iterator {parameter = index, subtype = Nothing, reverse = False, domain = InRange (DiscreteBounds RangeExpr {span = s, low = lo, high = hi}), filter = Just (keepAt i), whileCondition = Nothing, alongside = []}, value = f i}])}) -- | Whether a context has `pragma Extensions_Allowed (On)`. extensionsAllowed :: [ContextItem] -> Bool extensionsAllowed context = or [Text.toCaseFold p.name.text == "extensions_allowed" && any on p.arguments | ContextPragma p <- context] where on a = case a.value of ArgExpr Expr {node = ENameRef i} -> Text.toCaseFold i.text == "on" _ -> False