Add line numbers to error messages (#919)

Fixes https://github.com/dhall-lang/dhall-haskell/issues/905

For example, this file:

```haskell
[ 1
, 2
, 3
, Bool

+ 1
]
```

... now produces this error message:

```
Use "dhall --explain" for detailed errors

↳ ./example.dhall

Error: ❰+❱ only works on ❰Natural❱s

4:   Bool
5:
6:
7:
8:
9: + 1

/Users/gabriel/proj/dhall-haskell/dhall/example.dhall:4:3
```
This commit is contained in:
Gabriel Gonzalez 2019-04-30 15:31:18 -07:00 committed by GitHub
parent d69ac6599f
commit 6d510ee2b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 4 deletions

View File

@ -38,6 +38,7 @@ import qualified Text.Megaparsec.Char
import qualified Text.Parser.Char
import qualified Text.Parser.Combinators
import qualified Text.Parser.Token.Style
import qualified Text.Printf
-- | Source code extract
data Src = Src !Text.Megaparsec.SourcePos !Text.Megaparsec.SourcePos Text
@ -68,7 +69,7 @@ laxSrcEq (Src p q _) (Src p' q' _) = eq p p' && eq q q'
instance Pretty Src where
pretty (Src begin _ text) =
pretty (Dhall.Util.snip (prefix <> text))
pretty (Dhall.Util.snip numberedLines)
<> "\n"
<> pretty (Text.Megaparsec.sourcePosPretty begin)
where
@ -76,6 +77,28 @@ instance Pretty Src where
where
n = Text.Megaparsec.unPos (Text.Megaparsec.sourceColumn begin)
ls = Data.Text.lines (prefix <> text)
numberOfLines = length ls
minimumNumber =
Text.Megaparsec.unPos (Text.Megaparsec.sourceLine begin)
maximumNumber = minimumNumber + numberOfLines - 1
numberWidth :: Int
numberWidth =
truncate (logBase (10 :: Double) (fromIntegral maximumNumber)) + 1
adapt n line = Data.Text.pack outputString
where
inputString = Data.Text.unpack line
outputString =
Text.Printf.printf ("%" <> show numberWidth <> "d: %s") n inputString
numberedLines = Data.Text.unlines (zipWith adapt [minimumNumber..] ls)
{-| A `Parser` that is almost identical to
@"Text.Megaparsec".`Text.Megaparsec.Parsec`@ except treating Haskell-style
comments as whitespace

View File

@ -314,7 +314,7 @@ import Dhall
-- - Bool
-- + Natural
-- ...
-- 1 : Bool
-- 1: 1 : Bool
-- ...
-- (input):1:1
-- ...
@ -514,7 +514,8 @@ import Dhall
-- *** Exception:
-- ...Error...: An empty list requires a type annotation
-- ...
-- []
-- 1: []
-- ...
-- (input):1:1
--
-- Also, list elements must all have the same type. You will get an error if
@ -527,7 +528,7 @@ import Dhall
-- - Natural
-- + Bool
-- ...
-- True
-- 1: True
-- ...
-- (input):1:5
-- ...