summaryrefslogtreecommitdiff
path: root/source/Felix/CommandLine.hs
blob: 448d6985bef9c99931da512d7ae882058eb12982 (plain)
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE NoImplicitPrelude #-}

module Felix.CommandLine
    ( runCommandLine
    , Input(..)
    , VerificationOptions(..)
    , Command(..)
    , CommandOutcome(..)
    , VerifiedOutputFailure(..)
    , parseCommandArguments
    , verificationCommandOutcome
    , commandOutcomeExitCode
    , renderCommandOutcome
    ) where

import Base
import Felix.OutputPlan qualified as Output
import Felix.Parse (ParseWorkspaceError)
import Felix.Parse qualified as Parse
import Felix.Provers qualified as Provers
import Felix.RequestDump qualified as RequestDump
import Felix.Source (SafeRelativePath)
import Felix.Source.Graph qualified as SourceGraph
import Felix.Store qualified as Store
import Felix.Verification qualified as Verification
import Felix.Version qualified as Version
import Felix.Workspace qualified as Workspace
import Felix.Render.Html.Export qualified as HtmlExport
import Felix.Render.Html.Layout qualified as HtmlLayout
import Felix.Render.Html.Output qualified as HtmlOutput
import Felix.Report.Location

import Control.Monad (unless, when)
import Data.Maybe (catMaybes)
import Data.Text qualified as StrictText
import Data.Text.IO qualified as Text
import GHC.Conc qualified
import Numeric (showFFloat)
import Options.Applicative hiding (renderFailure)
import System.Environment (getArgs, lookupEnv)
import System.Exit (ExitCode(..), exitWith)
import System.IO (stderr)
import Text.Read (readMaybe)


newtype Input = Input
    { inputFilePath :: FilePath
    }
    deriving stock (Show, Eq)

data VerificationOptions = VerificationOptions
    { verificationStoreSelection :: !Store.StoreSelection
    , verificationTimeLimit :: !Provers.TimeLimit
    , verificationMemoryLimit :: !Provers.MemoryLimit
    , verificationJobsOverride :: !(Maybe Provers.EffectiveJobs)
    , verificationDumpDestination :: !(Maybe FilePath)
    , verificationHtmlRequested :: !Bool
    }
    deriving stock (Show, Eq)

data Command
    = Version
    | ParseOnly !Input
    | Verify !Input !VerificationOptions
    deriving stock (Show, Eq)

data CommandOutcome
    = CommandCompleted
    | VerificationSucceeded
        !Verification.VerificationReport
        !Provers.SlowAtpReport
    | VerificationCompletedWithGaps
        !Verification.VerificationReport
        !Provers.SlowAtpReport
    | VerificationRejected
        !Verification.VerificationReport
        !Verification.FailedVerification
        !Provers.SlowAtpReport
    | VerificationCheckingRejected
        !Verification.VerificationReport
        !Verification.VerificationDriverError
        !Provers.SlowAtpReport
    | SourcePlanningFailed !ParseWorkspaceError
    | ParseOnlyFailed !Workspace.AuthorityFreeParseError
    | VerificationDriverFailed !Verification.VerificationDriverError
    | VerificationSessionFailed
        !Store.StorePath
        !Verification.VerificationSessionError
    | StorePlanningFailed !Store.StorePlanningError
    | StoreIncompatible !Store.StorePath !Store.StoreIncompatibility
    | StoreFailed !Store.StorePath !Store.StoreLifecycleError
    | OutputPlanningFailed !Output.OutputPlanError
    | HtmlLayoutFailed !HtmlLayout.HtmlLayoutError
    | DumpObservationFailed !RequestDump.DumpObservationError
    | VerifiedOutputFailed
        !Verification.VerificationReport
        !VerifiedOutputFailure
        !Provers.SlowAtpReport
    deriving stock (Show)

data VerifiedOutputFailure
    = VerifiedHtmlExportFailed !HtmlExport.HtmlExportError
    | VerifiedHtmlOutputPlanningFailed !HtmlOutput.HtmlOutputError
    | VerifiedHtmlPublicationFailed !HtmlOutput.HtmlPublicationError
    | VerifiedHtmlLayoutUnavailable
    deriving stock (Show)

data HtmlPreflight = HtmlPreflight
    !Workspace.WorkspaceEnvironment
    !SourceGraph.ResolvedSourceGraph
    !HtmlLayout.HtmlLayout
    ![SafeRelativePath]


runCommandLine :: IO ()
runCommandLine = do
    arguments <- getArgs
    selected <- handleParseResult (parseCommandArguments arguments)
    outcome <- runCommand selected
    renderCommandOutcome outcome
    exitWith (commandOutcomeExitCode outcome)

rawCommandParserInfo :: ParserInfo RawCommand
rawCommandParserInfo =
    info
        (helper <*> rawCommandParser)
        (fullDesc <> header "Felix")

runCommand :: Command -> IO CommandOutcome
runCommand = \case
    Version -> do
        Text.putStrLn Version.info
        pure CommandCompleted
    ParseOnly (Input input) ->
        Workspace.parseWorkspace input >>= \case
            Left failure ->
                pure (ParseOnlyFailed failure)
            Right _blocks ->
                pure CommandCompleted
    Verify input options ->
        runVerification input options

runVerification
    :: Input
    -> VerificationOptions
    -> IO CommandOutcome
runVerification input options = do
    plannedStore <-
        Store.planStore
            (verificationStoreSelection options)
    case plannedStore of
        Left failure ->
            pure (StorePlanningFailed failure)
        Right storePlan -> do
            htmlResult <- discoverHtmlDestinations input options
            case htmlResult of
                Left failure ->
                    pure failure
                Right htmlPreflight ->
                    Store.withStoreLease storePlan \lease -> do
                        outputResult <-
                            Output.planVerificationOutputs
                                (Store.storeLeasePath lease)
                                (verificationDumpDestination options)
                                (fmap
                                    (\(HtmlPreflight
                                            _environment _graph _layout destinations) ->
                                        ("html", destinations))
                                    htmlPreflight)
                        case outputResult of
                            Left failure ->
                                pure (OutputPlanningFailed failure)
                            Right outputPlan ->
                                openVerificationSession
                                    input
                                    options
                                    lease
                                    outputPlan
                                    htmlPreflight

discoverHtmlDestinations
    :: Input
    -> VerificationOptions
    -> IO (Either CommandOutcome (Maybe HtmlPreflight))
discoverHtmlDestinations input options
    | not (verificationHtmlRequested options) =
        pure (Right Nothing)
    | otherwise = do
        prepared <- prepareInputSourceGraph input
        pure case prepared of
            Left failure -> Left (SourcePlanningFailed failure)
            Right (environment, graph) ->
                case planHtmlDestinations environment graph of
                    Left failure -> Left (HtmlLayoutFailed failure)
                    Right (layout, destinations) ->
                        Right
                            (Just
                                (HtmlPreflight
                                    environment graph layout destinations))

planHtmlDestinations
    :: Workspace.WorkspaceEnvironment
    -> SourceGraph.ResolvedSourceGraph
    -> Either
        HtmlLayout.HtmlLayoutError
        (HtmlLayout.HtmlLayout, [SafeRelativePath])
planHtmlDestinations environment graph = do
    layout <-
        HtmlLayout.layoutHtmlSourceGraph
            (Workspace.workspaceHtmlMountPrefixes environment)
            graph
    pure
        ( layout
        , [ HtmlLayout.routeDestination route
          | (_source, route) <-
                HtmlLayout.htmlPageRoutes layout
          ]
            <> [HtmlLayout.routeDestination
                    (HtmlLayout.htmlSupportScriptRoute layout)]
        )

prepareInputSourceGraph
    :: Input
    -> IO
        (Either
            ParseWorkspaceError
            (Workspace.WorkspaceEnvironment, SourceGraph.ResolvedSourceGraph))
prepareInputSourceGraph input = do
    preparedEnvironment <- Workspace.prepareDefaultWorkspaceEnvironment
    case preparedEnvironment of
        Left failure -> pure (Left failure)
        Right environment -> do
            preparedRoot <- Workspace.prepareWorkspaceRoot
                environment
                (inputFilePath input)
            case preparedRoot of
                Left failure -> pure (Left failure)
                Right root ->
                    fmap (fmap (\graph -> (environment, graph)))
                        (Workspace.prepareSourceGraph environment root)

openVerificationSession
    :: Input
    -> VerificationOptions
    -> Store.StoreLease
    -> Output.VerificationOutputPlan
    -> Maybe HtmlPreflight
    -> IO CommandOutcome
openVerificationSession input options lease outputPlan htmlPreflight = do
    opened <- Verification.withVerificationSession lease
        (\session ->
            runOpenVerification
                input
                options
                outputPlan
                htmlPreflight
                session)
    pure case opened of
        Left
            (Verification.VerificationSessionStoreError
                (Store.StoreLifecycleOpenFailed
                    (Store.IncompatibleStore incompatibility))) ->
                        StoreIncompatible
                            (Store.storeLeasePath lease)
                            incompatibility
        Left (Verification.VerificationSessionStoreError failure) ->
            StoreFailed (Store.storeLeasePath lease) failure
        Left failure ->
            VerificationSessionFailed (Store.storeLeasePath lease) failure
        Right outcome -> outcome

runOpenVerification
    :: Input
    -> VerificationOptions
    -> Output.VerificationOutputPlan
    -> Maybe HtmlPreflight
    -> Verification.VerificationSession
    -> IO CommandOutcome
runOpenVerification input options outputPlan htmlPreflight session = do
    observerResult <-
        RequestDump.prepareRequestObserver
            (Output.verificationDumpOutput outputPlan)
    case observerResult of
        Left failure ->
            pure (DumpObservationFailed failure)
        Right observer -> do
            (preparedGraph, htmlOutputPreparation) <- case htmlPreflight of
                Just (HtmlPreflight
                        environment graph layout _destinations) ->
                    pure
                        ( Right graph
                        , Just
                            ( Workspace.workspaceRendererSearchRoots environment
                            , layout
                            )
                        )
                Nothing -> do
                    graphResult <- fmap snd <$> prepareInputSourceGraph input
                    pure (graphResult, Nothing)
            case preparedGraph of
                Left failure -> pure (SourcePlanningFailed failure)
                Right graph -> do
                    vampirePath <- getVampireExecutable
                    jobs <- Provers.selectEffectiveJobs
                        (verificationJobsOverride options)
                        GHC.Conc.getNumProcessors
                    let vampire =
                            Provers.vampire
                                vampirePath
                                (verificationTimeLimit options)
                                (verificationMemoryLimit options)
                        validationMode =
                            case verificationStoreSelection options of
                                Store.FreshTemporaryStore ->
                                    Verification.FreshStoreValidation
                                Store.DefaultStore ->
                                    Verification.WarmStoreValidation
                                Store.ExplicitStore{} ->
                                    Verification.WarmStoreValidation
                        request = Verification.CheckRequest
                            { Verification.checkSourceGraph = graph
                            , Verification.checkStoreValidationMode =
                                validationMode
                            , Verification.checkEffectiveJobs = jobs
                            , Verification.checkVampire = vampire
                            , Verification.checkRequestObserver = observer
                            }
                    observed <- RequestDump.captureDumpFailure
                        (Verification.checkWorkspace session request)
                    case observed of
                        Left failure -> pure (DumpObservationFailed failure)
                        Right (Left failure) ->
                            pure (VerificationDriverFailed failure)
                        Right (Right outcome) ->
                            finishVerification
                                outputPlan
                                htmlOutputPreparation
                                outcome

finishVerification
    :: Output.VerificationOutputPlan
    -> Maybe ([FilePath], HtmlLayout.HtmlLayout)
    -> Verification.CheckOutcome
    -> IO CommandOutcome
finishVerification outputPlan selectedLayout outcome =
    case result of
        Verification.VerificationFailure{} ->
            pure (verificationCommandOutcome result slowReport)
        Verification.VerificationCheckingFailure{} ->
            pure (verificationCommandOutcome result slowReport)
        Verification.VerificationCompleted report presentation ->
            publishHtmlIfRequested
                outputPlan
                selectedLayout
                report
                presentation
                (VerificationSucceeded report slowReport)
                slowReport
        Verification.CompletedWithExplicitGaps report presentation ->
            publishHtmlIfRequested
                outputPlan
                selectedLayout
                report
                presentation
                (VerificationCompletedWithGaps report slowReport)
                slowReport
  where
    result = Verification.checkVerificationResult outcome
    slowReport = Verification.checkSlowAtpReport outcome

publishHtmlIfRequested
    :: Output.VerificationOutputPlan
    -> Maybe ([FilePath], HtmlLayout.HtmlLayout)
    -> Verification.VerificationReport
    -> Verification.VerificationPresentation
    -> CommandOutcome
    -> Provers.SlowAtpReport
    -> IO CommandOutcome
publishHtmlIfRequested
        outputPlan selectedLayout report presentation successOutcome slowReport =
    case Output.verificationHtmlRoutes outputPlan of
        Nothing ->
            pure successOutcome
        Just routes -> do
            case selectedLayout of
                Nothing ->
                    pure
                        (VerifiedOutputFailed
                            report
                            VerifiedHtmlLayoutUnavailable
                            slowReport)
                Just (rendererRoots, layout) -> do
                    prepared <-
                        HtmlExport.prepareHtmlExportWithLayoutFromRendererRoots
                            rendererRoots
                            layout
                            (Verification.verificationHtmlPresentation presentation)
                    case prepared of
                        Left failure ->
                            pure
                                (VerifiedOutputFailed
                                    report
                                    (VerifiedHtmlExportFailed failure)
                                    slowReport)
                        Right artifacts ->
                            case HtmlOutput.planHtmlOutputAgainst routes artifacts of
                                Left failure ->
                                    pure
                                        (VerifiedOutputFailed
                                            report
                                            (VerifiedHtmlOutputPlanningFailed failure)
                                            slowReport)
                                Right plan ->
                                    HtmlOutput.writeHtmlOutput plan >>= \case
                                        Left failure ->
                                            pure
                                                (VerifiedOutputFailed
                                                    report
                                                    (VerifiedHtmlPublicationFailed
                                                        failure)
                                                    slowReport)
                                        Right () ->
                                            pure successOutcome

verificationCommandOutcome
    :: Verification.VerificationResult
    -> Provers.SlowAtpReport
    -> CommandOutcome
verificationCommandOutcome result slowReport = case result of
    Verification.VerificationCompleted report _presentation ->
        VerificationSucceeded report slowReport
    Verification.CompletedWithExplicitGaps report _presentation ->
        VerificationCompletedWithGaps report slowReport
    Verification.VerificationFailure report failure ->
        VerificationRejected report failure slowReport
    Verification.VerificationCheckingFailure report failure ->
        VerificationCheckingRejected report failure slowReport

commandOutcomeExitCode :: CommandOutcome -> ExitCode
commandOutcomeExitCode = \case
    CommandCompleted ->
        ExitSuccess
    VerificationSucceeded{} ->
        ExitSuccess
    VerificationCompletedWithGaps{} ->
        ExitSuccess
    VerificationRejected _report failed _slow ->
        case Verification.failedVerificationReason failed of
            Verification.CountermodelFailure{} -> ExitFailure 1
            Verification.ContradictoryInputFailure{} -> ExitFailure 1
            Verification.IndeterminateFailure{} -> ExitFailure 2
            Verification.ProtocolFailure{} -> ExitFailure 2
            Verification.TransportFailure{} -> ExitFailure 2
    VerificationCheckingRejected _report failure _slow ->
        case Verification.verificationDriverErrorKind failure of
            Verification.VerificationSourceFailure -> ExitFailure 1
            Verification.VerificationInfrastructureFailure -> ExitFailure 2
    SourcePlanningFailed{} ->
        ExitFailure 1
    ParseOnlyFailed{} ->
        ExitFailure 1
    VerificationDriverFailed failure ->
        case Verification.verificationDriverErrorKind failure of
            Verification.VerificationSourceFailure -> ExitFailure 1
            Verification.VerificationInfrastructureFailure -> ExitFailure 2
    VerificationSessionFailed{} ->
        ExitFailure 2
    StorePlanningFailed{} ->
        ExitFailure 2
    StoreIncompatible{} ->
        ExitFailure 2
    StoreFailed{} ->
        ExitFailure 2
    OutputPlanningFailed{} ->
        ExitFailure 2
    HtmlLayoutFailed{} ->
        ExitFailure 2
    DumpObservationFailed{} ->
        ExitFailure 2
    VerifiedOutputFailed{} ->
        ExitFailure 2

renderCommandOutcome :: CommandOutcome -> IO ()
renderCommandOutcome = \case
    CommandCompleted ->
        pure ()
    VerificationSucceeded report slowReport -> do
        Text.hPutStrLn stderr "Verification successful."
        renderVerificationReport report
        renderSlowAtpReport slowReport
    VerificationCompletedWithGaps report slowReport -> do
        Text.hPutStrLn stderr
            "Verification completed with explicit proof gaps."
        renderVerificationReport report
        renderSlowAtpReport slowReport
    VerificationRejected report failure slowReport -> do
        renderFailedVerification failure
        renderVerificationReport report
        renderSlowAtpReport slowReport
    VerificationCheckingRejected report failure slowReport -> do
        renderVerificationDriverFailure failure
        renderVerificationReport report
        renderSlowAtpReport slowReport
    SourcePlanningFailed failure ->
        renderFailure
            ("Source planning failed: "
                <> Parse.renderParseWorkspaceError failure)
    ParseOnlyFailed failure ->
        renderFailure
            ("Parsing failed: "
                <> Workspace.renderAuthorityFreeParseError failure)
    VerificationDriverFailed failure ->
        renderVerificationDriverFailure failure
    VerificationSessionFailed path failure ->
        renderFailure case failure of
            Verification.VerificationSessionFoundationError{} ->
                "The fixed foundation manifest is invalid."
            Verification.VerificationSessionStoreError storeFailure ->
                "Store failure at "
                    <> quotePath (Store.storePathFilePath path)
                    <> ": "
                    <> Store.renderStoreLifecycleError storeFailure
            Verification.VerificationSessionTheoryMismatch expected actual ->
                "Store theory mismatch at "
                    <> quotePath (Store.storePathFilePath path)
                    <> ": expected "
                    <> StrictText.pack (show expected)
                    <> ", found "
                    <> StrictText.pack (show actual)
    StorePlanningFailed failure ->
        renderFailure
            ("Store path planning failed: "
                <> Store.renderStorePlanningError failure)
    StoreIncompatible path failure ->
        renderFailure
            ("Disposable store "
                <> quotePath (Store.storePathFilePath path)
                <> " is incompatible: "
                <> Store.renderStoreIncompatibility failure
                <> ". Use --fresh, choose another --store path, or remove the disposable store.")
    StoreFailed path failure ->
        renderFailure
            ("Store failure at "
                <> quotePath (Store.storePathFilePath path)
                <> ": " <> Store.renderStoreLifecycleError failure)
    OutputPlanningFailed failure ->
        renderFailure
            ("Verification output preflight failed: "
                <> Output.renderOutputPlanError failure)
    HtmlLayoutFailed failure ->
        renderFailure
            ("HTML route planning failed: "
                <> HtmlLayout.renderHtmlLayoutError failure)
    DumpObservationFailed failure ->
        renderFailure (RequestDump.renderDumpObservationError failure)
    VerifiedOutputFailed report failure slowReport -> do
        renderVerifiedOutputFailure failure
        renderVerificationReport report
        renderSlowAtpReport slowReport

renderFailure :: Text -> IO ()
renderFailure =
    Text.hPutStrLn stderr

renderVerificationDriverFailure
    :: Verification.VerificationDriverError
    -> IO ()
renderVerificationDriverFailure =
    renderFailure . Verification.renderVerificationDriverError

quotePath :: FilePath -> Text
quotePath = StrictText.pack . show

renderFailedVerification :: Verification.FailedVerification -> IO ()
renderFailedVerification failed =
    case Verification.failedVerificationReason failed of
        Verification.CountermodelFailure tptp -> do
            renderFailedTask tptp
            Text.hPutStrLn stderr
                ("Verification failed: prover found countermodel at "
                    <> locationToText location)
            Text.hPutStrLn stderr
                "This often happens when an explicit justification with \\cref{...} is missing some references."
        Verification.ContradictoryInputFailure tptp -> do
            renderFailedTask tptp
            Text.hPutStrLn stderr
                ("Verification failed: contradictory axioms at "
                    <> locationToText location)
            Text.hPutStrLn stderr
                "This is usually caused by an incorrect axiom or a theorem that has its proof omitted."
        Verification.IndeterminateFailure tptp -> do
            renderFailedTask tptp
            Text.hPutStrLn stderr
                ("Verification failed: prover returned an indeterminate result at "
                    <> locationToText location)
        Verification.ProtocolFailure label message -> do
            Text.hPutStrLn stderr
                ("Prover error at " <> locationToText location <> ":")
            Text.hPutStrLn stderr ("Task: " <> label)
            Text.hPutStrLn stderr ("Error: " <> message)
        Verification.TransportFailure processError -> do
            Text.hPutStrLn stderr
                ("Prover process error at " <> locationToText location <> ":")
            Text.hPutStrLn stderr (StrictText.pack (show processError))
  where
    location = Verification.failedVerificationLocation failed

renderVerifiedOutputFailure :: VerifiedOutputFailure -> IO ()
renderVerifiedOutputFailure = \case
    VerifiedHtmlExportFailed failure ->
        renderFailure
            ("Verification succeeded, but HTML preparation failed: "
                <> HtmlExport.renderHtmlExportError failure)
    VerifiedHtmlOutputPlanningFailed failure ->
        renderFailure
            ("Verification succeeded, but prepared HTML did not match the reserved routes: "
                <> HtmlOutput.renderHtmlOutputError failure)
    VerifiedHtmlPublicationFailed failure -> do
        renderFailure
            "Verification succeeded, but HTML publication did not complete."
        traverse_
            renderFailure
            (HtmlOutput.renderHtmlPublicationError failure)
    VerifiedHtmlLayoutUnavailable ->
        renderFailure
            "Verification succeeded, but the preflight HTML layout was unavailable."

renderFailedTask :: Text -> IO ()
renderFailedTask tptp = do
    Text.hPutStrLn stderr "(Failed TPTP task follows.)"
    Text.hPutStrLn stderr tptp

renderVerificationReport :: Verification.VerificationReport -> IO ()
renderVerificationReport report = do
    Text.hPutStrLn stderr
        ( "Direct source authorization summary: "
            <> renderCount
                sourceAxiomCount
                "source axiom"
            <> ", "
            <> renderCount
                omittedCount
                "explicit proof gap"
            <> "."
        )
    for_
        (Verification.verificationDirectEscapes report)
        \escape ->
            Text.hPutStrLn stderr case Verification.reportedEscapeKind escape of
                Verification.ReportedSourceAxiom ->
                    "Source axiom at "
                        <> locationToText
                            (Verification.reportedEscapeLocation escape)
                Verification.ReportedOmitted ->
                    "Explicit proof gap at "
                        <> locationToText
                            (Verification.reportedEscapeLocation escape)
  where
    sourceAxiomCount =
        length
            [ ()
            | escape <- Verification.verificationDirectEscapes report
            , Verification.reportedEscapeKind escape
                == Verification.ReportedSourceAxiom
            ]
    omittedCount =
        length
            [ ()
            | escape <- Verification.verificationDirectEscapes report
            , Verification.reportedEscapeKind escape
                == Verification.ReportedOmitted
            ]
    renderCount amount noun =
        StrictText.pack (show amount)
            <> " "
            <> noun
            <> if amount == 1 then "" else "s"

renderSlowAtpReport :: Provers.SlowAtpReport -> IO ()
renderSlowAtpReport report =
    unless (null (Provers.slowAtpTasks report)) do
        Text.hPutStrLn stderr
            "Slow Vampire tasks (executor wall time; run-local performance note):"
        traverse_ renderTask (Provers.slowAtpTasks report)
        let omitted = Provers.slowAtpOmittedTaskCount report
        when (omitted > 0)
            (Text.hPutStrLn stderr
                ( StrictText.pack
                    (show (length (Provers.slowAtpTasks report)))
                    <> " slowest shown; "
                    <> StrictText.pack (show omitted)
                    <> " additional tasks took at least 5.0 seconds."
                ))
  where
    renderTask task =
        Text.hPutStrLn stderr
            ( "  "
                <> renderAtpDuration (Provers.slowAtpDuration task)
                <> " "
                <> renderSlowAtpOutcome (Provers.slowAtpOutcome task)
                <> " at "
                <> locationToText (Provers.slowAtpLocation task)
                <> " (module "
                <> renderNatural
                    (Provers.workPositionModuleOrdinal
                        (Provers.slowAtpPosition task))
                <> ", request "
                <> renderNatural
                    (Provers.workPositionLocalRequestOrdinal
                        (Provers.slowAtpPosition task))
                <> ", id "
                <> StrictText.pack (show (Provers.slowAtpRequestId task))
                <> ")"
            )

    renderNatural = StrictText.pack . show

renderAtpDuration :: Provers.AtpDuration -> Text
renderAtpDuration duration =
    StrictText.pack
        (showFFloat
            (Just 2)
            (fromIntegral (Provers.atpDurationNanoseconds duration)
                / (1000000000 :: Double))
            "s")

renderSlowAtpOutcome :: Provers.SlowAtpOutcome -> Text
renderSlowAtpOutcome = \case
    Provers.SlowAtpAccepted -> "accepted"
    Provers.SlowAtpRejected rejection ->
        "rejected (" <> StrictText.pack (show rejection) <> ")"
    Provers.SlowAtpProtocolFailed -> "protocol failure"
    Provers.SlowAtpProcessFailed -> "process failure"

getVampireExecutable :: IO FilePath
getVampireExecutable =
    fromMaybe "vampire" <$> lookupEnv "FELIX_VAMPIRE"


data RawCommand
    = RawVersion
    | RawFile !RawFileCommand

data RawFileCommand = RawFileCommand
    { rawInput :: !Input
    , rawParseOnly :: !Bool
    , rawStore :: !(Maybe FilePath)
    , rawFresh :: !Bool
    , rawTimeLimit :: !(Maybe Provers.TimeLimit)
    , rawMemoryLimit :: !(Maybe Provers.MemoryLimit)
    , rawJobs :: !(Maybe Provers.EffectiveJobs)
    , rawDump :: !(Maybe FilePath)
    , rawHtml :: !Bool
    }

rawCommandParser :: Parser RawCommand
rawCommandParser =
    versionParser
        <|> (RawFile <$> rawFileCommandParser)

versionParser :: Parser RawCommand
versionParser =
    flag'
        RawVersion
        (long "version" <> help "Show the Felix version.")

inputParser :: Parser Input
inputParser =
    Input
        <$> strArgument
            (help "Source file" <> metavar "FILE")

rawFileCommandParser :: Parser RawFileCommand
rawFileCommandParser =
    RawFileCommand
        <$> inputParser
        <*> switch
            (long "parseonly"
                <> help "Resolve and parse source without verification.")
        <*> optional
            (strOption
                (long "store"
                    <> metavar "PATH"
                    <> help "Use the disposable SQLite store at PATH."))
        <*> switch
            (long "fresh"
                <> help "Use a fresh temporary disposable store.")
        <*> optional timeLimitParser
        <*> optional memoryLimitParser
        <*> optional jobsParser
        <*> optional
            (strOption
                (long "dump"
                    <> metavar "DUMPDIR"
                    <> help "Dump exact Vampire requests as they execute."))
        <*> switch
            (long "html"
                <> help "Publish verified HTML under ./html.")

parseCommandArguments :: [String] -> ParserResult Command
parseCommandArguments arguments =
    case execParserPure
            defaultPrefs
            rawCommandParserInfo
            arguments of
        Success raw ->
            case validateRawCommand raw of
                Left message ->
                    Failure
                        (parserFailure
                            defaultPrefs
                            rawCommandParserInfo
                            (ErrorMsg message)
                            [])
                Right selected ->
                    Success selected
        Failure failure ->
            Failure failure
        CompletionInvoked completion ->
            CompletionInvoked completion

validateRawCommand :: RawCommand -> Either String Command
validateRawCommand = \case
    RawVersion ->
        Right Version
    RawFile raw
        | rawParseOnly raw
        , not (null verificationOnlyOptions) ->
            Left
                ("--parseonly cannot be combined with verification options: "
                    <> unwords verificationOnlyOptions)
        | rawParseOnly raw ->
            Right (ParseOnly (rawInput raw))
        | isJust (rawStore raw) && rawFresh raw ->
            Left "--store and --fresh are mutually exclusive"
        | otherwise ->
            Right
                (Verify
                    (rawInput raw)
                    VerificationOptions
                        { verificationStoreSelection =
                            case rawStore raw of
                                Just path ->
                                    Store.ExplicitStore path
                                Nothing
                                    | rawFresh raw ->
                                        Store.FreshTemporaryStore
                                    | otherwise ->
                                        Store.DefaultStore
                        , verificationTimeLimit =
                            fromMaybe
                                Provers.defaultTimeLimit
                                (rawTimeLimit raw)
                        , verificationMemoryLimit =
                            fromMaybe
                                Provers.defaultMemoryLimit
                                (rawMemoryLimit raw)
                        , verificationJobsOverride = rawJobs raw
                        , verificationDumpDestination =
                            rawDump raw
                        , verificationHtmlRequested =
                            rawHtml raw
                        })
      where
        verificationOnlyOptions =
            catMaybes
                [ "--store" <$ rawStore raw
                , if rawFresh raw then Just "--fresh" else Nothing
                , "--timelimit" <$ rawTimeLimit raw
                , "--memlimit" <$ rawMemoryLimit raw
                , "--jobs" <$ rawJobs raw
                , "--dump" <$ rawDump raw
                , if rawHtml raw then Just "--html" else Nothing
                ]

timeLimitParser :: Parser Provers.TimeLimit
timeLimitParser =
    Provers.Seconds
        <$> option auto
            ( long "timelimit"
                <> short 't'
                <> metavar "SECONDS"
                <> help "Time limit for each Vampire request."
            )

memoryLimitParser :: Parser Provers.MemoryLimit
memoryLimitParser =
    Provers.Megabytes
        <$> option auto
            ( long "memlimit"
                <> short 'm'
                <> metavar "MB"
                <> help "Memory limit for each Vampire process."
            )

jobsParser :: Parser Provers.EffectiveJobs
jobsParser =
    option
        (eitherReader parseJobs)
        ( long "jobs"
            <> short 'j'
            <> metavar "JOBS"
            <> help
                "Run at most JOBS module checkers and Vampire invocations."
        )
  where
    parseJobs raw =
        case readMaybe raw >>= Provers.effectiveJobs of
            Just jobs -> Right jobs
            Nothing -> Left "JOBS must be a positive integer"