File: Main.hs

package info (click to toggle)
haskell-hsyaml 0.2.1.5-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 484 kB
  • sloc: haskell: 4,042; makefile: 2; sh: 1
file content (777 lines) | stat: -rw-r--r-- 30,060 bytes parent folder | download | duplicates (2)
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
{-# LANGUAGE LambdaCase        #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards   #-}

-- |
-- Copyright: © Herbert Valerio Riedel 2018
-- SPDX-License-Identifier: GPL-2.0-or-later
--
module Main where

import           Control.Monad
import           Control.Monad.Identity
import qualified Data.ByteString.Char8      as BS
import qualified Data.ByteString.Lazy.Char8 as BS.L
import           Data.Int                   (Int64)
import           Data.List                  (groupBy)
import           Data.Maybe
import           System.Directory
import           System.Environment
import           System.Exit
import           System.FilePath
import           System.IO
import           Text.Printf                (printf)
import           Text.Read

import qualified Data.Aeson.Micro           as J
import           Data.Map                   (Map)
import qualified Data.Map                   as Map
import           Data.Text                  (Text)
import qualified Data.Text                  as T
import qualified Data.Text.Encoding         as T
import qualified Data.Text.IO               as T

import           Data.YAML                  as Y
import           Data.YAML.Event            as YE
import           Data.YAML.Schema           as Y
import qualified Data.YAML.Token            as YT

import qualified TML

main :: IO ()
main = do
  args <- getArgs

  case args of
    ("yaml2event":args')
      | null args' -> cmdYaml2Event
      | otherwise -> do
          hPutStrLn stderr "unexpected arguments passed to yaml2event sub-command"
          exitFailure

    ("yaml2event-pos":args')
      | null args' -> cmdYaml2EventPos
      | otherwise -> do
          hPutStrLn stderr "unexpected arguments passed to yaml2event sub-command"
          exitFailure

    ("yaml2yaml-validate":args')
      | null args' -> cmdYaml2YamlVal
      | otherwise -> do
          hPutStrLn stderr "unexpected arguments passed to check sub-command"
          exitFailure

    ("yaml2event0":args')
      | null args' -> cmdYaml2Event0
      | otherwise -> do
          hPutStrLn stderr "unexpected arguments passed to yaml2event0 sub-command"
          exitFailure

    ("yaml2token":args')
      | null args' -> cmdYaml2Token
      | otherwise -> do
          hPutStrLn stderr "unexpected arguments passed to yaml2token sub-command"
          exitFailure

    ("yaml2token0":args')
      | null args' -> cmdYaml2Token0
      | otherwise -> do
          hPutStrLn stderr "unexpected arguments passed to yaml2token0 sub-command"
          exitFailure

    ("yaml2json":args')
      | null args' -> cmdYaml2Json
      | otherwise -> do
          hPutStrLn stderr "unexpected arguments passed to yaml2json sub-command"
          exitFailure

    ("yaml2yaml":args')
      | null args' -> cmdYaml2Yaml
      | otherwise -> do
          hPutStrLn stderr "unexpected arguments passed to yaml2yaml sub-command"
          exitFailure

    ("yaml2yaml-":args')
      | null args' -> cmdYaml2Yaml'
      | otherwise -> do
          hPutStrLn stderr "unexpected arguments passed to yaml2yaml- sub-command"
          exitFailure

    ("yaml2yaml-dump": args')
      | null args' -> cmdDumpYAML
      | otherwise  -> do
          hPutStrLn stderr "unexpected arguments passed to yaml2event sub-command"
          exitFailure

    ("yaml2node":args')
      | null args' -> cmdPrintNode
      | otherwise -> do
          hPutStrLn stderr "unexpected arguments passed to yaml2event sub-command"
          exitFailure

    ("run-tml":args') -> cmdRunTml args'

    ("run-tml2":args') -> cmdRunTml' args' -- Temp function for check comment round-trip

    ("testml-compiler":args') -> cmdTestmlCompiler args'

    _ -> do
      hPutStrLn stderr "usage: yaml-test <command> [<args>]"
      hPutStrLn stderr ""
      hPutStrLn stderr "Commands:"
      hPutStrLn stderr ""
      hPutStrLn stderr "  yaml2token          reads YAML stream from STDIN and dumps tokens to STDOUT"
      hPutStrLn stderr "  yaml2token0         reads YAML stream from STDIN and prints count of tokens to STDOUT"
      hPutStrLn stderr "  yaml2event          reads YAML stream from STDIN and dumps events to STDOUT"
      hPutStrLn stderr "  yaml2event0         reads YAML stream from STDIN and prints count of events to STDOUT"
      hPutStrLn stderr "  yaml2event-pos      reads YAML stream from STDIN and dumps events & position to STDOUT"
      hPutStrLn stderr "  yaml2json           reads YAML stream from STDIN and dumps JSON to STDOUT"
      hPutStrLn stderr "  yaml2yaml           reads YAML stream from STDIN and dumps YAML to STDOUT (non-streaming version)"
      hPutStrLn stderr "  yaml2yaml-          reads YAML stream from STDIN and dumps YAML to STDOUT (streaming version)"
      hPutStrLn stderr "  yaml2yaml-validate  reads YAML stream from STDIN and dumps YAML to STDOUT and also outputs the no. of differences and differences after a round-trip"
      hPutStrLn stderr "  yaml2node           reads YAML stream from STDIN and dumps YAML Nodes to STDOUT"
      hPutStrLn stderr "  yaml2yaml-dump      reads YAML stream from STDIN and dumps YAML to STDOUT after a complete round-trip"
      hPutStrLn stderr "  run-tml             run/validate YAML-specific .tml file(s)"
      hPutStrLn stderr "  run-tml2            run/validate YAML-specific .tml file(s) while preserving comments"
      hPutStrLn stderr "  testml-compiler     emulate testml-compiler"

      exitFailure



cmdYaml2Token :: IO ()
cmdYaml2Token = do
  inYamlDat <- BS.L.getContents
  forM_ (groupBy (\x y -> YT.tLine x == YT.tLine y) $  YT.tokenize inYamlDat False) $ \lgrp -> do
    forM_  lgrp $ \YT.Token{..} -> do
      let tText' | null tText = ""
                 | any (== ' ') tText = replicate tLineChar ' ' ++ show tText
                 | otherwise  = replicate (tLineChar+1) ' ' ++ drop 1 (init (show tText))
      hPutStrLn stdout $ printf "<stdin>:%d:%d: %-15s| %s" tLine tLineChar (show tCode) tText'
    hPutStrLn stdout ""
  hFlush stdout

cmdYaml2Token0 :: IO ()
cmdYaml2Token0 = do
  inYamlDat <- BS.L.getContents
  print (length (YT.tokenize inYamlDat False))

cmdYaml2Yaml :: IO ()
cmdYaml2Yaml = do
  inYamlDat <- BS.L.getContents
  case sequence $ parseEvents inYamlDat of
    Left (ofs,msg) -> do
      hPutStrLn stderr ("Parsing error near byte offset " ++ show ofs ++ if null msg then "" else " (" ++ msg ++ ")")
      exitFailure
    Right events -> do
      BS.L.hPutStr stdout (writeEvents YT.UTF8 (map eEvent events))
      hFlush stdout

-- lazy streaming version
cmdYaml2Yaml' :: IO ()
cmdYaml2Yaml' = do
    inYamlDat <- BS.L.getContents
    BS.L.hPutStr stdout $ writeEvents YT.UTF8 $ parseEvents' inYamlDat
    hFlush stdout
  where
    parseEvents' = map (either (\(ofs,msg) -> error ("parsing error near byte offset " ++ show ofs ++ " (" ++ msg ++ ")")) (\evPos -> eEvent evPos)). filter (not. isComment). parseEvents

cmdYaml2Event :: IO ()
cmdYaml2Event = do
  inYamlDat <- BS.L.getContents
  forM_ (parseEvents inYamlDat) $ \ev -> case ev of
    Left (ofs,msg) -> do
      hPutStrLn stderr ("Parsing error near byte offset " ++ show ofs ++ if null msg then "" else " (" ++ msg ++ ")")
      exitFailure
    Right event -> do
      hPutStrLn stdout (ev2str True (eEvent event))
      hFlush stdout

cmdYaml2EventPos :: IO ()
cmdYaml2EventPos = do
  inYamlDat <- BS.L.getContents
  let inYamlDatTxt = T.decodeUtf8 (BS.L.toStrict inYamlDat)
      inYamlDatLns = T.lines inYamlDatTxt
      maxLine = length inYamlDatLns

  forM_ (parseEvents inYamlDat) $ \ev -> case ev of
    Left (ofs,msg) -> do
      hPutStrLn stderr (prettyPosWithSource ofs inYamlDat (" error [" ++ show ofs ++ "]") ++ msg)
      exitFailure
    Right event -> do
      let Pos{..} = ePos event

      putStrLn (prettyPosWithSource (ePos event) inYamlDat ("\t" ++ ev2str True (eEvent event)))

cmdYaml2Event0 :: IO ()
cmdYaml2Event0 = do
    inYamlDat <- BS.L.getContents
    print (length (parseEvents' inYamlDat))
  where
    parseEvents' = map (either (\(ofs,msg) -> error ("parsing error near byte offset " ++ show ofs ++ " (" ++ msg ++ ")")) id) . parseEvents

cmdYaml2YamlVal :: IO()
cmdYaml2YamlVal = do
  inYamlDat <- BS.L.getContents
  case sequence $ parseEvents inYamlDat of
    Left (ofs,msg) -> do
      hPutStrLn stderr ("Parsing error near byte offset " ++ show ofs ++ if null msg then "" else " (" ++ msg ++ ")")
      exitFailure
    Right oldEvents -> do
      let output = writeEvents YT.UTF8 (map eEvent oldEvents)
      BS.L.hPutStr stdout output
      hFlush stdout
      case sequence (parseEvents output) of
        Left (ofs',msg') -> do
          hPutStrLn stderr ("Parsing error in the generated YAML stream near byte offset " ++ show ofs' ++ if null msg' then "" else " (" ++ msg' ++ ")")
          exitFailure
        Right newEvents -> do
          hPutStrLn stdout $ printf "\nInput  Event Stream Length: %d\nOutput Event Stream Length: %d\n" (length oldEvents) (length newEvents)
          let diffList = filter (uncurry (/=)) $ zipWith (\a b -> (eEvent a, eEvent b)) oldEvents newEvents
          hPutStrLn stdout $ printf "No of difference detected: %d\n" $ length diffList
          forM_ diffList $ \(old,new) -> do
            hPutStrLn stdout $ "Input  > " ++ show old
            hPutStrLn stdout $ "Output < " ++ show new

cmdPrintNode :: IO()
cmdPrintNode = do
  str <-  BS.L.getContents
  case decode str :: Either (Pos, String) [Node Pos] of
    Left (pos, s) -> do
      hPutStrLn stdout s
      hFlush stdout
    Right nodeSeq -> forM_ nodeSeq $ \node -> do
      printNode node
      putStrLn ""

cmdDumpYAML :: IO()
cmdDumpYAML = do
  str <-  BS.L.getContents
  case decode str :: Either (Pos, String) [Node Pos] of
    Left (pos, str) -> do
      hPutStrLn stdout str
      hFlush stdout
    Right nodes -> do
      BS.L.hPutStrLn stdout $ encode nodes
      hFlush stdout

-- | 'J.Value' look-alike
data Value' = Object'  (Map Text Value')
            | Array'   [Value']
            | String'  !Text
            | NumberD' !Double
            | NumberI' !Integer
            | Bool'    !Bool
            | Null'
            deriving Show

toProperValue :: Value' -> J.Value
toProperValue v = case v of
  Null'      -> J.Null
  String' t  -> J.String t
  NumberD' x -> J.Number x
  NumberI' x -> J.Number (fromInteger x)
  Bool' b    -> J.Bool b
  Array' xs  -> J.Array (map toProperValue xs)
  Object' xs -> J.Object (fmap toProperValue xs)

instance FromYAML Value' where
  parseYAML (Y.Scalar _ s) = case s of
    SNull        -> pure Null'
    SBool b      -> pure (Bool' b)
    SFloat x     -> pure (NumberD' x)
    SInt x       -> pure (NumberI' x)
    SStr t       -> pure (String' t)
    SUnknown _ t -> pure (String' t) -- HACK

  parseYAML (Y.Sequence _ _ xs) = Array' <$> mapM parseYAML xs

  parseYAML (Y.Mapping _ _ m) = Object' . Map.fromList <$> mapM parseKV (Map.toList m)
    where
      parseKV :: (Y.Node Pos,Y.Node Pos) -> Parser (Text,Value')
      parseKV (k,v) = (,) <$> parseK k <*> parseYAML v

      -- for numbers and !!null we apply implicit conversions
      parseK n = do
        k <- parseYAML n
        case k of
          NumberI' t -> pure (T.pack (show t))
          NumberD' t -> pure (T.pack (show t))
          String' t  -> pure t
          Null'      -> pure ""
          -- we stringify the key with an added risk of nameclashing
          _          -> pure $ T.decodeUtf8 $ J.encodeStrict $ toProperValue k
--        _          -> fail ("dictionary entry had non-string key " ++ show k)

decodeAeson :: BS.L.ByteString -> Either (Pos,String) [J.Value]
decodeAeson = fmap (map toProperValue) . decode'
  where
    -- TODO
    decode' :: FromYAML v => BS.L.ByteString -> Either (Pos,String) [v]
    decode' bs0 = case decodeNode' coreSchemaResolver { schemaResolverMappingDuplicates = True } False False bs0 of
                  Left (pos, err) -> Left (pos, err)
                  Right a         -> Right a >>= mapM (parseEither . parseYAML . (\(Doc x) -> x))


-- | Try to convert 'Double' into 'Int64', return 'Nothing' if not
-- representable loss-free as integral 'Int64' value.
doubleToInt64 :: Double -> Maybe Int64
doubleToInt64 x
  | fromInteger x' == x
  , x' <= toInteger (maxBound :: Int64)
  , x' >= toInteger (minBound :: Int64)
    = Just (fromIntegral x')
  | otherwise = Nothing
  where
    x' = round x


decodeNumber :: T.Text -> Maybe Double
decodeNumber = readMaybe . T.unpack -- fixme

cmdYaml2Json :: IO ()
cmdYaml2Json = do
  inYamlDat <- BS.L.getContents

  case decodeAeson inYamlDat of
    Left (_, e) -> fail e
    Right vs -> do
      forM_ vs $ \v -> BS.L.putStrLn (J.encode v)

  return ()

unescapeSpcTab :: T.Text -> T.Text
unescapeSpcTab = T.replace "<SPC>" " " . T.replace "<TAB>" "\t"


data TestPass = PassExpErr   -- ^ expected parse fail
              | PassEvs      -- ^ events ok
              | PassEvsJson  -- ^ events+json ok
              | PassEvsJsonYaml
              deriving (Eq,Ord,Show)

data TestFail = FailParse    -- ^ unexpected parse fail
              | FailSuccess  -- ^ unexpected parse success
              | FailEvs      -- ^ events wrong/mismatched
              | FailJson     -- ^ JSON wrong/mismatched
              | FailYaml     -- ^ YAML wrong/mismatched
              deriving (Eq,Ord,Show)

data TestRes
  = Pass !TestPass
  | Fail !TestFail
  deriving (Eq,Ord,Show)

cmdRunTml :: [FilePath] -> IO ()
cmdRunTml args = do
  results <- forM args $ \fn -> do
    tml <- BS.readFile fn

    hPutStr stdout (fn ++ " : ")
    hFlush stdout

    TML.Document _ blocks <- either (fail . T.unpack) pure $ TML.parse fn (T.decodeUtf8 tml)

    forM blocks $ \(TML.Block label points) -> do

      let dats = [ (k,v) | TML.PointStr k v <- points ]

      let isErr = isJust (lookup "error" dats)

          Just inYamlDat = BS.L.fromStrict . T.encodeUtf8 . unescapeSpcTab <$> lookup "in-yaml" dats
          Just testEvDat = lines . T.unpack . unescapeSpcTab <$> lookup "test-event" dats

          mInJsonDat :: Maybe [J.Value]
          mInJsonDat = (maybe (error ("invalid JSON in " ++ show fn)) id . J.decodeStrictN . T.encodeUtf8) <$> lookup "in-json" dats

          mOutYamlDat = BS.L.fromStrict . T.encodeUtf8 . unescapeSpcTab <$> lookup "out-yaml" dats

      case sequence $ filter (not. isComment) (parseEvents inYamlDat) of
        Left err
          | isErr -> do
              putStrLn "OK! (error)"
              pure (Pass PassExpErr)
          | otherwise -> do
              putStrLn "FAIL!"
              putStrLn ""
              putStrLn "----------------------------------------------------------------------------"
              putStrLn' (T.unpack label)
              putStrLn ""
              putStrLn' (show err)
              putStrLn ""
              putStrLn' (show testEvDat)
              putStrLn ""
              BS.L.putStr inYamlDat
              putStrLn ""
              testParse inYamlDat
              putStrLn ""
              -- forM_ (parseEvents inYamlDat) (putStrLn' . show)
              putStrLn ""
              putStrLn "----------------------------------------------------------------------------"
              putStrLn ""
              pure (Fail FailParse)

        Right evs' -> do
          let events = map eEvent evs'
              evs'' = map (ev2str False) events
          if evs'' == testEvDat
             then do

               let outYamlDatIut = writeEvents YT.UTF8 (map toBlockStyle events)
                    where toBlockStyle ev = case ev of
                                              SequenceStart a b _ -> SequenceStart a b Block
                                              MappingStart a b _  -> MappingStart a b Block
                                              otherwise           -> ev
                   Right ev = sequence $ filter (not. isComment) (parseEvents outYamlDatIut)
                   outYamlEvsIut = either (const []) (map (ev2str False)) (Right (map eEvent ev))

               unless (outYamlEvsIut == evs'') $ do
                 putStrLn' ("\nWARNING: (iut /= ref)")

                 putStrLn' ("iut[yaml] = " ++ show outYamlDatIut)
                 putStrLn' ("ref[raw-evs] = " ++ show evs')
                 putStrLn' ("ref[evs] = " ++ show evs'')
                 putStrLn' ("iut[evs] = " ++ show outYamlEvsIut)

                 putStrLn ""


               case mInJsonDat of
                 Nothing -> do
                   putStrLn "OK!"
                   pure (Pass PassEvs)
                 Just inJsonDat -> do
                   iutJson <- either (fail. snd) pure $ decodeAeson inYamlDat

                   if iutJson == inJsonDat
                     then do
                       case mOutYamlDat of
                         Nothing -> do
                           putStrLn "OK! (+JSON)"
                           pure (Pass PassEvsJson)
                         Just outYamlDat -> do
                           case () of
                             _ | outYamlDat == outYamlDatIut -> do
                                   putStrLn "OK! (+JSON+YAML)"
                                   pure (Pass PassEvsJsonYaml)

                               | otherwise -> do

                                   putStrLn $ if outYamlEvsIut == evs'' then "OK (+JSON-YAML)" else "FAIL! (bad out-YAML)"

                                   putStrLn' ("ref = " ++ show outYamlDat)
                                   putStrLn' ("iut = " ++ show outYamlDatIut)
                                   putStrLn ""
                                   putStrLn' ("ref = " ++ show evs'')
                                   putStrLn' ("iut = " ++ show outYamlEvsIut)

                                   case outYamlEvsIut == evs'' of
                                     True -> do
                                       putStrLn' ("(iut == ref)")
                                       pure (Pass PassEvsJson)
                                     False -> pure (Fail FailYaml)


                     else do
                       putStrLn "FAIL! (bad JSON)"

                       putStrLn' ("ref = " ++ show inJsonDat)
                       putStrLn' ("iut = " ++ show iutJson)

                       pure (Fail FailJson)

             else do
               if isErr
                 then putStrLn "FAIL! (unexpected parser success)"
                 else putStrLn "FAIL!"

               putStrLn ""
               putStrLn "----------------------------------------------------------------------------"
               putStrLn' (T.unpack label)
               putStrLn ""
               putStrLn' ("ref = " ++ show testEvDat)
               putStrLn' ("iut = " ++ show evs'')
               putStrLn ""
               BS.L.putStr inYamlDat
               putStrLn ""
               testParse inYamlDat
               putStrLn ""
               -- forM_ (parseEvents inYamlDat) (putStrLn' . show)
               putStrLn ""
               putStrLn "----------------------------------------------------------------------------"
               putStrLn ""
               pure (Fail (if isErr then FailSuccess else FailEvs))

  putStrLn ""

  let ok = length [ () | Pass _ <- results' ]
      nok = length [ () | Fail _ <- results' ]

      stat j = show $ Map.findWithDefault 0 j $ Map.fromListWith (+) [ (k,1::Int) | k <- results' ]

      results' = concat results

  putStrLn $ concat
    [ "done -- passed: ", show ok
    , " (ev: ", stat (Pass PassEvs), ", ev+json: ", stat (Pass PassEvsJson), ", ev+json+yaml: ", stat (Pass PassEvsJsonYaml), ", err: ", stat (Pass PassExpErr), ") / "
    , "failed: ", show nok
    , " (err: ", stat (Fail FailParse), ", ev:", stat (Fail FailEvs), ", json:", stat (Fail FailJson), ", yaml:", stat (Fail FailYaml), ", ok:", stat (Fail FailSuccess), ")"
    ]

cmdRunTml' :: [FilePath] -> IO ()
cmdRunTml' args = do
  results <- forM args $ \fn -> do
    tml <- BS.readFile fn

    hPutStr stdout (fn ++ " : ")
    hFlush stdout

    TML.Document _ blocks <- either (fail . T.unpack) pure $ TML.parse fn (T.decodeUtf8 tml)

    forM blocks $ \(TML.Block label points) -> do

      let dats = [ (k,v) | TML.PointStr k v <- points ]

      let isErr = isJust (lookup "error" dats)

          Just inYamlDat = BS.L.fromStrict . T.encodeUtf8 . unescapeSpcTab <$> lookup "in-yaml" dats
          Just testEvDat = lines . T.unpack . unescapeSpcTab <$> lookup "test-event" dats

          mInJsonDat :: Maybe [J.Value]
          mInJsonDat = (maybe (error ("invalid JSON in " ++ show fn)) id . J.decodeStrictN . T.encodeUtf8) <$> lookup "in-json" dats

          mOutYamlDat = BS.L.fromStrict . T.encodeUtf8 . unescapeSpcTab <$> lookup "out-yaml" dats

      case sequence $ parseEvents inYamlDat of  -- allow parsing with comments
        Left err
          | isErr -> do
              putStrLn "OK! (error)"
              pure (Pass PassExpErr)
          | otherwise -> do
              putStrLn "FAIL!"
              putStrLn ""
              putStrLn "----------------------------------------------------------------------------"
              putStrLn' (T.unpack label)
              putStrLn ""
              putStrLn' (show err)
              putStrLn ""
              putStrLn' (show testEvDat)
              putStrLn ""
              BS.L.putStr inYamlDat
              putStrLn ""
              testParse inYamlDat
              putStrLn ""
              -- forM_ (parseEvents inYamlDat) (putStrLn' . show)
              putStrLn ""
              putStrLn "----------------------------------------------------------------------------"
              putStrLn ""
              pure (Fail FailParse)

        Right evs' -> do
          let events = map eEvent (filter (not. isComment'. eEvent) evs')                     -- filter comments before comparing
              evs'' = map (ev2str False) events
          if evs'' == testEvDat
             then do
               let outYamlDatIut = writeEvents YT.UTF8 (map eEvent evs')                -- Allow both block and flow style
               -- let outYamlDatIut = writeEvents YT.UTF8 (map (toBlockStyle. eEvent) evs')   -- Allow only Block style
               --      where toBlockStyle ev = case ev of
               --                                SequenceStart a b _ -> SequenceStart a b Block
               --                                MappingStart a b _  -> MappingStart a b Block
               --                                otherwise           -> ev
                   Right ev = sequence $ parseEvents outYamlDatIut
                   outYamlEvsIut = either (const []) (map (ev2str False)) (Right (map eEvent (filter (not. isComment'. eEvent) ev)))

               unless (outYamlEvsIut == evs'') $ do
                 putStrLn' ("\nWARNING: (iut /= ref)")

                 putStrLn' ("iut[yaml] = " ++ show outYamlDatIut)
                 putStrLn' ("ref[raw-evs] = " ++ show evs')
                 putStrLn' ("ref[evs] = " ++ show evs'')
                 putStrLn' ("iut[evs] = " ++ show outYamlEvsIut)

                 putStrLn ""


               case mInJsonDat of
                 Nothing -> do
                   putStrLn "OK!"
                   pure (Pass PassEvs)
                 Just inJsonDat -> do
                   iutJson <- either (fail. snd) pure $ decodeAeson inYamlDat

                   if iutJson == inJsonDat
                     then do
                       case mOutYamlDat of
                         Nothing -> do
                           putStrLn "OK! (+JSON)"
                           pure (Pass PassEvsJson)
                         Just outYamlDat -> do
                           case () of
                             _ | outYamlDat == outYamlDatIut -> do
                                   putStrLn "OK! (+JSON+YAML)"
                                   pure (Pass PassEvsJsonYaml)

                               | otherwise -> do

                                   putStrLn $ if outYamlEvsIut == evs'' then "OK (+JSON-YAML)" else "FAIL! (bad out-YAML)"

                                   putStrLn' ("ref = " ++ show outYamlDat)
                                   putStrLn' ("iut = " ++ show outYamlDatIut)
                                   putStrLn ""
                                   putStrLn' ("ref = " ++ show evs'')
                                   putStrLn' ("iut = " ++ show outYamlEvsIut)

                                   case outYamlEvsIut == evs'' of
                                     True -> do
                                       putStrLn' ("(iut == ref)")
                                       pure (Pass PassEvsJson)
                                     False -> pure (Fail FailYaml)


                     else do
                       putStrLn "FAIL! (bad JSON)"

                       putStrLn' ("ref = " ++ show inJsonDat)
                       putStrLn' ("iut = " ++ show iutJson)

                       pure (Fail FailJson)

             else do
               if isErr
                 then putStrLn "FAIL! (unexpected parser success)"
                 else putStrLn "FAIL!"

               putStrLn ""
               putStrLn "----------------------------------------------------------------------------"
               putStrLn' (T.unpack label)
               putStrLn ""
               putStrLn' ("ref = " ++ show testEvDat)
               putStrLn' ("iut = " ++ show evs'')
               putStrLn ""
               BS.L.putStr inYamlDat
               putStrLn ""
               testParse inYamlDat
               putStrLn ""
               -- forM_ (parseEvents inYamlDat) (putStrLn' . show)
               putStrLn ""
               putStrLn "----------------------------------------------------------------------------"
               putStrLn ""
               pure (Fail (if isErr then FailSuccess else FailEvs))

  putStrLn ""

  let ok = length [ () | Pass _ <- results' ]
      nok = length [ () | Fail _ <- results' ]

      stat j = show $ Map.findWithDefault 0 j $ Map.fromListWith (+) [ (k,1::Int) | k <- results' ]

      results' = concat results

  putStrLn $ concat
    [ "done -- passed: ", show ok
    , " (ev: ", stat (Pass PassEvs), ", ev+json: ", stat (Pass PassEvsJson), ", ev+json+yaml: ", stat (Pass PassEvsJsonYaml), ", err: ", stat (Pass PassExpErr), ") / "
    , "failed: ", show nok
    , " (err: ", stat (Fail FailParse), ", ev:", stat (Fail FailEvs), ", json:", stat (Fail FailJson), ", yaml:", stat (Fail FailYaml), ", ok:", stat (Fail FailSuccess), ")"
    ]

-- | Incomplete proof-of-concept 'testml-compiler' operation
cmdTestmlCompiler :: [FilePath] -> IO ()
cmdTestmlCompiler [fn0] = do
  (fn,raw) <- case fn0 of
    "-" -> (,) "<stdin>" <$> T.getContents
    _   -> (,) fn0 <$> T.readFile fn0

  case TML.parse fn raw of
    Left e    -> T.hPutStrLn stderr e >> exitFailure
    Right doc -> BS.putStrLn (J.encodeStrict doc)
cmdTestmlCompiler _ = do
  hPutStrLn stderr ("Usage: yaml-test testml-compiler [ <testml-file-name> | - ]")
  exitFailure


putStrLn' :: String -> IO ()
putStrLn' msg = putStrLn ("  " ++ msg)

printNode :: Node loc -> IO ()
printNode node = case node of
    (Y.Scalar _ a)      -> hPutStrLn stdout $  "Scalar "   ++ show a
    (Y.Mapping _ a b)   -> do
                              hPutStrLn stdout $  "Mapping "  ++ show a
                              printMap b
    (Y.Sequence _ a b)  -> do
                              hPutStrLn stdout $  "Sequence " ++ show a
                              mapM_ printNode b
    (Y.Anchor _ a b)    -> do
                              hPutStr stdout $  "Anchor "   ++ show a ++ " "
                              printNode b

printMap :: Map (Node loc) (Node loc) -> IO ()
printMap b = forM_ (Map.toList b) $ \(k,v) -> do
              hPutStr stdout "Key: "
              printNode k
              hPutStr stdout "Value: "
              printNode v

isComment evPos = case evPos of
  Right (YE.EvPos {eEvent = (YE.Comment _), ePos = _}) -> True
  _                                                    -> False

isComment' ev = case ev of
  (Comment _) -> True
  _           -> False

ev2str :: Bool -> Event -> String
ev2str withColSty = \case
    StreamStart                 -> "+STR"
    DocumentStart NoDirEndMarker-> "+DOC"
    DocumentStart _             -> "+DOC ---"
    MappingEnd                  -> "-MAP"
    (MappingStart manc mtag Flow)
      | withColSty              -> "+MAP {}" ++ ancTagStr manc mtag
    (MappingStart manc mtag _)  -> "+MAP"    ++ ancTagStr manc mtag
    SequenceEnd                 -> "-SEQ"
    (SequenceStart manc mtag Flow)
      | withColSty              -> "+SEQ []" ++ ancTagStr manc mtag
    SequenceStart manc mtag _   -> "+SEQ"    ++ ancTagStr manc mtag
    DocumentEnd True            -> "-DOC ..."
    DocumentEnd False           -> "-DOC"
    StreamEnd                   -> "-STR"
    Alias a                     -> "=ALI *"  ++ T.unpack a
    YE.Scalar manc mtag sty v   -> "=VAL"    ++ ancTagStr manc mtag ++ styStr sty ++ quote2 v
    Comment comment             -> "=COMMENT "++ quote2 comment
  where
    styStr = \case
           Plain        -> " :"
           DoubleQuoted -> " \""
           Literal _ _  -> " |"
           Folded  _ _  -> " >"
           SingleQuoted -> " '"

    ancTagStr manc mtag = anc' ++ tag'
      where
        anc' = case manc of
                 Nothing  -> ""
                 Just anc -> " &" ++ T.unpack anc

        tag' = case tagToText mtag of
                 Nothing -> ""
                 Just t  -> " <" ++ T.unpack t ++ ">"


    quote2 :: T.Text -> String
    quote2 = concatMap go . T.unpack
      where
        go c | c == '\n' = "\\n"
             | c == '\t' = "\\t"
             | c == '\b' = "\\b"
             | c == '\r' = "\\r"
             | c == '\\' = "\\\\"
             | otherwise = [c]



testParse :: BS.L.ByteString -> IO ()
testParse bs0 = mapM_  (putStrLn' . showT) $ YT.tokenize bs0 False
  where
    showT :: YT.Token -> String
    showT t = replicate (YT.tLineChar t) ' ' ++ show (YT.tText t) ++ "  " ++ show (YT.tCode t)