File: Error.hs

package info (click to toggle)
elm-compiler 0.19.1-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,288 kB
  • sloc: haskell: 35,930; javascript: 5,404; sh: 82; xml: 27; python: 26; makefile: 11
file content (457 lines) | stat: -rw-r--r-- 11,723 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
{-# LANGUAGE GADTs, OverloadedStrings #-}
module Terminal.Error
  ( Error(..)
  , ArgError(..)
  , FlagError(..)
  , Expectation(..)
  , exitWithHelp
  , exitWithError
  , exitWithUnknown
  , exitWithOverview
  )
  where


import Data.Monoid ((<>))
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import GHC.IO.Handle (hIsTerminalDevice)
import qualified System.Environment as Env
import qualified System.Exit as Exit
import qualified System.FilePath as FP
import System.IO (hPutStrLn, stderr)
import qualified Text.PrettyPrint.ANSI.Leijen as P

import Reporting.Suggest as Suggest
import Terminal.Internal



-- ERROR


data Error where
  BadArgs :: [(CompleteArgs a, ArgError)] -> Error
  BadFlag :: FlagError -> Error


data ArgError
  = ArgMissing Expectation
  | ArgBad String Expectation
  | ArgExtras [String]


data FlagError where
  FlagWithValue :: String -> String -> FlagError
  FlagWithBadValue :: String -> String -> Expectation -> FlagError
  FlagWithNoValue :: String -> Expectation -> FlagError
  FlagUnknown :: String -> Flags a -> FlagError


data Expectation =
  Expectation
    { _type :: String
    , _examples :: IO [String]
    }



-- EXIT


exitSuccess :: [P.Doc] -> IO a
exitSuccess =
  exitWith Exit.ExitSuccess


exitFailure :: [P.Doc] -> IO a
exitFailure =
  exitWith (Exit.ExitFailure 1)


exitWith :: Exit.ExitCode -> [P.Doc] -> IO a
exitWith code docs =
  do  isTerminal <- hIsTerminalDevice stderr
      let adjust = if isTerminal then id else P.plain
      P.displayIO stderr $ P.renderPretty 1 80 $
        adjust $ P.vcat $ concatMap (\d -> [d,""]) docs
      hPutStrLn stderr ""
      Exit.exitWith code


getExeName :: IO String
getExeName =
  FP.takeFileName <$> Env.getProgName


stack :: [P.Doc] -> P.Doc
stack docs =
  P.vcat $ List.intersperse "" docs


reflow :: String -> P.Doc
reflow string =
  P.fillSep $ map P.text $ words string



-- HELP


exitWithHelp :: Maybe String -> String -> P.Doc -> Args args -> Flags flags -> IO a
exitWithHelp maybeCommand details example (Args args) flags =
  do  command <- toCommand maybeCommand
      exitSuccess $
        [ reflow details
        , P.indent 4 $ P.cyan $ P.vcat $ map (argsToDoc command) args
        , example
        ]
        ++
          case flagsToDocs flags [] of
            [] ->
              []

            docs@(_:_) ->
              [ "You can customize this command with the following flags:"
              , P.indent 4 $ stack docs
              ]


toCommand :: Maybe String -> IO String
toCommand maybeCommand =
  do  exeName <- getExeName
      return $
        case maybeCommand of
          Nothing ->
            exeName

          Just command ->
            exeName ++ " " ++ command


argsToDoc :: String -> CompleteArgs a -> P.Doc
argsToDoc command args =
  case args of
    Exactly required ->
      argsToDocHelp command required []

    Multiple required (Parser _ plural _ _ _) ->
      argsToDocHelp command required ["zero or more " ++ plural]

    Optional required (Parser singular _ _ _ _) ->
      argsToDocHelp command required ["optional " ++ singular]


argsToDocHelp :: String -> RequiredArgs a -> [String] -> P.Doc
argsToDocHelp command args names =
  case args of
    Done _ ->
      P.hang 4 $ P.hsep $ map P.text $
        command : map toToken names

    Required others (Parser singular _ _ _ _) ->
      argsToDocHelp command others (singular : names)


toToken :: String -> String
toToken string =
  "<" ++ map (\c -> if c == ' ' then '-' else c) string ++ ">"


flagsToDocs :: Flags flags -> [P.Doc] -> [P.Doc]
flagsToDocs flags docs =
  case flags of
    FDone _ ->
      docs

    FMore more flag ->
      let
        flagDoc =
          P.vcat $
            case flag of
              Flag name (Parser singular _ _ _ _) description ->
                [ P.dullcyan $ P.text $ "--" ++ name ++ "=" ++ toToken singular
                , P.indent 4 $ reflow description
                ]

              OnOff name description ->
                [ P.dullcyan $ P.text $ "--" ++ name
                , P.indent 4 $ reflow description
                ]
      in
      flagsToDocs more (flagDoc:docs)



-- OVERVIEW


exitWithOverview :: P.Doc -> P.Doc -> [Command] -> IO a
exitWithOverview intro outro commands =
  do  exeName <- getExeName
      exitSuccess
        [ intro
        , "The most common commands are:"
        , P.indent 4 $ stack $ Maybe.mapMaybe (toSummary exeName) commands
        , "There are a bunch of other commands as well though. Here is a full list:"
        , P.indent 4 $ P.dullcyan $ toCommandList exeName commands
        , "Adding the --help flag gives a bunch of additional details about each one."
        , outro
        ]


toSummary :: String -> Command -> Maybe P.Doc
toSummary exeName (Command name summary _ _ (Args args) _ _) =
  case summary of
    Uncommon ->
      Nothing

    Common summaryString ->
      Just $
        P.vcat
          [ P.cyan $ argsToDoc (exeName ++ " " ++ name) (head args)
          , P.indent 4 $ reflow summaryString
          ]


toCommandList :: String -> [Command] -> P.Doc
toCommandList exeName commands =
  let
    names = map toName commands
    width = maximum (map length names)

    toExample name =
      P.text $ exeName ++ " " ++ name ++ replicate (width - length name) ' ' ++ " --help"
  in
  P.vcat (map toExample names)



-- UNKNOWN


exitWithUnknown :: String -> [String] -> IO a
exitWithUnknown unknown knowns =
  let
    nearbyKnowns =
      takeWhile (\(r,_) -> r <= 3) (Suggest.rank unknown id knowns)

    suggestions =
      case map toGreen (map snd nearbyKnowns) of
        [] ->
          []

        [nearby] ->
          ["Try",nearby,"instead?"]

        [a,b] ->
          ["Try",a,"or",b,"instead?"]

        abcs@(_:_:_:_) ->
          ["Try"] ++ map (<> ",") (init abcs) ++ ["or",last abcs,"instead?"]
  in
  do  exeName <- getExeName
      exitFailure
        [ P.fillSep $ ["There","is","no",toRed unknown,"command."] ++ suggestions
        , reflow $ "Run `" ++ exeName ++ "` with no arguments to get more hints."
        ]



-- ERROR TO DOC


exitWithError :: Error -> IO a
exitWithError err =
  exitFailure =<<
    case err of
      BadFlag flagError ->
        flagErrorToDocs flagError

      BadArgs argErrors ->
        case argErrors of
          [] ->
            return
              [ reflow $ "I was not expecting any arguments for this command."
              , reflow $ "Try removing them?"
              ]

          [(_args, argError)] ->
            argErrorToDocs argError

          _:_:_ ->
            argErrorToDocs $ head $ List.sortOn toArgErrorRank (map snd argErrors)


toArgErrorRank :: ArgError -> Int -- lower is better
toArgErrorRank err =
  case err of
    ArgBad _ _   -> 0
    ArgMissing _ -> 1
    ArgExtras _  -> 2


toGreen :: String -> P.Doc
toGreen str =
  P.green (P.text str)


toYellow :: String -> P.Doc
toYellow str =
  P.yellow (P.text str)


toRed :: String -> P.Doc
toRed str =
  P.red (P.text str)



-- ARG ERROR TO DOC


argErrorToDocs :: ArgError -> IO [P.Doc]
argErrorToDocs argError =
  case argError of
    ArgMissing (Expectation tipe makeExamples) ->
      do  examples <- makeExamples
          return
            [ P.fillSep
                ["The","arguments","you","have","are","fine,","but","in","addition,","I","was"
                ,"expecting","a",toYellow (toToken tipe),"value.","For","example:"
                ]
            , P.indent 4 $ P.green $ P.vcat $ map P.text examples
            ]

    ArgBad string (Expectation tipe makeExamples) ->
      do  examples <- makeExamples
          return
            [ "I am having trouble with this argument:"
            , P.indent 4 $ toRed string
            , P.fillSep $
                ["It","is","supposed","to","be","a"
                ,toYellow (toToken tipe),"value,","like"
                ] ++ if length examples == 1 then ["this:"] else ["one","of","these:"]
            , P.indent 4 $ P.green $ P.vcat $ map P.text examples
            ]

    ArgExtras extras ->
      let
        (these, them) =
          case extras of
            [_] -> ("this argument", "it")
            _ -> ("these arguments", "them")
      in
      return
        [ reflow $ "I was not expecting " ++ these ++ ":"
        , P.indent 4 $ P.red $ P.vcat $ map P.text extras
        , reflow $ "Try removing " ++ them ++ "?"
        ]



-- FLAG ERROR TO DOC


flagErrorHelp :: String -> String -> [P.Doc] -> IO [P.Doc]
flagErrorHelp summary original explanation =
  return $
    [ reflow summary
    , P.indent 4 (toRed original)
    ]
    ++ explanation


flagErrorToDocs :: FlagError -> IO [P.Doc]
flagErrorToDocs flagError =
  case flagError of
    FlagWithValue flagName value ->
      flagErrorHelp
        "This on/off flag was given a value:"
        ("--" ++ flagName ++ "=" ++ value)
        [ "An on/off flag either exists or not. It cannot have an equals sign and value.\n\
          \Maybe you want this instead?"
        , P.indent 4 $ toGreen $ "--" ++ flagName
        ]

    FlagWithNoValue flagName (Expectation tipe makeExamples) ->
      do  examples <- makeExamples
          flagErrorHelp
            "This flag needs more information:"
            ("--" ++ flagName)
            [ P.fillSep ["It","needs","a",toYellow (toToken tipe),"like","this:"]
            , P.indent 4 $ P.vcat $ map toGreen $
                case take 4 examples of
                  [] ->
                    ["--" ++ flagName ++ "=" ++ toToken tipe]

                  _:_ ->
                    map (\example -> "--" ++ flagName ++ "=" ++ example) examples
            ]

    FlagWithBadValue flagName badValue (Expectation tipe makeExamples) ->
      do  examples <- makeExamples
          flagErrorHelp
            "This flag was given a bad value:"
            ("--" ++ flagName ++ "=" ++ badValue)
            [ P.fillSep $
                ["I","need","a","valid",toYellow (toToken tipe),"value.","For","example:"
                ]
            , P.indent 4 $ P.vcat $ map toGreen $
                case take 4 examples of
                  [] ->
                    ["--" ++ flagName ++ "=" ++ toToken tipe]

                  _:_ ->
                    map (\example -> "--" ++ flagName ++ "=" ++ example) examples
            ]

    FlagUnknown unknown flags ->
      flagErrorHelp
        "I do not recognize this flag:"
        unknown
        (
          let unknownName = takeWhile ('=' /=) (dropWhile ('-' ==) unknown) in
          case getNearbyFlags unknownName flags [] of
            [] ->
              []

            [thisOne] ->
              [ P.fillSep ["Maybe","you","want",P.green thisOne,"instead?"]
              ]

            suggestions ->
              [ P.fillSep ["Maybe","you","want","one","of","these","instead?"]
              , P.indent 4 $ P.green $ P.vcat suggestions
              ]
        )


getNearbyFlags :: String -> Flags a -> [(Int, String)] -> [P.Doc]
getNearbyFlags unknown flags unsortedFlags =
  case flags of
    FMore more flag ->
      getNearbyFlags unknown more (getNearbyFlagsHelp unknown flag : unsortedFlags)

    FDone _ ->
      map P.text $ map snd $ List.sortOn fst $
        case filter (\(d,_) -> d < 3) unsortedFlags of
          [] ->
            unsortedFlags

          nearbyUnsortedFlags ->
            nearbyUnsortedFlags


getNearbyFlagsHelp :: String -> Flag a -> (Int, String)
getNearbyFlagsHelp unknown flag =
  case flag of
    OnOff flagName _ ->
      ( Suggest.distance unknown flagName
      , "--" ++ flagName
      )

    Flag flagName (Parser singular _ _ _ _) _ ->
      ( Suggest.distance unknown flagName
      , "--" ++ flagName ++ "=" ++ toToken singular
      )