packages feed

hydra-kernel-0.18.1: src/main/haskell/Hydra/Core/Positions.hs

-- Note: this is an automatically generated file. Do not edit.

-- | Source positions: reserved span annotations on parsed terms, resolution of a SubtermPath to a span, and conversion of codepoint offsets to (line, column) positions.

module Hydra.Core.Positions where

import qualified Hydra.Core.Annotations as Annotations
import qualified Hydra.Core.Overlay.Haskell.Lib.Eithers as Eithers
import qualified Hydra.Core.Overlay.Haskell.Lib.Equality as Equality
import qualified Hydra.Core.Overlay.Haskell.Lib.Lists as Lists
import qualified Hydra.Core.Overlay.Haskell.Lib.Literals as Literals
import qualified Hydra.Core.Overlay.Haskell.Lib.Logic as Logic
import qualified Hydra.Core.Overlay.Haskell.Lib.Maps as Maps
import qualified Hydra.Core.Overlay.Haskell.Lib.Math as Math
import qualified Hydra.Core.Overlay.Haskell.Lib.Optionals as Optionals
import qualified Hydra.Core.Overlay.Haskell.Lib.Ordering as Ordering
import qualified Hydra.Core.Overlay.Haskell.Lib.Pairs as Pairs
import qualified Hydra.Core.Overlay.Haskell.Lib.Strings as Strings
import qualified Hydra.Core.Model as Model
import qualified Hydra.Core.Parsing as Parsing
import qualified Hydra.Core.Paths as Paths
import qualified Hydra.Core.Rewriting as Rewriting
import Prelude hiding  (Enum, Ordering, decodeFloat, encodeFloat, fail, lines, map, pure, sum, unlines)
import qualified Data.Scientific as Sci
import Data.Void

-- | Annotate an application term with the span running from the start of its function to the end of its argument, when both have spans; otherwise leave it unannotated
annotateApplicationSpan :: Model.Term -> Model.Term -> Model.Term -> Model.Term
annotateApplicationSpan function argument application =
    Optionals.match (termSpan function) application (\fs -> Optionals.match (termSpan argument) application (\as -> annotateSpan (Parsing.SourceSpan {
      Parsing.sourceSpanStart = (Parsing.sourceSpanStart fs),
      Parsing.sourceSpanEnd = (Parsing.sourceSpanEnd as)}) application))

-- | Wrap a term in a layer whose only annotation is the reserved span key. This is surface trivia, like comments: it is exempt from the round-trip contract and is removed by stripSpans.
annotateSpan :: Parsing.SourceSpan -> Model.Term -> Model.Term
annotateSpan span term =
    Model.TermAnnotated (Model.AnnotatedTerm {
      Model.annotatedTermBody = term,
      Model.annotatedTermAnnotation = (Annotations.wrapAnnotationMap (Maps.singleton keySourceSpan (spanToTerm span)))})

-- | Format a parse failure as 'line:col: message' (1-based line/column), given the full input text, the codepoint offset of the failure, and the raw error message
formatParseFailure :: String -> Int -> String -> String
formatParseFailure text offset message =

      let pos = offsetToPosition text offset
          line1 = Math.add (Parsing.sourcePositionLine pos) 1
          col1 = Math.add (Parsing.sourcePositionColumn pos) 1
      in (Strings.concat [
        Literals.printInt32 line1,
        ":",
        (Literals.printInt32 col1),
        ": ",
        message])

-- | Reserved annotation key for source spans recorded by the textual parser
keySourceSpan :: Model.Name
keySourceSpan = Model.Name "sourceSpan"

-- | Convert a codepoint offset within a text into a zero-based line and a zero-based column counted in UTF-16 code units (the Language Server Protocol's convention). Lines end at LF, CR, or CR LF; an offset beyond the end of the text is clamped to the end.
offsetToPosition :: String -> Int -> Parsing.SourcePosition
offsetToPosition text offset =

      let all = Strings.toList text
          cps = Lists.take offset all
          nexts = Lists.concat2 (Lists.drop 1 all) [
                0]
          step =
                  \acc -> \cn ->
                    let c = Pairs.first cn
                        next = Pairs.second cn
                        line = Pairs.first acc
                        col = Pairs.second acc
                        newline = Logic.or (Equality.equal c 10) (Logic.and (Equality.equal c 13) (Logic.not (Equality.equal next 10)))
                        width = Logic.ifElse (Ordering.gte c 65536) 2 1
                    in (Logic.ifElse newline (Math.add line 1, 0) (line, (Math.add col width)))
          end = Lists.foldl step (0, 0) (Lists.zip cps nexts)
      in Parsing.SourcePosition {
        Parsing.sourcePositionLine = (Pairs.first end),
        Parsing.sourcePositionColumn = (Pairs.second end)}

-- | Remove span-only annotation layers from the top of a term, leaving the term itself
peelSpans :: Model.Term -> Model.Term
peelSpans term = Optionals.match (spanLayer term) term (\layer -> peelSpans (Pairs.second layer))

-- | Resolve a subterm path (as carried by type-checking errors, computed on the span-free term) against a span-annotated term, returning the span of the node it reaches. If the node itself has no span, the span of its nearest enclosing node that has one is returned; if the path cannot be followed, the span of the last node reached.
spanAtPath :: Paths.SubtermPath -> Model.Term -> Maybe Parsing.SourceSpan
spanAtPath path term = spanAtSteps (Paths.unSubtermPath path) term

-- | Resolve a list of subterm steps against a span-annotated term; see spanAtPath
spanAtSteps :: [Paths.SubtermStep] -> Model.Term -> Maybe Parsing.SourceSpan
spanAtSteps steps term =

      let outer = termSpan term
      in (Optionals.match (Lists.uncons steps) outer (\uc -> Optionals.match (subtermAtStep (Pairs.first uc) (peelSpans term)) outer (\child -> Optionals.match (spanAtSteps (Pairs.second uc) child) outer (\found -> Just found))))

-- | Decode a span from its annotation value, a pair of int32 literals (start, end)
spanFromTerm :: Model.Term -> Maybe Parsing.SourceSpan
spanFromTerm term =

      let int32Of =
              \t -> case t of
                Model.TermLiteral v0 -> case v0 of
                  Model.LiteralInteger v1 -> case v1 of
                    Model.IntegerValueInt32 v2 -> Just v2
                    _ -> Nothing
                  _ -> Nothing
                _ -> Nothing
      in case term of
        Model.TermPair v0 -> Optionals.bind (int32Of (Pairs.first v0)) (\s -> Optionals.map (\e -> Parsing.SourceSpan {
          Parsing.sourceSpanStart = s,
          Parsing.sourceSpanEnd = e}) (int32Of (Pairs.second v0)))
        _ -> Nothing

-- | If a term is a span-only annotation layer (see annotateSpan), return its span and the term it wraps
spanLayer :: Model.Term -> Maybe (Parsing.SourceSpan, Model.Term)
spanLayer term =
    case term of
      Model.TermAnnotated v0 ->
        let anns = Annotations.getAnnotationMap (Model.annotatedTermAnnotation v0)
        in (Logic.ifElse (Equality.equal (Maps.size anns) 1) (Optionals.bind (Maps.lookup keySourceSpan anns) (\v -> Optionals.map (\sp -> (sp, (Model.annotatedTermBody v0))) (spanFromTerm v))) Nothing)
      _ -> Nothing

-- | Encode a span as an annotation value: a pair of int32 literals (start, end)
spanToTerm :: Parsing.SourceSpan -> Model.Term
spanToTerm span =

      let int32Term = \n -> Model.TermLiteral (Model.LiteralInteger (Model.IntegerValueInt32 n))
      in (Model.TermPair (int32Term (Parsing.sourceSpanStart span), (int32Term (Parsing.sourceSpanEnd span))))

-- | Remove every span-only annotation layer from a term, including those inside user annotation payloads. Applied to a freshly parsed term, this yields exactly the term that parsing without spans produces.
stripSpans :: Model.Term -> Model.Term
stripSpans term =
    Rewriting.rewriteTerm (\recurse -> \t -> Optionals.match (spanLayer t) (case t of
      Model.TermAnnotated v0 -> Model.TermAnnotated (Model.AnnotatedTerm {
        Model.annotatedTermBody = (stripSpans (Model.annotatedTermBody v0)),
        Model.annotatedTermAnnotation = (stripSpans (Model.annotatedTermAnnotation v0))})
      _ -> recurse t) (\layer -> stripSpans (Pairs.second layer))) term

-- | Follow a single subterm step from a (span-free) term to the immediate subterm it names, if the term has that shape. Map-entry and set-element steps depend on a term ordering and are not resolved.
subtermAtStep :: Paths.SubtermStep -> Model.Term -> Maybe Model.Term
subtermAtStep step term =

      let fieldTerm =
              \fname -> \fields -> Optionals.map (\f -> Model.fieldTerm f) (Lists.find (\f -> Equality.equal (Model.fieldName f) fname) fields)
      in case step of
        Paths.SubtermStepAnnotatedAnnotation -> case term of
          Model.TermAnnotated v1 -> Just (Model.annotatedTermAnnotation v1)
          _ -> Nothing
        Paths.SubtermStepAnnotatedBody -> case term of
          Model.TermAnnotated v1 -> Just (Model.annotatedTermBody v1)
          _ -> Nothing
        Paths.SubtermStepApplicationArgument -> case term of
          Model.TermApplication v1 -> Just (Model.applicationArgument v1)
          _ -> Nothing
        Paths.SubtermStepApplicationFunction -> case term of
          Model.TermApplication v1 -> Just (Model.applicationFunction v1)
          _ -> Nothing
        Paths.SubtermStepCasesCase v0 -> case term of
          Model.TermCases v1 -> Optionals.map (\a -> Model.caseAlternativeHandler a) (Lists.find (\a -> Equality.equal (Model.caseAlternativeName a) v0) (Model.caseStatementCases v1))
          _ -> Nothing
        Paths.SubtermStepCasesDefault -> case term of
          Model.TermCases v1 -> Model.caseStatementDefault v1
          _ -> Nothing
        Paths.SubtermStepEitherLeft -> case term of
          Model.TermEither v1 -> Eithers.either (\l -> Just l) (\r -> Nothing) v1
          _ -> Nothing
        Paths.SubtermStepEitherRight -> case term of
          Model.TermEither v1 -> Eithers.either (\l -> Nothing) (\r -> Just r) v1
          _ -> Nothing
        Paths.SubtermStepInjectField v0 -> case term of
          Model.TermInject v1 -> fieldTerm v0 [
            Model.injectionField v1]
          _ -> Nothing
        Paths.SubtermStepLambdaBody -> case term of
          Model.TermLambda v1 -> Just (Model.lambdaBody v1)
          _ -> Nothing
        Paths.SubtermStepLetBinding v0 -> case term of
          Model.TermLet v1 -> Optionals.map (\b -> Model.bindingTerm b) (Lists.find (\b -> Equality.equal (Model.bindingName b) v0) (Model.letBindings v1))
          _ -> Nothing
        Paths.SubtermStepLetBody -> case term of
          Model.TermLet v1 -> Just (Model.letBody v1)
          _ -> Nothing
        Paths.SubtermStepListElement v0 -> case term of
          Model.TermList v1 -> Lists.at v0 v1
          _ -> Nothing
        Paths.SubtermStepOptionalGiven -> case term of
          Model.TermOptional v1 -> v1
          _ -> Nothing
        Paths.SubtermStepPairFirst -> case term of
          Model.TermPair v1 -> Just (Pairs.first v1)
          _ -> Nothing
        Paths.SubtermStepPairSecond -> case term of
          Model.TermPair v1 -> Just (Pairs.second v1)
          _ -> Nothing
        Paths.SubtermStepRecordField v0 -> case term of
          Model.TermRecord v1 -> fieldTerm v0 (Model.recordFields v1)
          _ -> Nothing
        Paths.SubtermStepTypeApplicationBody -> case term of
          Model.TermTypeApplication v1 -> Just (Model.typeApplicationTermBody v1)
          _ -> Nothing
        Paths.SubtermStepTypeLambdaBody -> case term of
          Model.TermTypeLambda v1 -> Just (Model.typeLambdaBody v1)
          _ -> Nothing
        Paths.SubtermStepWrapBody -> case term of
          Model.TermWrap v1 -> Just (Model.wrappedTermBody v1)
          _ -> Nothing
        _ -> Nothing

-- | The source span recorded on a term by the parser, if the term's outermost layer is a span annotation
termSpan :: Model.Term -> Maybe Parsing.SourceSpan
termSpan term = Optionals.map (\layer -> Pairs.first layer) (spanLayer term)