-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathFlagsDecode.hs
More file actions
2077 lines (1806 loc) · 86 KB
/
Copy pathFlagsDecode.hs
File metadata and controls
2077 lines (1806 loc) · 86 KB
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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE CPP #-}
module FlagsDecode(
exitWithUsage,
exitWithHelp, exitWithHelpHidden,
Decoded(..),
decodeArgs,
updateFlags,
defaultFlags,
decodeFlags,
adjustFinalFlags,
showFlags, showFlagsRaw,
showFlagsLst, showFlagsAllLst,
getFlagValueString,
) where
import Data.List(nub, sort, intercalate, intersperse, partition, stripPrefix)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Control.Exception as CE
import System.IO.Error(ioeGetErrorString)
import System.IO.Unsafe(unsafePerformIO)
import System.IO(hPutStr, hPutStrLn, stderr, stdout)
import System.FilePath(normalise, dropTrailingPathSeparator)
import System.Directory(getDirectoryContents, canonicalizePath)
import Control.Monad(when)
import Data.Char(isAlpha, isDigit, toUpper)
import Data.List.Split(splitWhen)
import Version(bluespec)
import Backend
import FileNameUtil(hasDotSuf, takeSuf,
bscSrcSuffix, bsvSrcSuffix,
cSuffix, cxxSuffix, cppSuffix, ccSuffix,
objSuffix, arSuffix,
verSuffix, verSuffix2, verSuffix3, verSuffix4, verSuffix5,
vhdlSuffix, vhdlSuffix2,
abinSuffix)
-- For error messages
import Error(internalError, EMsg, WMsg, ErrMsg(..),
ErrorHandle, bsError, bsWarning, exitFail, exitOK)
import Position(Position, cmdPosition)
import VFileName
import Verilog(vIsValidIdent)
import Flags
catchIO :: IO a -> (IOError -> IO a) -> IO a
catchIO = CE.catch
-- -------------------------
-- File name testing
-- These could be FileUtil.hs
-- and used in place of calls to hasDotSuffix in other places
-- (like bsc.hs and Depend.hs)
isSrcFile :: String -> Bool
isSrcFile s = isBlueSrcFile s
|| isABinFile s
|| isHDLSrcFile s
|| isCSrcFile s
isBlueSrcFile :: String -> Bool
isBlueSrcFile s = hasDotSuf bscSrcSuffix s
|| hasDotSuf bsvSrcSuffix s
isABinFile :: String -> Bool
isABinFile s = hasDotSuf abinSuffix s
isHDLSrcFile :: String -> Bool
isHDLSrcFile s = isVerSrcFile s
|| isVhdlSrcFile s
isVerSrcFile :: String -> Bool
isVerSrcFile s = hasDotSuf verSuffix s
|| hasDotSuf verSuffix2 s
|| hasDotSuf verSuffix3 s
|| hasDotSuf verSuffix4 s
|| hasDotSuf verSuffix5 s
isVhdlSrcFile :: String -> Bool
isVhdlSrcFile s = hasDotSuf vhdlSuffix s
|| hasDotSuf vhdlSuffix2 s
isCSrcFile :: String -> Bool
isCSrcFile s = hasDotSuf cSuffix s
|| hasDotSuf cxxSuffix s
|| hasDotSuf cppSuffix s
|| hasDotSuf ccSuffix s
|| hasDotSuf objSuffix s
|| hasDotSuf arSuffix s
-- -------------------------
-- Usage message for BSC
-- Usage:
-- bsc -help to get help
-- bsc [flags] file.bsv to partially compile a Bluespec file
-- bsc [flags] -verilog -g mod file.bsv to compile a module to Verilog
-- bsc [flags] -verilog -g mod -u file.bsv to recursively compile modules to Verilog
-- bsc [flags] -verilog -e topmodule to link Verilog into a simulation model
-- bsc [flags] -sim -g mod file.bsv to compile to a Bluesim object
-- bsc [flags] -sim -g mod -u file.bsv to recursively compile to Bluesim objects
-- bsc [flags] -sim -e topmodule to link objects into a Bluesim binary
-- bsc [flags] -systemc -e topmodule to link objects into a SystemC model
usage :: String -> String
usage prog =
let mkUsage (cl,desc) =
let lcol = " " ++ prog ++ " " ++ cl
in (take 41 (lcol ++ (repeat ' '))) ++ " " ++ desc ++ "\n"
in "Usage:\n" ++ concatMap mkUsage examples
where examples =
[ ("-help","to get help")
, ("[flags] file." ++ bsvSrcSuffix, "to partially compile a Bluespec file")
, ("[flags] -verilog -g mod file." ++ bsvSrcSuffix, "to compile a module to Verilog")
, ("[flags] -verilog -g mod -u file." ++ bsvSrcSuffix, "to recursively compile modules to Verilog")
, ("[flags] -verilog -e topmodule", "to link Verilog into a simulation model")
, ("[flags] -sim -g mod file." ++ bsvSrcSuffix, "to compile to a Bluesim object")
, ("[flags] -sim -g mod -u file." ++ bsvSrcSuffix, "to recursively compile to Bluesim objects")
, ("[flags] -sim -e topmodule", "to link objects into a Bluesim binary")
, ("[flags] -systemc -e topmodule", "to link objects into a SystemC model")
]
exitWithUsage :: ErrorHandle -> String -> IO ()
exitWithUsage errh prog =
hPutStr stderr (usage prog) >> exitFail errh
-- -------------------------
-- Decoded use case for BSC based on the flags
data Decoded = DHelp Flags -- Display the public help message
| DHelpHidden Flags -- Display the full help message
| DUsage -- Display the usage message
| DError [EMsg] -- Report a list of errors
-- No source is given, but print-flag or verbose
-- flags were specified, so this is not an error and
-- no usage message or error is required
| DNoSrc Flags
-- Bluespec source file
| DBlueSrc Flags String
-- entry, Verilog objects to be linked, and any ABin and C files
| DVerLink Flags String [VFileName] [String] [String]
-- entry, ABin files and C files to be generated and linked
| DSimLink Flags String [String] [String]
decodeArgs :: String -> [String] -> String -> ([WMsg], Decoded)
decodeArgs prog args cdir =
let (sets, warnings0, errors0, flags0, anames) =
decodeFlags args ([], [], [], defaultFlags cdir)
-- do some final adjustments
(warnings, errors, flags) = adjustFinalFlags warnings0 errors0 flags0
in if "help-hidden" `elem` sets
then (warnings, DHelpHidden flags)
else if "h" `elem` sets || "help" `elem` sets
then (warnings, DHelp flags)
else if (null errors)
then if (null anames)
then if ((printFlags flags) ||
(printFlagsHidden flags) ||
(printFlagsRaw flags))
then (warnings, DNoSrc flags)
else -- We allow the file names to be omitted if the
-- backend and entry point are both specified
case (entry flags) of
(Just e) | (backend flags == Just Verilog)
-> (warnings, DVerLink flags e [] [] [])
(Just e) | (backend flags == Just Bluesim)
-> (warnings, DSimLink flags e [] [])
_ -> if (verbose flags)
then -- handle -v without compilation
(warnings, DNoSrc flags)
else (warnings, DUsage)
else case (partition isBlueSrcFile anames) of
([name], []) -> (warnings, checkBSrcFlags flags name)
([name], names) ->
-- This is the case of a Bluespec source name accompanied
-- by more things which are not Bluespec source names.
-- If any of those are flags, we issue an error that flags
-- must go before source files.
-- We used to attempt to support the "-e" flag along with
-- "-g" via the "-u" flag (which would do the recompile),
-- but it has been removed. The feature could be added
-- back, if it is properly implemented and regressed.
-- Instead, we error that there is unrecognized text on
-- the command-line. (We could report this for the
-- entire list "names", but that could be too much.
-- We just report the first encountered unknown text.)
let known_ext_names = filter isSrcFile names
in (warnings, checkNamesForFlag names $
if (not (null known_ext_names))
then -- XXX should we check that the user wasn't
-- XXX trying to link, but accidentally
-- XXX typed .bs or .bsv?
DError
[(cmdPosition,
ELinkFilesWithSrc name known_ext_names)]
else DError [(cmdPosition,
EUnrecognizedCmdLineText (head names))])
-- Backwards support for optional -verilog.
([], names) | all isHDLSrcFile names ->
-- generation flag not supported during linking
if (not (null (genName flags)))
then (warnings, DError [(cmdPosition,
EGenNamesForLinking (genName flags))])
else -- Verilog need not be specified, but another backend better not be
case (backend flags) of
Just be | be /= Verilog
-> (warnings, DError [(cmdPosition,
EWrongBackend "Verilog" "Bluesim")])
_ -> case (entry flags) of
Nothing -> (warnings, DError [(cmdPosition, ENoEntryPoint)])
Just top ->
-- set the Verilog flag and go back into
-- the standard flow (so that any other
-- checks of the link flags are performed)
let flags' = flags { backend = Just Verilog }
in (warnings, checkLinkFlags flags' names)
-- Catch-all for linking
([], names) -> (warnings, checkLinkFlags flags names)
-- Multiple src files
-- XXX Do we want a different error if the user was linking
-- XXX and accidentally included multiple BSV files?
(bnames, _) -> (warnings, DError [(cmdPosition, EMultipleSrcFiles)])
else (warnings, DError errors)
-- check that the flags are OK for compiling Bluespec src file
checkBSrcFlags :: Flags -> String -> Decoded
checkBSrcFlags flags filename =
-- if generate is requested, require a backend
if not (null (genName flags)) && (backend flags == Nothing)
then DError [(cmdPosition, ENoBackendCodeGen (genName flags))]
else
-- error if entry point is given
case (entry flags) of
Just e -> DError [(cmdPosition, EEntryForCodeGen e)]
Nothing ->
-- The -remove-dollar flag only applies to the Verilog backend
if (removeVerilogDollar flags && (backend flags /= Just Verilog))
then DError [(cmdPosition, EDollarNoVerilog)]
else
-- If the user hasn't allowed Bluesim/Verilog to diverge,
-- then don't-cares can only be 2-state values
if (not (optUndet flags) &&
( (unSpecTo flags == "X") || (unSpecTo flags == "Z") ))
then DError [(cmdPosition, ENoOptUndetNoXZ (unSpecTo flags))]
else
-- Everything is OK for source compilation
DBlueSrc flags filename
-- check that the flags are OK for linking generated files
-- filenames is guaranteed to be nonEmpty (and not contain .bs/.bsv files)
checkLinkFlags :: Flags -> [String] -> Decoded
checkLinkFlags flags names =
let (anames, names') = partition isABinFile names
(hdlnames, names'') = partition isHDLSrcFile names'
(cnames, bad_names) = partition isCSrcFile names''
errBadName name =
if not (elem '.' name)
then (cmdPosition, ENoSrcExt name)
else (cmdPosition, EUnknownSrcExt (takeSuf name))
bad_name_errs = map errBadName bad_names
in -- check for flags
checkNamesForFlag bad_names $
-- report bad file extensions
if not (null bad_names)
then DError bad_name_errs
else
-- generation flag not supported during linking
if not (null (genName flags))
then DError [(cmdPosition, EGenNamesForLinking (genName flags))]
else
if (removeVerilogDollar flags)
then DError [(cmdPosition, EDollarLink)]
else
-- Verilog backend
if (backend flags == Just Verilog)
then -- An entry point must be specified
case (entry flags) of
Nothing -> DError [(cmdPosition, ENoEntryPoint)]
Just top ->
-- Everything is OK for Verilog linking
DVerLink flags top (map VFileName hdlnames)
anames cnames
else
-- Bluesim backend
if (backend flags == Just Bluesim)
then -- Only 2-state values are allowed for don't-cares
if ( (unSpecTo flags == "X") || (unSpecTo flags == "Z") )
then DError [(cmdPosition, EBluesimNoXZ (unSpecTo flags))]
else
-- Verilog files cannot be provided
if not (null hdlnames)
then DError [(cmdPosition, EVerilogFilesWithSimBackend hdlnames)]
else
-- An entry point must be specified
case (entry flags) of
Nothing -> DError [(cmdPosition, ENoEntryPoint)]
Just top ->
-- Everything is OK for Bluesim linking
DSimLink flags top anames cnames
-- error if no backend chosen
else DError [(cmdPosition, ENoBackendLinking)]
-- and, if so, error that flags must go before source files
checkNamesForFlag :: [String] -> Decoded -> Decoded
checkNamesForFlag bad_names dflt_result =
let
-- function to find the first non-match in "names"
findFirst f (x:xs) = if (f x) then x else findFirst f xs
findFirst f [] = internalError "decodeArgs.findFirst"
in
if (any isFlag bad_names)
then DError [(cmdPosition,
EFlagAfterSrc (findFirst isFlag bad_names))]
else dflt_result
-- -------------------------
-- This is used to parse the "option" pragma, which allows specifying
-- command-line options specific to one module (changing optimizations
-- or other generation behaviors).
-- XXX If there's a way to record the positions of the strings, that would
-- XXX be better to report, but at least we report the module's position
-- XXX in the code, rather than giving "cmdPosition" as the location.
updateFlags :: ErrorHandle -> Position -> [String] -> Flags -> IO Flags
updateFlags errh mod_pos args0 flags = do
let args = concatMap words args0
let (_, warnings, errs, flags', unknown) = decodeFlags args ([], [], [], flags)
let updPos (_, m) = (mod_pos, m)
when ((not . null) warnings) $ bsWarning errh (map updPos warnings)
case (errs, unknown) of
([], []) -> return flags'
([], s:_) -> bsError errh [(mod_pos, EUnknownFlag s)]
(msgs, _) -> bsError errh (map updPos msgs)
-- -------------------------
-- Help Message
exitWithHelp :: ErrorHandle -> String -> [String] -> String -> IO ()
exitWithHelp errh prog args cd =
hPutStrLn stdout (helpMessage Visible prog args cd) >>
exitOK errh
exitWithHelpHidden :: ErrorHandle -> String -> [String] -> String -> IO ()
exitWithHelpHidden errh prog args cd =
hPutStrLn stdout (helpMessage Hidden prog args cd) >>
exitOK errh
helpMessage :: HideExpose -> String -> [String] -> String -> String
helpMessage showHidden prog args cd =
let flags = defaultFlags cd
in
unlines ([
usage prog,
"Compiler flags:"]
++
sort (describeFlags showHidden)
++
["",
"Most flags may be preceded by a `no-' to reverse the effect.",
"Flags later on the command line override earlier ones.",
"Path strings such as the import path may contain the character"
,"`%' representing the current " ++ bluespec ++ " directory, as well as"
,"`+' representing the current value of the path.",
"Lists of error or warning tags may take the values `ALL' and `NONE'.",
"",
"Default flags:",
bluespec ++ " directory: " ++ bluespecDir flags,
"import path: " ++ unPath (ifcPath flags)
] ++
if (Hidden == showHidden) then
["",
"Dump/kill after various passes:"] ++
-- describe the dump flags
(map (("-d" ++) . drop 2 . show)
([minBound .. maxBound ] :: [DumpFlag])) ++
["",
"Dump to a file with -dpass=filename;" ++
"filename may contain the following digraphs:",
" %f file being compiled (without path or extension)",
" %p package name",
" %m module name" ++
" (empty for passes not involved in code generation)",
" %s compiler pass",
" %% the % character",
"% followed by any other character yields that character",
"You may substitute -KILL for -d" ++
" to stop compilation after the named pass",
"",
"-dall enables dumping after every pass;" ++
" an optional filename (with digraphs) may be provided." ++
" If a filename is given for an individual pass, it takes" ++
" precedence over the -dall filename.",
"",
"Note: If a file is dumped to multiple times in a compilation,",
"it is appended to after the first dump.",
"",
"The following trace flags are also available:",
unwords (map ("-"++) (sort traceflags))
]
else
[]
)
describeFlags :: HideExpose -> [String]
describeFlags showHidden =
let getDataFromInfo :: String -> FlagType -> String
getDataFromInfo f (Arg a1 _ _) = f ++ " " ++ a1
getDataFromInfo f (Arg2 a1 a2 _ _) = f ++ " " ++ a1 ++ " " ++ a2
getDataFromInfo f (PassThrough a _ _) = f ++ " " ++ a
getDataFromInfo f _ = f
in
sort [ "-" ++ flag ++ replicate (22 - length flag) ' ' ++ " " ++ desc |
(f, (ft, desc, isHidden)) <- externalFlags,
-- Deprecated flags are never shown
(showHidden == isHidden) || (Visible == isHidden),
let flag = getDataFromInfo f ft ]
-- -------------------------
-- Trace flags
--
-- These are flags which are allowed on the command-line but are ignored
-- by the flag decoding. BSC stages can query their existence by looking
-- for them in the "progArgs". This allows for quick-and-dirty adding of
-- trace flags, without the overhead of updating the Flags structure, etc.
traceflags :: [String]
traceflags = [
"debug-eval-free-vars",
"no-use-layout",
"trace-aopt",
"trace-apaths",
"trace-bs-mcd",
"trace-cfmap",
"trace-cfmaps",
"trace-conAp",
"trace-atf-cache",
"trace-atf-cache-miss",
"trace-ctxreduce",
"trace-debug",
"trace-eval-steps",
"trace-eval-types",
"trace-eval-if",
"trace-eval-nf",
"trace-eval-trans",
"trace-expand-batch-subst",
"trace-full",
"trace-fun-expand",
"trace-genbin",
"trace-heap",
"trace-heap-alloc",
"trace-heap-size",
"trace-icheck",
"trace-inst-tree",
"trace-instance-overlap",
"legacy-inst-index",
"trace-kind-inference",
"trace-lift",
"trace-mergesched",
"trace-mutatormap",
"trace-ncsets",
"trace-no-urgency-edge",
"trace-port-types",
"trace-profile",
"trace-pcmap",
"trace-pcmaps",
"trace-ralloc",
"trace-uugraph",
"trace-scgraph",
"trace-seqgraph",
"trace-sched-steps",
"trace-schedinfo",
"trace-scmap",
"trace-scmaps",
"trace-skip-trim",
"trace-simplify",
"trace-smt-conv",
"trace-smt-test",
"trace-state-loc",
"trace-syn",
"trace-tcvar",
"trace-tc-reducepred",
"trace-tc-satisfy",
"trace-type",
"trace-type-expl",
"trace-type-extsubst",
"trace-usemap",
"trace-disjoint-tests",
"trace-a-definitions",
"trace-clock",
"trace-def-cache",
"trace-cexpr-cache",
"hack-disable-urgency-warnings",
"hack-gate-clock-inputs",
"hack-gate-default-clock",
"hack-no-itype-ftv-cache",
"hack-strict-inst-tree",
"outlaw-sv-kws-as-classic-ids",
"show-qualifiers",
"show-raw-id",
"warn-meth-arg-mismatch"
]
-- -------------------------
-- Default flag values
defaultFlags :: String -> Flags
defaultFlags bluespecdir = Flags {
aggImpConds = True,
allowIncoherentMatches = False,
backend = Nothing,
bdir = Nothing,
biasMethodScheduling = False,
bluespecDir = bluespecdir,
cIncPath = [],
cLibPath = [],
cLibs = [],
cDebug = False,
cFlags = [],
cxxFlags = [],
cppFlags = [],
linkFlags = [],
cdir = Nothing,
cpp = False,
defines = [],
demoteErrors = SomeMsgs [],
disableAssertions = False,
passThroughAssertions = False,
doICheck = True,
dumpAll = Nothing,
dumps = [],
enablePoisonPills = False,
entry = Nothing,
expandATSlimit = 20,
expandIf = False,
fdir = Nothing,
finalcleanup = 1,
genABin = False,
genABinVerilog = False,
genName = [],
genSysC = False,
-- The ifcPath value will be produced from the raw value,
-- by replacing the default-path token with the appropriate value
-- once all the flag values are known, and adding bdir to the front,
-- in adjustFinalFlags.
ifcPathRaw = [ defaultPathToken ],
-- ifcPath = [],
-- XXX this value is for properly constructing the help message
ifcPath = [ "."
, bluespecdir ++ "/Libraries"
],
infoDir = Nothing,
inlineBool = True,
inlineISyntax = True,
inlineSimple = False,
keepAddSize = False,
keepFires = False,
keepInlined = False,
kill = Nothing,
ifLift = True,
letGen = False,
maxTIStackDepth = 1000,
methodBVI = False,
methodConf = False,
methodConditions = False,
neatNames = False,
oFile = "a.out",
optAggInline = True,
optATS = True,
optAndOr = True,
optBitConst = False,
optBool = False,
optFinalPass = True,
optIfMux = False,
optIfMuxSize = 256,
optJoinDefs = True,
optMux = True,
optMuxExpand = False,
optMuxConst = True,
optSched = True,
optUndet = False,
parallelSimLink = 1,
printFlags = False,
printFlagsHidden = False,
printFlagsRaw = False,
preprocessOnly = False,
promoteWarnings = SomeMsgs [],
readableMux = True,
redStepsWarnInterval = 100000,
redStepsMaxIntervals = 10,
relaxMethodEarliness = True,
removeEmptyRules = True,
removeFalseRules = True,
removeInoutConnect = True,
removePrimModules = True,
removeCReg = True,
removeReg = True,
removeRWire = True,
removeCross = True,
removeStarvedRules = False,
removeUnusedMods = False,
removeVerilogDollar = False,
resetName = "RST_N",
resource = RFoff,
rstGate = False,
ruleNameCheck = True,
satBackend = SAT_Yices,
schedConds = True,
schedDOT = False,
schedQueries = [],
showCSyntax = False,
showCodeGen = False,
showElabProgress = False,
showIESyntax = False,
showISyntax = False,
showModuleUse = False,
showRangeConflict = False,
showSchedule = False,
showStats = False,
showUpds = True,
simplifyCSyntax = False,
strictMethodSched = True,
suppressWarnings = SomeMsgs [],
synthesize = False,
systemVerilogTasks = False,
tclShowHidden = False,
testAssert = False,
timeStamps = True,
showVersion = True,
unsafeAlwaysRdy = False,
unSpecTo = "A",
updCheck = False,
useDPI = False,
useNegate = True,
usePrelude = True,
useProvisoSAT = True,
stdlibNames = False,
v95 = False,
vFlags = [],
vdir = Nothing,
-- The vPath value will be produced from the raw value,
-- by replacing the default-path token with the appropriate value
-- once the full ifcPath is known, and adding vdir to the front,
-- in adjustFinalFlags.
vPathRaw = [ defaultPathToken ],
vPath = [],
vpp = True,
vsim = Nothing,
verbosity = Normal,
verilogDeclareAllFirst = True,
verilogFilter = [],
warnActionShadowing = True,
warnMethodUrgency = True,
warnUndetPred = False
}
-- Default path value replaced in adjustFinalFlags
defaultPathToken :: String
defaultPathToken = "$DEFAULT_PATH"
-- -------------------------
-- decodeFlags
--
-- Function to parse a list of command-line arguments as flags
-- Returns a list of error messages, the result of processing flags,
-- and a list of non-flags (the trace flags) which were set.
decodeFlags :: [String] -> ([String],[WMsg], [EMsg], Flags) -> ([String],[WMsg], [EMsg], Flags, [String])
decodeFlags (('-':'-':s):ss) (sets, warnings, bad, flags) | (length s > 1) && (head s /= '-') =
-- accept --option as a synonym for -option (for long options)
decodeFlags (('-':s):ss) (sets, warnings, bad, flags)
decodeFlags (s@("-dall"):ss) (sets, warnings, bad, flags) =
decodeFlags ss (sets, warnings, bad, flags { dumpAll = Just Nothing })
decodeFlags (s:ss) (sets, warnings, bad, flags) | Just file <- stripPrefix "-dall=" s =
decodeFlags ss (sets, warnings, bad, flags { dumpAll = Just (Just file) })
decodeFlags (s@('-':'d':d):ss) (sets, warnings, bad, flags) | (isDumpName d) =
case reads ("DF" ++ d) of
[(df, "")]
-> decodeFlags ss (sets, warnings, bad, flags { dumps = (df, Nothing) : dumps flags })
[(df, '=':file)]
-> decodeFlags ss (sets, warnings, bad, flags { dumps = (df, Just file) : dumps flags })
_ -> internalError ("decodeFlags: isDumpName: " ++ ('d':d))
decodeFlags (s@('-':'K':'I':'L':'L':d):ss) (sets, warnings, bad, flags) =
case (reads ("DF" ++ d), kill flags) of
([(df, "")], Nothing)
-> decodeFlags ss (sets,warnings, bad, flags { kill = (Just (df, Nothing)) })
([(df, '=':package_or_mod_name)], Nothing)
-> decodeFlags ss (sets,warnings, bad, flags { kill = (Just (df, Just package_or_mod_name)) })
([(df, "")], Just prev)
-> let eDupKill = (cmdPosition, EDupKillFlag ("-KILL" ++ d) ("-KILL" ++ drop 2 (show prev)))
in decodeFlags ss (sets,warnings, eDupKill : bad, flags)
_ -> decodeFlags ss (sets,warnings, badflag ("KILL"++d) bad, flags)
decodeFlags (('-':s):ss) (sets,warnings, bad, flags) =
if take 3 s == "no-" then
let drop3s = drop 3 s in
case lookup drop3s flagsTable of
Nothing -> decodeFlags ss (sets, warnings, badflag s bad, flags)
Just flagtype ->
case flagtype of
-- this will report "Deprecated flag -foo" even if "-no-foo" is specified.
-- We do this to prevent the helpful message from being confusing.
Toggle doflag _ -> decodeFlags ss
(drop3s:sets, (getDeprecation drop3s warnings), bad, doflag flags False)
_ -> let eNonToggle = (cmdPosition, ENotToggleFlag ('-':drop3s))
in decodeFlags ss (sets,warnings, eNonToggle : bad, flags)
else
case lookup s flagsTable of
Nothing -> decodeFlags ss (sets, warnings, badflag s bad, flags)
Just flagtype -> let
perhaps_warn :: [WMsg]
perhaps_warn = getDeprecation s warnings
-- We give a DEPRECATED warning even if the flag is otherwise used INcorrectly.
-- Of course we give a DEPRECATED warning if the flag is used correctly.
in
case flagtype of
Toggle doflag _ -> decodeFlags ss (s:sets, perhaps_warn, bad, doflag flags True)
NoArg dofunc _ ->
if (null ss) || (isFlag (head ss)) || (isSrcFile (head ss)) then
case (dofunc flags) of
Left flags' -> decodeFlags ss (s:sets, perhaps_warn, bad, flags')
Right emsg -> decodeFlags ss (sets, perhaps_warn, emsg:bad, flags)
else
let eHasArg = (cmdPosition, ENoArgFlag ('-':s))
in decodeFlags ss (sets,perhaps_warn, eHasArg : bad, flags)
Arg _ dofunc _ ->
let eExpectsArg = (cmdPosition, EOneArgFlag ('-':s))
in case ss of
(s2:ss') ->
if (isFlag s2) then
decodeFlags ss (sets, perhaps_warn, eExpectsArg : bad, flags)
else
case (dofunc flags s2) of
Left flags' -> decodeFlags ss' (s:sets, perhaps_warn, bad, flags')
Right emsg -> decodeFlags ss' (sets, perhaps_warn, emsg:bad, flags)
[] -> decodeFlags ss (sets, perhaps_warn, eExpectsArg : bad, flags)
Arg2 _ _ dofunc _ ->
let eExpectsArg2 = (cmdPosition, ETwoArgFlag ('-':s))
in case ss of
(s2:s3:ss') ->
if (isFlag s2) || (isFlag s3) then
decodeFlags ss (sets, perhaps_warn, eExpectsArg2 : bad, flags)
else
case (dofunc flags s2 s3) of
Left flags' -> decodeFlags ss' (s:sets, perhaps_warn, bad, flags')
Right emsg -> decodeFlags ss' (sets, perhaps_warn, emsg:bad, flags)
-- for the cases when there's only 1 or 0 elements left
_ -> decodeFlags ss (sets, perhaps_warn, eExpectsArg2 : bad, flags)
PassThrough _ dofunc _ ->
let eExpectsArg = (cmdPosition, EOneArgFlag ('-':s))
in case ss of
(s2:ss') ->
case (dofunc flags s2) of
Left flags' -> decodeFlags ss' (s:sets, perhaps_warn, bad, flags')
Right emsg -> decodeFlags ss' (sets, perhaps_warn, emsg:bad, flags)
[] -> decodeFlags ss (sets, perhaps_warn, eExpectsArg : bad, flags)
Alias f2 -> decodeFlags (("-"++f2):ss) (sets, perhaps_warn, bad, flags)
Resource rf -> decodeFlags ss (s:sets, perhaps_warn, bad, flags { resource = rf })
decodeFlags ss (sets, warnings, bad, flags) = (sets, warnings, bad, flags, ss)
isFlag :: String -> Bool
isFlag ('-':_) = True
isFlag _ = False
isDumpName :: String -> Bool
isDumpName s =
case ((reads ("DF" ++ s)) :: [(DumpFlag, String)]) of
[(df, "")] -> True
[(df, '=':_)] -> True
_ -> False
-- If the argument is not in the nonflags (the trace flags),
-- then it is added to the list of bad strings, otherwise the
-- list of bad strings is returned unchanged.
badflag ::String -> [EMsg] -> [EMsg]
badflag s bad
| s `elem` traceflags = bad
| otherwise = ((cmdPosition, EUnknownFlag ('-':s)) : bad)
getDeprecation :: String -> [WMsg] -> [WMsg]
-- second argument gives all the error messages so far
getDeprecation s bad = case (lookup s externalFlags) of
Just (_, _, (Deprecated message))
-> (cmdPosition, (WDeprecatedFlag s message)) : bad
Just (_, _, _) -> bad
_ -> internalError ("inconsistency in flag decoding")
-- -------------------------
-- adjustFinalFlags
--
-- Function to be used after "decodeFlags", to check the well-formedness
-- of the flags as a whole. (Decoding can only check flags as it goes.)
canonDir :: String -> Either String String
canonDir d =
let handler ioe = return $ Left $ ioeGetErrorString ioe
ioFn = do -- on some systems, canonicalise path doesn't error
-- so we explicitly check
_ <- getDirectoryContents d
-- Some versions of "canonicalizePath" don't drop the trailing path separator
canon_d <- canonicalizePath d >>= return . dropTrailingPathSeparator
return $ Right canon_d
in unsafePerformIO $ catchIO ioFn handler
filterPath :: [String] -> [String] -> [String]
filterPath rem_dirs0 path =
let normFn d = either (const (normalise d)) id $ canonDir d
rem_dirs = map normFn rem_dirs0
keepDir d = (normFn d) `notElem` rem_dirs
in filter keepDir path
checkPath :: String -> String -> [String] -> Maybe String ->
([String], [WMsg], [EMsg])
checkPath path_flag_str dir_flag_str path mdir =
let
foldFn :: (M.Map String String, S.Set String, M.Map String (S.Set String), [String]) ->
String ->
(M.Map String String, S.Set String, M.Map String (S.Set String), [String])
foldFn (fail_map, seen_set, dup_map, nub_path) dir
| (dir == defaultPathToken) =
-- skip default tokens
(fail_map, seen_set, dup_map, (dir:nub_path))
foldFn (fail_map, seen_set, dup_map, nub_path) dir =
case (canonDir dir) of
Left err_str ->
let -- at least normalise as much as possible,
-- so that we don't report duplicate warnings
dir' = normalise dir
fail_map' = M.insert dir' err_str fail_map
in (fail_map', seen_set, dup_map, nub_path)
Right canon_dir ->
if (canon_dir `S.member` seen_set)
then let dup_map' = M.insertWith (S.union)
canon_dir (S.singleton dir) dup_map
in (fail_map, seen_set, dup_map', nub_path)
else let seen_set' = S.insert canon_dir seen_set
in (fail_map, seen_set', dup_map, (dir:nub_path))
(access_fail_map, path_seen_set, path_dups_map, rev_nub_path) =
foldl foldFn (M.empty, S.empty, M.empty, []) path
-- we use a map, to remove duplicate warnings
access_warnings =
let mkWarn (d, str) =
(cmdPosition, WOpenPathDirFailure path_flag_str d str)
in map mkWarn (M.toList access_fail_map)
path_dups =
-- use the canonical name
M.keys path_dups_map
(access_errors, dir_is_dup) =
case (mdir) of
Nothing -> ([], False)
Just dir ->
case (canonDir dir) of
Left err_str ->
let emsg = (cmdPosition,
EOpenOutputDirFailure dir_flag_str dir err_str)
-- attempt to still determine if it's a duplicate
dir' = normalise dir
in ([emsg], dir' `S.member` path_seen_set)
Right canon_dir ->
([], canon_dir `S.member` path_seen_set)
dup_warnings =
if (not (null path_dups))
then [(cmdPosition, WDuplicatePathDirs path_flag_str dir_flag_str
dir_is_dup path_dups)]
else []
in
(reverse rev_nub_path, access_warnings ++ dup_warnings, access_errors)
-- combine the warnings from two passes
-- XXX this seems more readable than returning the raw warning data and
-- XXX constructing the warnings at the end
combinePathWarnings :: [WMsg] -> [WMsg]
combinePathWarnings warns0 =
let
-- assume cmdPosition
foldFn (_, WDuplicatePathDirs s1 s2 b ds) (ws, dup_map) =
let combFn (b1, ds1) (b2, ds2) = (b1 || b2, S.union ds1 ds2)
in (ws, M.insertWith combFn (s1, s2) (b, S.fromList ds) dup_map)
foldFn w (ws, dup_map) = (w:ws, dup_map)
mkDupWarn ((s1,s2), (b, ds)) =
(cmdPosition, WDuplicatePathDirs s1 s2 b (S.toList ds))
(other_warns, dup_map) = foldr foldFn ([], M.empty) warns0
dup_warns = map mkDupWarn (M.toList dup_map)
in
other_warns ++ dup_warns
-- make some adjustments to flags, once all values are visible
adjustFinalFlags :: [WMsg] -> [EMsg] -> Flags -> ([WMsg], [EMsg], Flags)
adjustFinalFlags warns0 errs0 flags0 =
let
bspecdir = (bluespecDir flags0)
checkDir :: String -> Maybe String -> ([WMsg], [EMsg])
checkDir dir_flag_str mdir =
case mdir of
Nothing -> ([], [])
Just dir ->
case (canonDir dir) of
Right _ -> ([], [])
Left err_str ->
let emsg = (cmdPosition,
EOpenOutputDirFailure dir_flag_str dir err_str)
in ([], [emsg])
-- ==========
-- -p / -bdir checks
-- add bdir to the head of the import path.
-- replace the default path with the Prelude and Libraries locations
-- XXX make sure this is in sync with the default value (ifcPath)
-- XXX displayed in the help message
def_bpath = [ "."
, bspecdir ++ "/Libraries"
]
bdir_path = case (bdir flags0) of
Just dir -> [dir]
Nothing -> []
bpathraw = ifcPathRaw flags0
-- warn about duplicates in the raw path
(bpathraw_nub, b_warns1, b_errs1) =
checkPath "p" "bdir" bpathraw Nothing
-- construct the visible path
bpath = bdir_path ++
replacePathToken defaultPathToken bpathraw_nub def_bpath
-- warn about duplicates introduced from the default (?)
(bpath_nub, b_warns2, b_errs2) =
checkPath "p" "bdir" bpath (bdir flags0)
-- combine the errors and warnings
b_warns = combinePathWarnings (b_warns1 ++ b_warns2)
b_errs = b_errs1 ++ b_errs2
-- update flags with the new path, removing duplicates
flags1 = flags0 { ifcPathRaw = bpathraw_nub, ifcPath = bpath_nub }
-- ==========
-- -vsearch / -vdir checks
-- add vdir to the head of the Verilog search path
-- otherwise, add "."
-- replace the default vsearch path token with
-- the Verilog and Libraries locations if the token is
-- still in the vPath.
-- if vdir is not used, include every place in ifcPath, too.
-- XXX The ifcPath should be included with "." at the head
-- XXX because it's also conceptually the default "vdir".
-- XXX Don't use "."! Use ifcPath plus the directory of all
-- XXX source files provided on the command line!
prim_path = [bspecdir ++ "/Verilog"]
azure_path = [bspecdir ++ "/Libraries"]
(vdir_path,ifc_path) =
case (vdir flags1) of
Just dir -> ([dir],[])
Nothing ->
-- use "." as the vdir
-- return the ifc path without "." (to avoid duplicates)
-- and remove the azure path (to place at the end?)
(["."], filterPath (".":azure_path) (ifcPath flags1))
def_vpath = ifc_path ++ azure_path ++ prim_path
vpathraw = vPathRaw flags1
-- warn about duplicates in the raw path
(vpathraw_nub, v_warns1, v_errs1) =
checkPath "vsearch" "vdir" vpathraw Nothing
-- construct the visible path
vpath = vdir_path ++
replacePathToken defaultPathToken vpathraw_nub def_vpath
-- warn about duplicates introduced from the default (?)
(vpath_nub, v_warns2, v_errs2) =
checkPath "vsearch" "vdir" vpath (vdir flags1)
-- combine the errors and warnings
(v_warns, v_errs) =
let ws = combinePathWarnings (v_warns1 ++ v_warns2)
es = v_errs1 ++ v_errs2
in -- only warn, not error, if the vdir flag won't be used
if (backend flags1 == Just Verilog)
then (ws, es)