forked from B-Lang-org/bsc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrelude.bs
4376 lines (3586 loc) · 144 KB
/
Prelude.bs
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
package Prelude(
{-Add(..), Max(..), Log(..),-}
Monad(..), MonadFix(..),
Bits(..), Eq(..),
Literal(..), RealLiteral(..), SizedLiteral(..), StringLiteral(..),
Ord(..), Bounded(..), Bitwise(..), BitReduction(..), FShow(..), DefaultValue(..),
PrimParam(..), PrimPort(..),
Bit, Rules, Module, Integer, Real, String, Char, SizeOf, Id__,
PrimAction, ActionValue, Action, ActionValue_, ActionWorld, AVStruct,
TAdd, TSub, TMul, TDiv, TLog, TExp, TMax, TMin, TStrCat, TNumToStr,
Nat(..),
IsModule(..), addModuleRules, addRules,
__value, -- XXX not good
(++), split, bitconcat,
BitExtend(..),
UInt, Int,
signedLT, signedLE, signedGT, signedGE,
signedShiftRight,
signedMul, signedQuot,
unsignedMul, unsignedQuot,
error, warning, message,
errorM, warningM, messageM,
primError, primWarning, primMessage,
primGenerateError, primPoisonedDef,
moduleFix,
splitIf, nosplitIf, nosplitDeepIf, splitDeepIf,
splitDeepAV, nosplitDeepAV,
Clock, Reset, Inout, Inout_, Power,
primInoutCast0, primInoutUncast0,
exposeCurrentClock,
exposeCurrentReset,
clockOf,
clocksOf,
noClock,
resetOf,
resetsOf,
noReset,
primModuleClock, primModuleReset, primBuildModule,
changeSpecialWires, -- primCLOCK, primRESET, primPOWER, primSW,
sameFamily, isAncestor,
chkClockDomain,
isStaticValue,
impCondOf,
primZeroExt, primSignExt, primTrunc,
primConcat, primSplit, PrimPair(..),
primOrd, primChr,
primValueOf,
primStringOf,
StringProxy,
_when_,
primExtract,
Position__, getStringPosition, setStringPosition, printPosition, noPosition, getEvalPosition,
Type, typeOf, printType, isInterfaceType,
forceIsModule,
Name__, primGetName, primMakeName, primJoinNames, primExtendNameIndex,
primGetNamePosition, primGetNameString,
primGetParamName,
setStateName, primGetModuleName, primSavePortType,
Attributes__, setStateAttrib,
primJoinActions, primNoActions, toPrimAction, fromPrimAction,
primJoinRules, primNoRules, emptyRules,
primFix,
primSeq,
PrimDeepSeqCond(..), PrimDeepSeqCond'(..),
primSeqCond,
noAction, (:<-),
toActionValue_,
fromActionValue_,
primDynamicError,
primStringConcat,
primStringToInteger,
(+++), strConcat, stringLength,
quote, doubleQuote,
stringSplit, stringHead, stringTail, stringCons,
stringToCharList, charListToString,
charToString,
charToInteger, integerToChar,
isSpace, isLower, isUpper, isAlpha, isAlphaNum,
isDigit, isOctDigit, isHexDigit,
toUpper, toLower,
digitToInteger, digitToBits, integerToDigit, bitsToDigit,
hexDigitToInteger, hexDigitToBits, integerToHexDigit, bitsToHexDigit,
primCharToString,
primUIntBitsToInteger, primIntBitsToInteger,
($), (∘), id, const, constFn, flip, while, curry, uncurry, asTypeOf,
liftM, liftM2, bindM,
(<+>), rJoin,
(<+), (+>), preempts, preempted, rJoinPreempts,
rJoinDescendingUrgency,
rJoinExecutionOrder,
rJoinMutuallyExclusive, rJoinConflictFree,
-- for lack of better primitive handling
primAdd, primSub, primAnd, primOr, primXor,
primSL, primSRL, primSRA,
primInv, primNeg,
primULE, primULT,
primSLE, primSLT,
primBNot, primBAnd, primBOr, primMul,
primQuot, primRem,
PrimIndex(..),
PrimShiftIndex(..),
PrimSelectable(..),
PrimUpdateable(..),
PrimWriteable(..),
primUpdateRangeFn,
Bool(..), not, (&&), (||), _if,
(===), (!==),
PrimUnit(..),
Reg(..), mkReg, mkRegU, mkRegA, asReg, readReg, writeReg, asIfc,
Maybe(..), unJust, isJust, isValid, validValue, fromMaybe,
Either(..), isLeft, isRight, either,
Empty(..),
add, div, mod, quot, rem, exp,
bind_, fmap,
Arith(..),
max, min,
reverseBits,
countOnes, countZerosMSB, countZerosLSB,
-- system tasks
$display,$displayh,$displayb,$displayo,
$write,$writeh,$writeb,$writeo,
$fwrite,$fwriteb,$fwriteo,$fwriteh,
$sformat,$sformatAV,$swrite,$swriteAV,
$swriteh,$swritehAV,$swriteb,$swritebAV,$swriteo,$swriteoAV,
$fdisplay,$fdisplayb,$fdisplayo,$fdisplayh,
$error, $warning, $info, $fatal,
$SVA, SvaParam(..),
$random,
$stop,$finish,
$dumpon,$dumpoff,$dumpvars,$dumpall,
$dumpfile,$dumpflush,$dumplimit,
File(..),
$fopen,$fclose,$fflush,
$fgetc, $ungetc,
stdin, stdout, stderr,
stdout_mcd,
$time, $stime,
$test$plusargs,
--- XXX for internal use only - these will not work in user code
$signed, $unsigned,
-- tuples
Has_tpl_1(..),
Tuple2, tuple2, Has_tpl_2(..),
Tuple3, tuple3, Has_tpl_3(..),
Tuple4, tuple4, Has_tpl_4(..),
Tuple5, tuple5, Has_tpl_5(..),
Tuple6, tuple6, Has_tpl_6(..),
Tuple7, tuple7, Has_tpl_7(..),
Tuple8, tuple8, Has_tpl_8(..),
-- lists required for desugaring
List(..),
cons, nil,
isCons, isNil,
decodeList,
-- other list primitives
listLength,
-- infixed operators not available in BSV
compose, composeM,
-- utility display functions
displayHex,
displayDec,
displayOct,
displayBin,
-- a constant with all bits set
constantWithAllBitsSet, constantWithAllBitsUnset,
-- undefined values
PrimMakeUndefined(..), PrimMakeUndefined'(..), PrimMakeUndefined''(..),
primBuildUndefined,
primMakeRawUndefined,
-- uninitialized values (BSV only)
PrimMakeUninitialized(..), PrimMakeUninitialized'(..), PrimMakeUninitialized''(..),
primMakeRawUninitialized,
primUninitialized,
Fmt,
primFmtConcat,
$format,
integerToString,
bitToString,
Array(..),
primArrayNew,
primArrayNewU,
arrayLength,
primArrayInitialize,
primArrayCheck,
-- Real
realToString, $realtobits, $bitstoreal,
primRealSin, primRealCos, primRealTan,
primRealSinH, primRealCosH, primRealTanH,
primRealASin, primRealACos, primRealATan,
primRealASinH, primRealACosH, primRealATanH,
primRealATan2,
primRealSqrt,
primRealTrunc, primRealCeil, primRealFloor, primRealRound,
primSplitReal, primDecodeReal, primRealToDigits,
primRealIsInfinite, primRealIsNegativeZero,
-- "Environment variables"
genC,
genVerilog,
genPackageName,
genModuleName,
compilerVersion,
date,
epochTime,
buildVersion,
testAssert,
-- Ordering type for working with comparators
Ordering(..),
Handle, IOMode(..),
openFile, hClose,
hIsEOF, hIsOpen, hIsClosed, hIsReadable, hIsWritable,
BufferMode(..),
hSetBuffering, hGetBuffering, hFlush,
hPutStr, hPutStrLn, hPutChar,
hGetLine, hGetChar,
-- Generics
Generic(..), Conc(..), ConcPrim(..), ConcPoly(..),
Meta(..), MetaData(..), StarArg(..), NumArg(..), StrArg(..), ConArg(..),
MetaConsNamed(..), MetaConsAnon(..), MetaField(..)
) where
infixr 0 $
infixr 0 :=
infixr 2 ||
infixr 3 &&
infixr 4 |
infixr 5 &
infixr 5 ^
infixr 5 ~^
infixr 5 ^~
infix 6 ==
infix 6 /=
infix 6 <=
infix 6 >=
infix 6 <
infix 6 >
infix 7 <<
infix 7 >>
infixr 8 ++
infixl 10 +
infixl 10 -
infixl 11 *
infixl 11 /
infixl 11 %
infixr 13 ∘
-- ================================================================
--@ \subsection{Typeclasses}
--@ \index{typeclass}
{-
--@ These classes are built into the compiler, and express size relationships.
--@ \index{Add@\te{Add} (built-in class of size types)}
--@ \index{Mul@\te{Mul} (built-in class of size types)}
--@ \index{Div@\te{Div} (built-in class of size types)}
--@ \index{Log@\te{Log} (built-in class of size types)}
--@ \index{Max@\te{Max} (built-in class of size types)}
--@ \index{Min@\te{Min} (built-in class of size types)}
--@ # 5
class (Add :: # -> # -> # -> *) a b c | a b -> c, b c -> a, c a -> b where { }
class (Mul :: # -> # -> # -> *) a b c | a b -> c, b c -> a, c a -> b where { }
class (Div :: # -> # -> # -> *) a b c | a b -> c where { }
class (Log :: # -> # -> *) a b | a -> b where { }
class (Max :: # -> # -> # -> *) a b c | a b -> c where { }
class (Min :: # -> # -> # -> *) a b c | a b -> c where { }
-}
--@ \index{Monad@\te{Monad} (type class)}
--@ \index{bind@\te{bind} (\te{Monad} class method)}
--@ \index{return@\te{return} (\te{Monad} class method)}
--@ Monads are an advanced topic and can be ignored on first reading.
--@ \begin{libverbatim}
--@ typeclass Monad #(type m);
--@ function m#(b) bind(m#(a) x1, function m#(b) x2(a x1));
--@ function m#(a) return(a x1);
--@ endtypeclass
--@ \end{libverbatim}
class Monad m where
bind :: m a -> (a -> m b) -> m b
return :: a -> m a
--@ The class of monads that admit recursion (advanced topic; can be ignored on first reading).
--@ \index{MonadFix@\te{MonadFix} (type class)}
--@ \index{mfix@\te{mfix} (\te{MonadFix} class method)}
--@ \begin{libverbatim}
--@ typeclass MonadFix #(type m)
--@ provisos (Monad#(m));
--@ function m#(a) mfix(function m#(a) x1(a x1));
--@ endtypeclass
--@ \end{libverbatim}
class (Monad m) => MonadFix m where
mfix :: (a -> m a) -> m a
fmap :: (Monad m) => (a -> b) -> (m a -> m b)
fmap f xs = do
{-# hide #-}
_x <- xs
return (f _x)
--@ The class of types that can be converted to bit vectors and back.
--@ \index{Bits@\te{Bits} (type class)}
--@ \index{pack@\te{pack} (\te{Bits} class method)}
--@ \index{unpack@\te{unpack} (\te{Bits} class method)}
--@ \begin{libverbatim}
--@ typeclass Bits #(type a, type n)
--@ dependencies a -> n;
--@ function Bit#(n) pack(a x);
--@ function a unpack(Bit#(n) x);
--@ endtypeclass
--@ \end{libverbatim}
class coherent Bits a n | a -> n where
pack :: a -> Bit n
unpack :: Bit n -> a
--@ The class of types on which equality is defined.
--@ \index{Eq@\te{Eq} (type class)}
--@ \index{==@{\te{==}} (\te{Eq} class method)}
--@ \index{!=@{\te{!=}} (\te{Eq} class method)}
--@ \begin{libverbatim}
--@ typeclass Eq #(type a);
--@ function Bool (==)(a x, a y);
--@ function Bool (!=)(a x, a y);
--@ endtypeclass
--@ \end{libverbatim}
class Eq a where
(==) :: a -> a -> Bool
x == y = not (x /= y)
(/=) :: a -> a -> Bool
x /= y = not (x == y)
--@ The class of types for which integer literals can be used.
--@ \index{Literal@\te{Literal} (type class)}
--@ \index{fromInteger@\te{fromInteger} (\te{Literal} class method)}
--@ \begin{libverbatim}
--@ typeclass Literal #(type a);
--@ function a fromInteger(Integer x);
--@ endtypeclass
--@ \end{libverbatim}
--
-- Note that the parameter to Literal is defaulted to Integer or Nat
-- (in that order) when the type variable in the context does not
-- appear in the base type.
--
class Literal a where
fromInteger :: Integer -> a
inLiteralRange :: a -> Integer -> Bool
class RealLiteral a where
fromReal :: Real -> a
class SizedLiteral a n | a -> n where
fromSizedInteger :: Bit n -> a
-- Because SV doesn't have a separate syntax for character literals,
-- we overload string literals
class StringLiteral a where
fromString :: String -> a
-- Ordering type used as the result of generic comparators
data Ordering = LT | EQ | GT deriving (Eq, Bits, Bounded)
--@ The class of types on which comparison operations are defined.
--@ \index{Ord@\te{Ord} (type class)}
--@ \index{<@{\te{<}} (\te{Ord} class method)}
--@ \index{<=@{\te{<=}} (\te{Ord} class method)}
--@ \index{>@{\te{>}} (\te{Ord} class method)}
--@ \index{>=@{\te{>=}} (\te{Ord} class method)}
--@ \index{compare@\te{compare} (\te{Ord} class method)}
--@ \index{min@\te{min} (\te{Ord} class method)}
--@ \index{max@\te{max} (\te{Ord} class method)}
--@ \begin{libverbatim}
--@ typeclass Ord #(type a);
--@ function Bool (<)(a x, a y);
--@ function Bool (<=)(a x, a y);
--@ function Bool (>)(a x, a y);
--@ function Bool (>=)(a x, a y);
--@ function Ordering compare(a x, a y);
--@ function a min(a x, a y);
--@ function a max(a x, a y);
--@ endtypeclass
--@ \end{libverbatim}
--@ Minimal complete definition is either <= or compare.
class Ord a where
-- relational operators
(<) :: a -> a -> Bool
x < y = (compare x y) == LT
(<=) :: a -> a -> Bool
x <= y = (compare x y) /= GT
(>) :: a -> a -> Bool
x > y = (compare x y) == GT
(>=) :: a -> a -> Bool
x >= y = (compare x y) /= LT
-- generalized comparison
compare :: a -> a -> Ordering
compare x y = if (x <= y)
then if (y <= x)
then EQ
else LT
else GT
-- min and max selectors
min :: a -> a -> a
min x y = if x <= y then x else y
max :: a -> a -> a
max x y = if x <= y then y else x
--@ The class of types with a finite range.
--@ \index{Bounded@\te{Bounded} (type class)}
--@ \index{minBound@\te{minBound} (\te{Bounded} class method)}
--@ \index{maxBound@\te{maxBound} (\te{Bounded} class method)}
--@ \begin{libverbatim}
--@ typeclass Bounded #(type a);
--@ a minBound;
--@ a maxBound;
--@ endtypeclass
--@ \end{libverbatim}
class Bounded a where
minBound :: a
maxBound :: a
--@ The class of types on which bitwise operations are defined.
--@ \index{Bitwise@\te{Bitwise} (type class)}
--@ \index{&@{\verb'&'} (\te{Bitwise} class ``and'' method)}
--@ \index{"|@{\verb'"|'} (\te{Bitwise} class ``or'' method)}
--@ \index{^@{\verb'^'} (\te{Bitwise} class ``exclusive or'' method)}
--@ \index{~^@{\verb'~^'} (\te{Bitwise} class ``exclusive nor'' method)}
--@ \index{^~@{\verb'^~'} (\te{Bitwise} class ``exclusive nor'' method)}
--@ \index{invert@\te{invert} (\te{Bitwise} class method)}
--@ \index{<<@\te{<}\te{<} (\te{Bitwise} class ``left shift'' method)}
--@ \index{>>@\te{>}\te{>} (\te{Bitwise} class ``right shift'' method)}
--@ \begin{libverbatim}
--@ typeclass Bitwise #(type a);
--@ function a (&)(a x1, a x2);
--@ function a (|)(a x1, a x2);
--@ function a (^)(a x1, a x2);
--@ function a (~^)(a x1, a x2);
--@ function a (^~)(a x1, a x2);
--@ function a invert(a x1);
--@ function a (<<)(a x1, Nat x2);
--@ function Bit#(1) msb(a x1);
--@ function Bit#(1) lsb(a x1);
--@ function a (>>)(a x1, Nat x2);
--@ endtypeclass
--@ \end{libverbatim}
class Bitwise a where
(&) :: a -> a -> a -- and
(|) :: a -> a -> a -- or
(^) :: a -> a -> a -- exclusive or
(~^) :: a -> a -> a -- exclusive nor
(^~) :: a -> a -> a -- exclusive nor
invert :: a -> a
(<<) :: (PrimShiftIndex ix dx) => a -> ix -> a -- left-shift (shift in zero)
(>>) :: (PrimShiftIndex ix dx) => a -> ix -> a -- right-shift (shift in zero)
msb :: a -> Bit 1
lsb :: a -> Bit 1
class (BitReduction :: (# -> *) -> # -> *) a n where
reduceAnd :: a n -> a 1 -- reduction with &
reduceOr :: a n -> a 1 -- reduction with |
reduceXor :: a n -> a 1 -- reduction with ^
reduceNand :: a n -> a 1 -- ! reduction with &
reduceNor :: a n -> a 1 -- ! reduction with |
reduceXnor :: a n -> a 1 -- ! reduction with ^
class (BitExtend :: # -> # -> (# -> *) -> *) a b c where
zeroExtend :: (c a) -> (c b)
signExtend :: (c a) -> (c b)
extend :: (c a) -> (c b)
truncate :: (c b) -> (c a)
--@ The class of types on which arithmetic ops are defined.
--@ \index{Arith@\te{Arith} (type class)}
--@ \index{+@{\te{+}} (\te{Arith} class ``add'' method)}
--@ \index{-@{\te{-}} (\te{Arith} class ``subtract'' method)}
--@ \index{negate@\te{negate} (\te{Arith} class method)}
--@ \index{*@\te{*} (\te{Arith} class ``multiply'' method)}
--@ \index{*@\te{/} (\te{Arith} class ``quotient'' method)}
--@ \index{*@\te{%} (\te{Arith} class ``remainder'' method)}
--@ \begin{libverbatim}
--@ typeclass Arith #(type a)
--@ provisos (Literal#(a));
--@ function a (+)(a x1, a x2);
--@ function a (-)(a x1, a x2);
--@ function a negate(a x1);
--@ function a (*)(a x1, a x2);
--@ function a (/)(a x1, a x2);
--@ function a (%)(a x1, a x2);
--@ endtypeclass
--@ \end{libverbatim}
class (Literal a) => Arith a where
(+) :: a -> a -> a
(-) :: a -> a -> a
negate :: a -> a
(*) :: a -> a -> a
(/) :: a -> a -> a
(%) :: a -> a -> a
-- absolute value
abs :: a -> a
abs x = let t = quote (printType (typeOf x))
in error ("The function `abs' is not defined for " +++ t)
-- a unit value with the same sign, s.t. abs(x)*signum(x) = x
signum :: a -> a
signum x =
let t = quote (printType (typeOf x))
in error ("The function `signum' is not defined for " +++ t)
-- logarithm and exponentiation
(**) :: a -> a -> a -- b to the x
(**) b x =
let t = quote (printType (typeOf x))
in error ("The operator `**' is not defined for " +++ t)
exp_e :: a -> a -- e to the x ("expe"?)
exp_e x =
let t = quote (printType (typeOf x))
in error ("The function `exp_e' is not defined for " +++ t)
log :: a -> a -- log base e
log x =
let t = quote (printType (typeOf x))
in error ("The function `log' is not defined for " +++ t)
logb :: a -> a -> a -- log base b
logb b x = --(log x) / (log b)
let t = quote (printType (typeOf x))
in error ("The function `logb' is not defined for " +++ t)
log2 :: a -> a -- log base 2
log2 x = --logb 2 x
let t = quote (printType (typeOf x))
in error ("The function `log2' is not defined for " +++ t)
log10 :: a -> a -- log base 10
log10 x = --logb 10 x
let t = quote (printType (typeOf x))
in error ("The function `log10' is not defined for " +++ t)
add :: (Arith a) => a -> a -> a
add x y = x + y
-- The class of types that may be used as index values
--
-- Note that the index parameter (the second parameter) to
-- PrimSelectable is defaulted to Integer or Nat (in that order) when
-- the type variable in the context does not appear in the base type.
--
-- Note that we require Literal for the index. This prevents
-- spurious errors about Literal context missing when the user
-- writes "xs[1]" and the PrimSelectable context can't be satisfied.
--
class (Literal a, Eq a) => PrimIndex a b | a -> b where
isStaticIndex :: a -> Bool
-- argument should be a elaboration-time constant
toStaticIndex :: a -> Integer
-- argument should be a runtime value
-- (or poor elaboration performance should be expected)
toDynamicIndex :: a -> Bit b
class (PrimIndex a b, Ord a) => PrimShiftIndex a b | a -> b where {}
-- converts to Bit n statically if possible, or dynamically if not
-- also performs a check that the value is nonnegative
indexableToBits :: (PrimShiftIndex a n) => a -> Bit n
indexableToBits x =
if (isStaticIndex x) then
-- primIntegerToUIntBits will complain if negative
primIntegerToUIntBits (toStaticIndex x)
else
if (x >= 0) then toDynamicIndex x
{-
(00:49:23) Ktakusa3: So we discussed on Wed, that we are not
completely doing "The Bluespec Way" of strong types for this negative
shift thing (prohibiting signed types from being on the RHS of a shift
operator) because our customers would kill us if we did. Fair
enough... So we are doing the compromise that there is a bounds check.
(00:50:30) Ktakusa3: However, if I understand correctly, because of
the "optimzed away" behavior of the bounds check, we are only doing
the bounds check if it can be detected by the evaluator, and not by
Bluesim or a verilog simulator.
(00:50:51) nanavatiravi: for the moment
(00:51:03) nanavatiravi: I have designs on adding runtime error
infrastructure to bsc
(00:51:18) nanavatiravi: which will detect the problem in simulation,
without compromising the generated hardware
-}
else _ -- This undefined will get optimized away at runtime.
-- For testing, substitute 0 for _
instance PrimIndex (Bit n) n where
isStaticIndex = areStaticBits
toStaticIndex = primUIntBitsToInteger
toDynamicIndex = id
instance PrimShiftIndex (Bit n) n where {}
instance PrimIndex Integer 32 where
isStaticIndex = isStaticInteger
-- if you need to check for negativeness for the following two functions
-- you may wish to use indexableToBits
toStaticIndex = id
toDynamicIndex = fromInteger
instance PrimShiftIndex Integer 32 where {}
--@ The class of types on which selection of elements may be done
--@ using square-bracket notation (in BSV).
--@ \begin{libverbatim}
--@ typeclass PrimSelectable #(type vector_t, type element_t);
--@ \end{libverbatim}
--
-- The typeclass parameters are as follows:
-- vector_t is the type of vector being selected from
-- element_t is the type of the value extracted from the vector_t (vec[idx])
class PrimSelectable vector_t element_t |
vector_t -> element_t where
primSelectFn :: (PrimIndex index_t dynamic_t) =>
Position__ -> vector_t -> index_t -> element_t
instance (PrimSelectable a b) => PrimSelectable (Reg a) b
where
primSelectFn pos r i = primSelectFn pos r._read i
--@ The class of types on which compile-time update of elements may be done
--@ using square-bracket notation with an = assignment (in BSV)
class (PrimSelectable vector_t element_t) => PrimUpdateable vector_t element_t |
vector_t -> element_t where
primUpdateFn :: (PrimIndex index_t dynamic_t) =>
Position__ -> vector_t -> index_t -> element_t -> vector_t
--@ The class of types on which indexed run-time writes of elements may be done
--@ using square-bracket notation with an <= assignment (in BSV)
--@ Note that the [] syntax requires that the PrimWriteable type be an interface
class (PrimSelectable ifc_t value_t) => PrimWriteable ifc_t value_t |
ifc_t -> value_t where
primWriteFn :: (PrimIndex index_t dynamic_t) =>
Position__ -> ifc_t -> index_t -> value_t -> Action
instance (PrimUpdateable a b) => PrimWriteable (Reg a) b
where
primWriteFn pos r i n =
action
r := primUpdateFn pos (r._read) i n
-- XXX only works with static indices
-- primUpdateRangeFn: original_bits[high:low] = spliced_bits[high-low:0]
-- this isn't the most efficient implementation, but it's simple,
-- and has the benefit of splice_size_t being unconstrained
primUpdateRangeFn :: (BitExtend splice_size_t vec_size_t Bit,
PrimIndex ix dx) =>
Position__ ->
Bit vec_size_t -> ix -> ix -> Bit splice_size_t
-> Bit vec_size_t
primUpdateRangeFn pos original_bits high low spliced_bits =
let high' = toStaticIndex high
low' = toStaticIndex low
max_index = valueOf vec_size_t
mask_base :: Bit splice_size_t
mask_base = constantWithAllBitsSet
mask :: Bit vec_size_t
mask = invert (zeroExtend mask_base << low')
new_bits = (zeroExtend spliced_bits) << low'
result = (original_bits & mask) | new_bits
zero_msg = "Assignment has no effect because bit range [" +++
integerToString high' +++ ":" +++
integerToString low' +++ "] selects " +++
"no bits"
negative_msg = "Bit range [" +++
integerToString high' +++ ":" +++
integerToString low' +++ "] selects " +++
"a negative number of bits at"
static_msg str = "The indexes of a range update must be compile-time values.\n" +++
"The " +++ str +++ " index of this range update is not."
size_msg = "Bit range [" +++
integerToString high' +++ ":" +++
integerToString low' +++ "]" +++
" is not " +++ integerToString (valueOf splice_size_t) +++
" bits, the size of the range-update argument."
in -- guard the failed-to-evaluate error on the indices
if (not (isStaticIndex high)) then
primError pos (static_msg "high")
else if (not (isStaticIndex low)) then
primError pos (static_msg "low")
else if (high' >= max_index ||
high' < 0) then
primError pos (listMessage high' "bit range update - high index")
else if (low' >= max_index ||
low' < 0) then
primError pos (listMessage low' "bit range update - low index")
else if (high' >= low') then
if (high' - low' + 1 == valueOf splice_size_t) then result
else primError pos size_msg
else if (high' == low' - 1) then primError pos zero_msg
else primError pos negative_msg
class (MonadFix m) => IsModule m c | m -> c where
liftModule :: Module a -> m a
liftModuleOp :: (Module (c a) -> Module (c b)) -> m a -> m b
primitive type Id__ :: * -> *
instance IsModule Module Id__ where
liftModule _m = _m
liftModuleOp _f = _f
addModuleRules :: (IsModule m c) => Rules -> a -> m a
addModuleRules rs f = liftModule $ do primAddRules rs
return f
addRules :: (IsModule m c) => Rules -> m Empty
addRules rs = liftModule $ do primAddRules rs
return (interface Empty { })
primitive primAddRules :: Rules -> Module ()
primitive type SchedPragma :: *
-- ================================================================
--@ \subsection{Data Types}
-- ----------------------------------------------------------------
--@ \subsubsection{Action}
--@ The type for actions on the lowest level.
--@ \index{PrimAction@\te{PrimAction} (type)}
--@ # 1
primitive type PrimAction :: *
data ActionWorld = ActionWorld
--@ \begin{libverbatim}
--@ struct ActionValue #(type a);
--@ \end{libverbatim}
struct AVStruct a
=
avValue :: a
avAction :: PrimAction
avWorld :: ActionWorld
data ActionValue a = ActionValue (ActionWorld -> AVStruct a)
instance (PrimDeepSeqCond a) => PrimDeepSeqCond (ActionValue a) where
primDeepSeqCond (ActionValue av) b =
let f = av ActionWorld
in primDeepSeqCond f b
__avFunc :: ActionValue a -> ActionWorld -> AVStruct a
__avFunc (ActionValue f) = f
__value :: ActionValue a -> a
__value (ActionValue av) = (av ActionWorld).avValue
primitive primNoActions :: PrimAction
primitive primJoinActions :: PrimAction -> PrimAction -> PrimAction
primitive primSeq :: a -> b -> b
-- implicit-condition strictness
primitive primSeqCond :: a -> b -> b
class coherent PrimDeepSeqCond a where
primDeepSeqCond :: a -> b -> b
instance PrimDeepSeqCond (a -> b) where
primDeepSeqCond f b = primSeqCond f b
-- Generic implementation of the PrimDeepSeqCond typeclass.
-- For each constructor, fully evaluate the data structure. Do this by,
-- for each constructor arg, calling primDeepSeqCond (if the type arguments
-- are known), or primSeqCond (if they are not known) in which case the
-- correct function is called at elaboation time.
instance (Generic a r, PrimDeepSeqCond' r) => PrimDeepSeqCond a where
primDeepSeqCond x = primDeepSeqCond' (from x)
class PrimDeepSeqCond' r where
primDeepSeqCond' :: r -> b -> b
instance (PrimDeepSeqCond' r) => PrimDeepSeqCond' (Meta m r) where
primDeepSeqCond' (Meta x) = primDeepSeqCond' x
instance (PrimDeepSeqCond' r1, PrimDeepSeqCond' r2) => PrimDeepSeqCond' (Either r1 r2) where
primDeepSeqCond' (Left x) = primDeepSeqCond' x
primDeepSeqCond' (Right x) = primDeepSeqCond' x
instance (PrimDeepSeqCond' r1, PrimDeepSeqCond' r2) => PrimDeepSeqCond' (r1, r2) where
primDeepSeqCond' (x, y) z = primDeepSeqCond' x $ primDeepSeqCond' y z
instance PrimDeepSeqCond' () where
primDeepSeqCond' () = id
instance (PrimDeepSeqCond a) => PrimDeepSeqCond' (Conc a) where
primDeepSeqCond' (Conc x) = primDeepSeqCond x
instance PrimDeepSeqCond' (ConcPrim a) where
primDeepSeqCond' (ConcPrim x) = primSeqCond x
-- We have choosen (for now) to not lift any conditions from higher-rank fields.
-- Note that some further lifting may be possible by calling primSeqCond
-- (instead of id) and adjusting the primitive's implementation in IExpand
-- to recognize when called on a SPolyWrap type and to recurse into the field's
-- value in that case; but that this doesn't seem useful -- the expression will
-- contain a lambda, and whether some conditions can be lifted depends on whether
-- some parts of the expression occur outside of the lambda (which is up to the
-- vagaries of the compiler) and on whether some type lambdas can be discharged
-- by defaulting (to Integer or PrimUnit, for example).
instance PrimDeepSeqCond' (ConcPoly a) where
primDeepSeqCond' _ = id
--@ \begin{libverbatim}
--@ instance Monad #(ActionValue);
--@ \end{libverbatim}
-- Sequencing and forcing re-evaluation with ActionWorld works because
-- we don't float expressions past lambda-bindings they don't depend on
-- if that changes, this would have to be revisited
-- (possibly making ActionWorld an argument of foreign-function calls)
instance Monad ActionValue
where
return x = ActionValue
(\aw -> AVStruct { avValue = x;
avAction = primNoActions;
avWorld = aw })
bind (ActionValue x) f = ActionValue (\aw ->
letseq x1 = x aw
a = x1.avAction
v = x1.avValue
aw1 = x1.avWorld
y = __avFunc (f v) $ aw1
in primSeq v $ primSeq a $ primSeq aw1 $
AVStruct {
avValue = y.avValue;
avAction = primJoinActions a y.avAction;
avWorld = y.avWorld
})
--@ \begin{libverbatim}
--@ instance MonadFix #(ActionValue);
--@ \end{libverbatim}
instance MonadFix ActionValue
where
mfix m = primFix (\ av -> m (__value av))
-- mfix :: (a -> ActionValue a) -> ActionValue a
-- mfix m =
-- let av :: ActionValue a
-- av = m av.avValue
-- in av
--@ Extract the \te{PrimAction} part of an \te{ActionValue}.
--@ \begin{libverbatim}
--@ function PrimAction toPrimAction(ActionValue#(a) a);
--@ \end{libverbatim}
toPrimAction :: ActionValue a -> PrimAction
toPrimAction (ActionValue a) = (a ActionWorld).avAction
--@ Construct an \te{ActionValue} (with a ``don't care'' value)
--@ from a \te{PrimAction}.
--@ \begin{libverbatim}
--@ function ActionValue#(a) fromPrimAction(PrimAction a);
--@ \end{libverbatim}
fromPrimAction :: PrimAction -> ActionValue a
fromPrimAction a = ActionValue (\aw -> AVStruct { avValue = _; avAction = a; avWorld = aw })
--@ \begin{libverbatim}
--@ typedef ActionValue#(void) Action;
--@ \end{libverbatim}
type Action = ActionValue ()
--X@ \begin{verbatim}
--X@ typedef ActionValue_#(0) Action_;
--X@ \end{verbatim}
type Action_ = ActionValue_ 0
--@ An empty \te{Action}.
--@ \index{noAction@\te{noAction} (empty action)}
--@ \begin{libverbatim}
--@ Action noAction;
--@ \end{libverbatim}
noAction :: Action
noAction = fromPrimAction primNoActions
--X@ Assign an \te{ActionValue} to a register.
--X@ \begin{libverbatim}
--X@ function Action (:<-)(Reg#(a) r, ActionValue#(a) av);
--X@ \end{libverbatim}
(:<-) :: Reg a -> ActionValue a -> Action
(:<-) r av = av `bind` r._write
--X@ A primitive \te{ActionValue} of bits
--X@ \begin{verbatim}
--X@ struct ActionValue_ #(type n);
--X@ \end{verbatim}
struct ActionValue_ n
=
avValue_ :: Bit n
avAction_ :: PrimAction
toActionValue_ :: (Bits a n) => ActionValue a -> ActionValue_ n
toActionValue_ (ActionValue av) =
letseq av' = av ActionWorld
in ActionValue_ { avValue_ = pack av'.avValue; avAction_ = av'.avAction}
fromActionValue_ :: (Bits a n) => ActionValue_ n -> ActionValue a
fromActionValue_ av_ = ActionValue (\aw ->
AVStruct { avValue = unpack av_.avValue_; avAction = av_.avAction_; avWorld = aw})
-- ----------------------------------------------------------------
--@ \subsubsection{Bit}
--@ \index{Bit@\te{Bit} (type)}
--@ # 1
primitive type Bit :: # -> *
primitive primUninitBitArray :: Position__ -> String -> Bit n
-- This is actually the primMarkArrayInitialized primitive, but with diff type
primitive primMarkBitArrayInitialized :: Bit n -> Bit n
primitive primIsBitArray :: Bit n -> Bit 1
isBitArray :: Bit n -> Bool
isBitArray = compose primChr primIsBitArray
primitive primUpdateBitArray :: Bit n -> Integer -> Bit 1 -> Bit n
instance PrimMakeUninitialized (Bit n) where
primMakeUninitialized pos name =
let n = valueOf n
in if (n == 0) then 0
else if (n == 1) then primMakeRawUninitialized pos name
else primUninitBitArray pos name
--@ \begin{libverbatim}
--@ instance Bits #(Bit#(k), k);
--@ \end{libverbatim}
instance Bits (Bit k) k
where
pack x = x
unpack x = x
--@ \begin{libverbatim}
--@ instance Eq #(Bit#(n));
--@ \end{libverbatim}
instance Eq (Bit n)
where
(==) x y = primChr (primEQ x y)
(/=) x y = primChr (primBNot (primEQ x y))
--@ Bit-level Verilog case equality.
--@ Undefined bits are strictly not equal to defined ones.
--@ \index{===@\te{===} (case equality operator)}
--@ \begin{libverbatim}
--@ function Bool (==)(a x, a y)
--@ provisos (Bits#(a, sa));
--@ \end{libverbatim}
(===) :: Bit n -> Bit n -> Bool
(===) x y = primChr $ primEQ3 x y
--@ Bit-level Verilog case inequality.
--@ Undefined bits are strictly not equal to defined ones.
--@ \index{!==@\te{!==} (case inequality operator)}