{-# LANGUAGE OverloadedStrings   #-}

-- | Source spans and locations.

module FP.Server.Spans where

import           FP.API.Types
import           FP.Server.Types

import           Data.Maybe
import           Data.Monoid
import           Data.Text (Text)
import qualified Data.Text                  as T
import           Prelude                    hiding (span)
import           System.FilePath

-- | Print either a useful span or a useless one.
printEitherSpan :: FilePath -> EitherSpan -> Text
printEitherSpan _ (TextSpan s) = s
printEitherSpan root (ProperSpan span') = printSourceSpan root span'

-- | Print a span as Main.hs:1:23
printSourceSpan :: FilePath -> SourceSpan -> Text
printSourceSpan root (SourceSpan source fromLine fromCol _toLine _toCol) =
  T.pack (root </> unEncFileNameString source) <> ":" <>
  T.pack (show fromLine) <> ":" <>
  T.pack (show fromCol)

toSpanType :: TypeInfo -> SpanType
toSpanType (TypeInfo (SourceSpan _ sl sc el ec) srcstr typs) =
  SpanType sl sc el ec srcstr typs

makeEitherLoc :: FilePath -> EitherSpan -> Maybe Loc
makeEitherLoc _ TextSpan{} = Nothing
makeEitherLoc root (ProperSpan span) = Just (makeLoc root span)

makeLoc :: FilePath -> SourceSpan -> Loc
makeLoc root (SourceSpan source fl fc tl tc) =
  Loc (root </> unEncFileNameString source)
      fl fc
      tl tc