forked from B-Lang-org/bsc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBH_lang.tex
4091 lines (3329 loc) · 141 KB
/
BH_lang.tex
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
% $Id$
%
% This document was forked from the internal Bluespec repository
% bsc-doc.git/doc/language-manual_old/lang.tex
% at commit 5a70486924b35cbd3344750debd4f4828e8e8e54.
\documentclass[twoside,letterpaper]{article}
% \usepackage{a4}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{latexsym}
\usepackage{makeidx}
\usepackage{verbatim}
\usepackage{moreverb}
\usepackage{index}
\usepackage{dingbat}
\usepackage{fancyhdr}
\usepackage{ifpdf}
% \newif\ifpdf
% \ifx\pdfoutput\undefined
% \else
% \ifx\pdfoutput\relax
% \else
% \ifcase\pdfoutput
% \else
% \pdftrue
% \fi
% \fi
% \fi
\ifpdf
\usepackage[pdftex,colorlinks=true,bookmarksopen, pdfstartview=FitH,
linkcolor=blue, citecolor=blue, urlcolor=blue]{hyperref}
\pdfcompresslevel=9
\usepackage[pdftex]{graphicx}
\else
\usepackage[dvips]{graphicx}
\fi
\usepackage{ae}
\usepackage{aecompl}
\usepackage{hyperref}
% HORIZONTAL MARGINS
% Left margin, odd pages: 1.25 inch (0.25 + 1)
\setlength{\oddsidemargin}{0.25in}
% Left margin, even pages: 1.25 inch (0 + 1)
\setlength{\evensidemargin}{0.25in}
% Text width 6 inch (so other margin is 1.25 inch).
\setlength{\textwidth}{6in}
% ----------------
% VERTICAL MARGINS
% Top margin 0.5 inch (-0.5 + 1)
\setlength{\topmargin}{-0.5in}
% Head height 0.25 inch (where page headers go)
\setlength{\headheight}{0.25in}
% Head separation 0.25 inch (between header and top line of text)
\setlength{\headsep}{0.25in}
% Text height 9 inch (so bottom margin 1 in)
\setlength{\textheight}{9in}
% ----------------
% PARAGRAPH INDENTATION
\setlength{\parindent}{0in}
% SPACE BETWEEN PARAGRAPHS
\setlength{\parskip}{\medskipamount}
% ----------------
% STRUTS
% HORIZONTAL STRUT. One argument (width).
\newcommand{\hstrut}[1]{\hspace*{#1}}
% VERTICAL STRUT. Two arguments (offset from baseline, height).
\newcommand{\vstrut}[2]{\rule[#1]{0in}{#2}}
% ----------------
% HORIZONTAL LINE ACROSS PAGE:
\newcommand{\hdivider}{\noindent\mbox{}\hrulefill\mbox{}}
% ----------------
% EMPTY BOXES OF VARIOUS WIDTHS, FOR INDENTATION
\newcommand{\hm}{\hspace*{1em}}
\newcommand{\hmm}{\hspace*{2em}}
\newcommand{\hmmm}{\hspace*{3em}}
\newcommand{\hmmmm}{\hspace*{4em}}
% ----------------
% ``TIGHTLIST'' ENVIRONMENT (no para space betwee items, small indent)
\newenvironment{tightlist}%
{\begin{list}{$\bullet$}{%
\setlength{\topsep}{0in}
\setlength{\partopsep}{0in}
\setlength{\itemsep}{0in}
\setlength{\parsep}{0in}
\setlength{\leftmargin}{1.5em}
\setlength{\rightmargin}{0in}
\setlength{\itemindent}{0in}
}
}%
{\end{list}
}
% ----------------
\newcommand{\ie}{\emph{i.e.,}}
%----------------
% Added to get special characters in index
\newcommand{\Caret}{\char94}
\newcommand{\Tilde}{\char126}
% ----------------
% BSV names
\newcommand{\LibRefGuide}{\emph{Libraries Reference Guide}}
\newcommand{\LibRefGuideFullName}{\emph{Bluespec Compiler (BSC) Libraries Reference Guide}}
\newcommand{\BS}{Bluespec}
\newcommand{\BSInc}{Bluespec, Inc.}
\newcommand{\BH}{BH}
\newcommand{\BHFull}{Bluespec Haskell/Classic}
\newcommand{\BSVFull}{Bluespec SystemVerilog}
\newcommand{\BSV}{BSV}
\newcommand{\bsc}{\emph{bsc}}
\newcommand{\SV}{SystemVerilog}
\newcommand{\SVThreeOneA}{SystemVerilog 3.1a}
\newcommand{\SC}{SystemC}
\newcommand{\V}{Verilog}
\newcommand{\veri}{Verilog}
\newcommand{\VOrig}{Verilog 1995}
\newcommand{\VTwoK}{Verilog 2001}
% ----------------------------------------------------------------
% CODE DISPLAYS.
% Bluespec code displays are enclosed between \BBS and \EBS
% Most characters are taken verbatim, in typewriter font,
% Except:
% Commands are still available (beginning with \)
% but use ` and ' instead of { and }
% Math mode is still available (beginning with $)
% but use ~ and ! for ^ and _
\outer\def\BBS{%
\begin{list}{$\bullet$}{%
\setlength{\topsep}{0in}
\setlength{\partopsep}{0in}
\setlength{\itemsep}{0in}
\setlength{\parsep}{0in}
\setlength{\leftmargin}{1em}
\setlength{\rightmargin}{0in}
\setlength{\itemindent}{0in}
}\item[]
% \catcode`\{=12
% \catcode`\}=12
\catcode`\&=12
\catcode`\#=12
\catcode`\%=12
\catcode`\~=12
% \catcode`\_=12
\catcode`\^=12
% \catcode`\~=7
% \catcode`\!=7 % superscript
% \catcode`\'=2
% \catcode`\`=1
\obeyspaces
\obeylines \tt}
\outer\def\EBS{%
\end{list}
}
{\obeyspaces\gdef {\ }}
% ----------------------------------------------------------------
% Editorial notes are enclosed between \begin{NOTE} and \end{NOTE}
\newenvironment{NOTE}{%
\hm{\bf{Note}}
\begin{list}{$\bullet$}{%
\setlength{\topsep}{0in}
\setlength{\partopsep}{0in}
\setlength{\itemsep}{0in}
\setlength{\parsep}{0in}
\setlength{\leftmargin}{2em}
\setlength{\rightmargin}{0in}
\setlength{\itemindent}{0in}
}\item[]
\sf
}
{\end{list}\hm{\bf{End of Note}}}
% ----------------------------------------------------------------
% The following hack is from Mark Tuttle
\newcommand{\ttsymbol}[1]{%
% print character at position #1 in the tt font family in current font size
\begingroup\fontfamily{cmtt}\selectfont\symbol{#1}\endgroup
}
% ----------------
% BANG (tt font exclamation mark), can be used inside \fbox environment
\newcommand{\BANG}{\ttsymbol{33}}
% ----------------
% HASH (tt font hash), can be used inside \fbox environment
\newcommand{\HASH}{\ttsymbol{35}}
% ----------------
% BSL (tt font backslash), can be used inside \fbox environment
\newcommand{\BSL}{\ttsymbol{92}}
% ----------------
% HAT (tt font hat), can be used inside \fbox environment
\newcommand{\HAT}{\ttsymbol{94}}
% ----------------
% UNDERSCORE of standard char width (normal tt font \_ is narrower)
\newcommand{\US}{\ttsymbol{95}}
% ----------------
% TILDE (tt font tilde), can be used inside \fbox environment
\newcommand{\TILDE}{\ttsymbol{126}}
% ----------------
% LBRACE (tt font left brace), can be used inside \fbox environment
\newcommand{\LBRACE}{\ttsymbol{123}}
% ----------------
% BAR (tt font vertical bar), can be used inside \fbox environment
\newcommand{\BAR}{\ttsymbol{124}}
% ----------------
% RBRACE (tt font right brace), can be used inside \fbox environment
\newcommand{\RBRACE}{\ttsymbol{125}}
% ----------------------------------------------------------------
% Library environment. Used by generated code.
\newenvironment{libverbatim}
{\vspace*{-1.0em}
\verbatim}
{\endverbatim
}
\newenvironment{smcenterboxverbatim}
{\center
\small
\boxedverbatim}
{\endboxedverbatim
{\endcenter} }
\newenvironment{centerboxverbatim}
{\center
\boxedverbatim}
{\endboxedverbatim
{\endcenter }}
% ----------------------------------------------------------------
\newcommand\lineup{\vspace*{-0.6em}}
\newcommand\com[1]{}
\newcommand{\te}[1]{\texttt{#1}}
\newcommand{\nterm}[1]{\emph{#1}}
\newcommand{\term}[1]{{\tt{#1}}}
\newcommand{\many}[1]{\{ #1 \}}
\newcommand{\opt}[1]{[ #1 ]}
\newcommand{\alt}{{$\mid$}}
\newcommand{\gram}[2]{ \hm\makebox[10em][l]{\it #1}\makebox[1.5em][l]{::=} #2}
\newcommand{\grammore}[1]{\hm\makebox[10em][l]{ }\makebox[1.5em][l]{} #1}
\newcommand{\gramalt}[1]{ \hm\makebox[10em][l]{ }\makebox[1.5em][l]{\alt} #1}
\newcommand{\tbd}[1]{{\sf TBD: #1}}
\newcommand{\note}[1]{\vspace*{2mm}{\sf {\large \bf Note\\} #1}\vspace{2mm}}
\newcommand{\begindescrlist}[1]{
\begin{list}{\arabic{enumi}}{
\settowidth{\labelwidth}{#1}
\setlength{\leftmargin}{\labelwidth} % {#1}
\addtolength{\leftmargin}{\labelsep}
\setlength{\parsep}{0ex}
\setlength{\itemsep}{0ex}
\usecounter{enumi}
}
}
\newcommand{\litem}[1]{\item[#1\hfill]}
% ``Quoted'' inline bluespec
\newcommand{\qbs}[1]{``\mbox{\te{#1}}''}
\newcommand{\obsolete}[1]{}
\makeindex
\title{
\resizebox{2in}{!}{\includegraphics[width=\textwidth]{../common/B-Lang}} \\
\vspace{0.3in}
{\BH}$^{\rm{TM}}$ ({\BS} Haskell/Classic) \\
\mbox{} \\
Language Reference Guide \\
\vspace*{2in}
\mbox{}
}
% Revision id, major copyrights
\input{version}
\ifpdf
\hypersetup{
pdfauthor = {Bluespec, Inc.},
pdftitle = {Bluespec Haskell (BH) (TM) Reference Guide},
pdfsubject = {Bluespec},
pdfkeywords = {Bluespec},
pdfcreator = {Bluespec}}
\else
\fi
\begin{document}
% ----------------
\maketitle
% ================================================================
\pagestyle{fancy}
\lhead[Reference Guide]{BH}
\rhead[BH]{Reference Guide}
%\lfoot[\thepage]{}
\cfoot{\thepage}
%\rfoot[]{\thepage}
% ----------------
\newpage
{\large\bf Trademarks and copyrights}
Verilog is a trademark of IEEE (the Institute of Electrical and
Electronics Engineers). The Verilog standard is copyrighted, owned
and maintained by IEEE.
VHDL is a trademark of IEEE (the Institute of Electrical and
Electronics Engineers). The VHDL standard is copyrighted, owned and
maintained by IEEE.
SystemVerilog is a trademark of IEEE. The SystemVerilog standard is
owned and maintained by IEEE.
SystemC is a trademark of IEEE. The SystemC standard is owned and
maintained by IEEE.
Bluespec is a trademark of Bluespec, Inc.
% ================================================================
\newpage
\clearpage
\phantomsection
\addcontentsline{toc}{section}{Table of Contents}
\tableofcontents
% The following two commands are a work-around for some bug
% seemingly introduced by the fancyhdr package. Without this,
% the entries on the last page of the table of are spread
% vertically across the page, i.e., the linespacing is
% screwed up. This work-around seems to fix it.
\vfill
\hm
\newpage
% ================================================================
\section{Introduction}
{\BH} ({\BHFull}) is a language for hardware design. The language borrows its
notation, type and package system from an existing general-purpose
functional programming language called Haskell
{\cite{haskell12}}{\index{Haskell}} where those constructs have been
well tested for over a decade. Unlike Haskell, {\BH} is meant
solely for hardware design--- a {\BH} program represents a circuit.
The abstract model for these circuits is a Term Rewriting System
(TRS); details about using TRSs for describing circuits, and compiling
these descriptions to real hardware, may be found in James Hoe's
thesis {\cite{jhoe}}. {\BH} has several restrictions and extensions
relative to Haskell, arising out of this hardware focus.
This document is not meant as a tutorial on {\BH} (separate
documents exist for that purpose). Nevertheless, this document has
numerous small examples to explicate {\BH} notation.
% ----------------------------------------------------------------
\subsection*{Meta notation}
The grammar
\index{grammar}
\index{meta notation|see{grammar}}
rules in the
presentation below mostly follow the usual EBNF (Extended BNF)
structure. Grammar alternatives are separated by ``{\alt}''. Items
enclosed in \opt{} are optional. Items enclosed in {\many{}} can be
repeated zero or more times. The last piece of notation is used
sloppily; sometimes there must be at least one item, and also, the
last terminal inside the {\many{}} is sometimes a separator rather
than terminator.
% ----------------------------------------------------------------
\subsection*{Identifiers and the r\^ole of upper and lower case}
An identifier {\index{identifiers|textbf}}in {\BH} consists of a letter
followed by zero or more letters, digits, underscores
\index{underscore|see{\qbs{\US}}}\index{_@\te{\US}!in identifiers}and single quotes.
\index{=squote@\te{'} (character, in identifiers)}
Identifiers are case sensitive: {\tt{glurph}},
{\tt{gluRph}} and {\tt{Glurph}} are three distinct identifiers.
The case of the first letter in an identifier
\index{identifiers!case of first letter}
is very important. If the first letter is lower
case, the identifier is a ``variable identifier'', referred to in the
grammar rules as a {\nterm{varId}}.
\index{varId@\te{varId} (grammar terminal)|textbf}
If the first letter is upper case,
the identifier is a ``constructor
identifier'',
\index{identifiers!constructor}
referred to in the
grammar rules as a
{\nterm{conId}}.
\index{conId@\nterm{conId} (grammar non-terminal)|textbf}
In {\BH}, package names (\nterm{packageId}),
\index{packageId@{\nterm{packageId}} (grammar non-terminal)}
type names (\nterm{tycon})
\index{tycon@\nterm{tycon} (grammar non-terminal)}
and value constructor names
\index{value constructor names}
are all constructor identifiers. (Ordinary)
variables,
\index{variables}
field names
\index{field names}
and type variables
\index{type variables}
are all variable identifiers.
\index{identifiers!variable}
A lone underscore, {\qbs{\US}},
\index{=underscore@\te{\US}!``don't care'' pattern}
\index{=underscore@\te{\US}!``don't care'' expression}
is treated as a
special identifier--- it is used as a ``don't care''
pattern
\index{don't care (patterns and expressions)|see{\qbs{\US}}}
or expression (more details in Sections \ref{sec-exprs-wildcard} and
\ref{sec-patterns-var}).
% ----------------------------------------------------------------
\subsection*{The Standard Prelude}
{\index{Prelude@{\te{Prelude}}}}
The Standard Prelude is a predefined package that is imported
implicitly into every {\BH} package. It contains a number of useful
predefined entities (types, values/functions, classes, instances,
etc.). It is somewhat analogous to the combination of various ``.h''
files and standard libraries in C, except that in {\BH} no special
action is needed to import the prelude or to link it in. We will
refer to the prelude periodically in the following sections, and there
are more details in appendix {\ref{sec-prelude}}.
% ----------------------------------------------------------------
\subsection*{Lexical syntax/layout}
\index{layout}
\index{indentation|see{layout}}
In {\BH}, there are various syntactic constructs that involve zero
or more items enclosed in braces and separated by semicolons:
\BBS
\{ {\rm\emph{item}} ; {\rm\emph{item}} ; $\cdots$ ; {\rm\emph{item}} \}
\EBS
These braces and semicolons
\index{braces and semicolons|see{layout}}
can be omitted entirely if the components are laid out with proper
indentation.
Suppose the parser discovers a missing open brace (e.g., after the
keywords {\te{where}}, {\te{let}}, {\te{do}} and {\te{of}}). Then,
the indentation of the next lexical element is remembered (and the
missing open brace is implicitly inserted before it). For each
subsequent line, if it contains only whitespace or is indented more,
then it is treated as a continuation of the current item. If it is
indented the same amount, it is treated as the beginning of the next
item ({\ie} a semicolon is inserted implicitly before the item). If
it is indented less, then the list of items is considered to be
complete ({\ie} a closing brace is implicitly inserted). An explicit
brace is never matched against an implicit one. Thus, while using the
layout rule, if the parser encounters an explicit open brace, then it
does not resume using the layout rule for this list of items until it
has ``emerged'' past the explicit corresponding closing brace (a
construct nested inside this list of items may still use the layout
rule).
% ----------------------------------------------------------------
\subsection*{Comments in {\BH} programs}
In a {\BH} program, a {\emph{comment}} is legal as whitespace, and
may be introduced in two ways. An {\emph{ordinary
comment}}{\index{comment!ordinary}}{\index{=minusminus@{\te{{-}{-}}} (ordinary
comment)}} is introduced by a lexical token consisting of two or more
consecutive dashes followed by a non-symbol, and extends up to and
including the end of the line. (See Section
{\ref{sec-infix-applications}} for the list of symbols.) Note: the
lexical token {\te{--->}} is a legal token in {\BH}, and since it
contains three consecutive dashes followed by a symbol, it does not
begin a comment.
A {\emph{nested comment}}{\index{comment!nested}} is introduced by the
lexeme {\qbs{\{-}}
{\index{=lbraceminus@\texttt{\LBRACE{}-} (open nested comment)}}
and extends until the next matching
{\qbs{-\}}},
{\index{=minusrbrace@\texttt{-\RBRACE{}} (close nested comment)}}
possibly spanning multiple lines. A nested comment can itself contain
another nested comment; this nesting can be repeated to any depth.
In an ordinary comment, the character sequences {\qbs{\{-}} and
{\qbs{-\}}} have no special significance, and, in a nested comment, a
sequence of dashes has no special significance.
% ----------------------------------------------------------------
\subsection*{General organization of this document}
A concept that is pervasive in {\BH} is the notion of a
{\emph{type}}. Every value expression in {\BH}, even a basic value
identifier, has a type, and the compiler does extensive static type
checking to rule out absurd use of values (such as taking the square
root of an IP address). Types are discussed in section
{\ref{sec-type}}.
A {\BH} program consists of one or more packages. These outermost
constructs are described in section {\ref{sec-packages}}. As
explained later, a {\BH} package is a linguistic
namespace-management mechanism and does not have any direct
correlation with any hardware module being described by the program.
Hardware modules correspond to {\emph{modules}}, a particular type of
value in {\BH}.
Within each package is a collection of top-level definitions. These
are described in section {\ref{sec-top-level-defs}}.
Amongst the top-level definitions are {\emph{value definitions}}
(section {\ref{sec-val-defs}}), which constitute the actual meat of
the code. Value definitions are built around {\emph{expressions}},
which are described in section {\ref{sec-exprs}}.
% ================================================================
\section{Types}
\label{sec-type}
\index{types|textbf}
Every value expression and, in particular, every value identifier in
{\BH} has a {\emph{type}}. In some cases the programmer must supply
a {\emph{type signature}}{\index{type signature}} specifying this and in many cases the
compiler infers it automatically. The {\BH} programmer should be
aware of types at all times.
\gram{type}{\nterm{btype} \opt{ \term{->} \nterm{type} } } \\
\gram{btype}{\opt{\nterm{btype}} \nterm{atype}} \\
\gram{atype}{\nterm{tycon} {\alt} \nterm{tyvar} {\alt} \term{(} \many{\nterm{type} \term{,}} \term{)}} \\
\gram{tycon}{\nterm{conId}}
\index{tycon@\nterm{tycon} (grammar non-terminal)|textbf}
Most type expressions have the form:
\index{type constructor}
\BBS
{\rm\emph{TypeConstructor}} $t_1$ $\cdots$ $t_n$
\EBS
where $t_1$ $\cdots$ $t_n$ are themselves type expressions, and $n
{\geq} 0$. The $t_1$ $\cdots$ $t_n$ are referred to as the
{\emph{type arguments}} to the type constructor. $n$ is also called
the {\emph{arity}}
\index{arity, of type constructor}
of the type constructor.
Familiar basic types have zero-arity type constructors (no type
arguments, $n = 0$). Examples:
\begin{verbatim}
Integer
Bool
String
Action
\end{verbatim}
Other type constructors have arity $n > 0$; these are also known as
{\emph{parameterized types}}.
\index{types!parameterized}
Examples:
\BBS
List Bool
List (List Bool)
Array Integer String
Maybe Integer
\EBS
These represent the types of lists of Booleans, lists of lists of
Booleans, arrays indexed by integers and containing strings, and
an optional result possibly containing an integer.
A type can be {\emph{polymorphic}},
\index{types!polymorphic}
indicated using type variables.
\index{type variables}
Examples:
\begin{verbatim}
List a
List (List b)
Array i (List String)
\end{verbatim}
These represent lists of things of some unknown type {\qbs{a}}, lists
of lists of things of some unknown type {\qbs{b}}, and arrays indexed
by some unknown type {\qbs{i}} and containing lists of strings.
One type constructor is given special status in the syntax. The type
of functions from arguments of type $t_1$ to results of type $t_2$
could have been written as:
\BBS
Function $t_1$ $t_2$
\EBS
but in {\BH} we write the constructor as an infix arrow:
\index{function types|textbf}
\index{arrow types|see{function types}}
\index{=minusgt@{\te{->}} (infix function type constructor)|textbf}
\BBS
$t_1$ -> $t_2$
\EBS
These associate to the right, {\ie}
\BBS
$t_1$ -> $\cdots$ -> $t_{n-1}$ -> $t_n$ \hmm $\equiv$ \hmm $t_1$ -> ($\cdots$ -> ($t_{n-1}$ -> $t_n$))
\EBS
There is one particular set of niladic type constructors that look
like numbers.
\index{size types}
These are used to represent certain ``sizes''. For
example, the type:
\begin{verbatim}
Bit 16
\end{verbatim}
consists of the unary type constructor {\te{Bit}} applied to type
represented by the niladic type constructor {\qbs{16}}. The type as a
whole represents bit vectors of length 16 bits. Similarly the type
\begin{verbatim}
UInt 32
\end{verbatim}
represents the type of unsigned integers that can be represented in 32
bits.
These numeric types are said to have kind \texttt{\#},
rather than kind \texttt{*} for value types.
\index{string types}
Strings can also be used as type, having kind \texttt{\$}.
This is less common, but string types are quite useful in the generics library,
described in the \LibRefGuide.
Examples:
\begin{verbatim}
MetaData#("Prelude","Maybe",PrimUnit,2)
MetaConsNamed#("Valid",1,1)
\end{verbatim}
% ----------------------------------------------------------------
\subsection{Type classes and overloading}
\label{sec-overloading}
\index{overloading, of type}
{\BH}'s {\te{class}} and {\te{instance}} mechanisms form a
systematic way to do {\emph{overloading}} (the approach has been well
tested in Haskell).
Overloading is a way to use a common name to refer to a set of
operations at different types. For example, we may want to use the
{\qbs{<}} operator name for the integer comparison operation, the
floating-point comparison operation, the vector comparison operation
and the matrix comparison operation. Note that this is not the same
as polymorphism: a polymorphic function is a {\emph{single}} function
that is meaningful at an infinity of types ({\ie} at every possible
instantiation of the type variables in its type). An overloaded
identifier, on the other hand, usually uses a common name to refer to
a (usually) small set of distinct operations.
Further, it may make sense to have {\qbs{<=}}, {\qbs{>}} and
{\qbs{>=}} operations wherever there is a {\qbs{<}} operation, on
integers, floating points numbers, vectors and matrices. Rather than
handle these separately, we say:
\begin{tightlist}
\item
there is class of types which we will call {\te{Ord}} (for ``ordered
types''),
\index{type class|textbf}
\index{class|see{type class}}
\item
that the integer, floating point, vector and matrix types are members
(or ``instances'') of this class, and
\index{instance (of type class)|textbf}
\item
that all types that are members of this class have appropriate
definitions for the {\qbs{<}}, {\qbs{<=}}, {\qbs{>}} and {\qbs{>=}}
operations. We also say that these operations are {\emph{overloaded}}
across these instance types, and we refer to these operations as the
{\emph{methods}} of this class.
\index{methods!of a type class|textbf}
\end{tightlist}
Another example: we could use a class {\te{Hashable}} with an
operation called {\te{hash}} to represent those types $T$ for which we
can and do define a hashing function. Each such type $T$ has to
specify how to compute the {\te{hash}} function at that type.
Classes, and the membership of a type in a class, do not come into
existence by magic. Every class is created explicitly using a class
declaration, described in section {\ref{sec-classes}}. A type must
explicitly be made an instance of a class and the corresponding class
methods have to be provided explicitly; this is described in
{\ref{sec-instances}}.
% ----------------
\subsubsection{Context-qualified types}
\index{context-qualified types|textbf}
\index{types!context-qualified|see{context-qualified types}}
Consider the following type declaration:
\begin{verbatim}
sort :: (Ord a) => List a -> List a
\end{verbatim}
It expresses the idea that a sorting function takes an (unsorted)
input list of items and produces a (sorted) output list of items, but
it is only meaningful for those types of items (\qbs{a}) for which the
ordering functions (such as {\qbs{<}}) are defined. Thus, it is ok to
apply {\te{sort}} to lists of {\te{Integer}}'s or lists of
{\te{Bool}}'s, because those types are instances of {\te{Ord}}, but it
is not ok to apply {\te{sort}} to a list of, say, {\te{Counter}}'s
(assuming {\te{Counter}} is not an instance of the {\te{Ord}} class).
In the type of {\te{sort}} above, the part before {\qbs{=>}} is called
a {\emph{context}}.
\index{contexts|see{context-qualified types}}
A context expresses constraints on one or more
type variables--- in the above example, the constraint is that any
actual type {\qbs{a}} must be an instance of the {\te{Ord}} class.
A context-qualified type has the following grammar:
\gram{ctxType}{\opt{\nterm{context} \term{=>}} \nterm{type}}
\index{=eqgt@\te{=>} (in context-qualified types)|textbf}
\gram{context}{\term{(} \many{\nterm{classId} \many{ \nterm{varId} } \term{,} } \term{)}}
\gram{classId}{\nterm{conId}}
In the above example, the class {\te{Ord}} had only one type parameter
({\ie} it constrains a single type) but, in general, a type class can
have multiple type parameters. For example, in {\BH} we frequently
use the class {\mbox{\qbs{Bits a n}}} which constrains the type
represented by {\te{a}} to be representable in bit strings of length
represented by the type {\te{n}}.
\begin{NOTE}
When using an overloaded identifier {\te{x}} there is always a
question of whether or not there is enough type information available
to the compiler to determine which of the overloaded {\te{x}}'s you
mean. For example, if {\te{read}} is an overloaded function that
takes strings to integers or Booleans, and {\te{show}} is an
overloaded function that takes integers or Booleans to strings, then
the expression {\mbox{\te{show (read s)}}} is ambiguous--- is the
thing to be read an integer or a Boolean?
In such ambiguous situations, the compiler will so notify you, and you
may need to give it a little help by inserting an explicit type
signature, e.g.,
\begin{verbatim}
show ((read s) :: Bool)
\end{verbatim}
\end{NOTE}
% ================================================================
\section{Packages}
\label{sec-packages}
\index{package|textbf}
Packages are the outermost constructs in {\BH}--- all {\BH} code
must be inside packages. There should be one package per file. A
{\BH} package is a linguistic device for namespace control, and is
particularly useful for programming-in-the-large. A package does not
directly correspond to hardware modules. (Hardware modules correspond
to {\BH} modules, described in section {\ref{sec-modules}}.)
A {\BH} package consists of the package header, import declarations,
and top level definitions. The package header indicates which names
defined in this package are exported, {\ie} available for import into
other packages.
\gram{packageDefn}{ \term{package} \nterm{packageId} \term{(} \nterm{exportDecl} \term{)} \term{where} \term{\{} }
\index{package@\te{package} (keyword)}
\index{where@\te{where} (keyword)}
\\
\grammore{\many{ \nterm{importDecl} \term{;} }} \\
\grammore{\many{ \nterm{fixityDecl} \term{;} }} \\
\grammore{\many{ \nterm{topDefn} \term{;} }} \\
\grammore{\term{\}}}
\gram{exportDecl}{ \nterm{varId} {\alt} \nterm{typeId} \opt{\nterm{conList}} }
\gram{conList}{ \term{(..)} }
\gram{importDecl}{ \term{import} \opt{\term{qualified}} \nterm{packageId} }
\index{import@\te{import} (keyword)}
\gram{fixityDecl}{ \nterm{fixity} \nterm{integer} \nterm{varId} }
\gram{fixity} { \term{infix} {\alt} \term{infixl} {\alt} \term{infixr} }
\index{infix@\te{infix} (keyword)}
\index{infixl@\te{infixl} (keyword)}
\index{infixr@\te{infixr} (keyword)}
\gram{packageId}{\nterm{conId}}
Example:
\BBS
package Foo (x, y) where
\null
import Bar
import Glurph
\null
{\rm\emph{... top level definition ...}}
{\rm\emph{... top level definition ...}}
{\rm\emph{... top level definition ...}}
\EBS
Here, {\te{Foo}} is the name of this package, {\te{x}} and {\te{y}} are
names exported from this package (they will be defined amongst the top
level definitions in this package), and {\te{Bar}} and {\te{Glurph}}
are the names of package being imported (for use in this package).
\index{export, identifiers from a package|textbf}
\index{identifiers!export from a package}
\index{=lparendotdotrparen@\te{(..)} (exporting constructors and field names)}
The export list is a list of identifiers, each optionally followed by
\te{(..)}. Each identifier in the list will be visible outside the
package. If the exported identifier is the name of \te{data},
\te{struct}, or \te{interface}, then the constructors or fields of the
type will be visible only if \te{(..)} is used. Otherwise, if you
export only the name of a type without the \te{(..)} suffix, the type
is an abstract (opaque) data type outside the package. The list of
identifiers may include identifiers defined in the package as well as
identifiers imported from other packages.
If the keyword \te{qualified} is present in the import declaration
all the imported entities from that package must be referred to
by a qualified name.
The fixity declaration can be used to give a precedence level to
a user-defined infix operator. The \te{infixl} specifies a left
associative operator, \te{infixr} a right associative operator, and
\te{infix} a non-associative operator.
% ----------------------------------------------------------------
\subsection{Name clashes and qualified names}
\index{identifiers!qualified|textbf}
When used in any scope, a name must have an unambiguous meaning. If
there is name clash for a name $x$ because it is defined in the
current package and/or it is available from one or more imported
packages, then the ambiguity can be resolved by using a qualified name
of the form $M.x$ to refer to the version of $x$ contained in package
$M$.
% ================================================================
\section{Top level definitions}
\label{sec-top-level-defs}
Top level definitions can be used only on the top level within a package.
% ----------------------------------------------------------------
\subsection{\te{data}}
\label{sec-data}
A {\te{data}} definition defines a brand new type, which is different
from every primitive type and every other type defined using a
{\te{data}} definition, even if they look structurally similar. The
new type defined by a {\te{data}} definition is a ``sum of products'',
or a ``union of products''.
\gram{topDefn}{ \term{data} \nterm{typeId} \many{\nterm{tyVarId}} \term{=} \many{\nterm{summand} \term{|}} \opt{\nterm{derive}}}
\gram{summand}{\nterm{conId} \many{\nterm{type}}}
\gram{summand}{\nterm{conId} \term{\{} \many{ \nterm{fieldDef} \term{;} } \term{\}} }
\index{deriving@\te{deriving} (keyword)|textbf}
\gram{derive}{\term{deriving} \term{(} \many{ \nterm{classId} \term{,} } \term{)} }
\gram{fieldDef}{ \nterm{fieldId} \term{::} \nterm{type} }
The {\nterm{typeId}} is the name of this new type. If the
{\nterm{tyVarId}}'s exist, they are type parameters, thereby making
this new type polymorphic. In each {\nterm{summand}}, the
{\nterm{conId}} is called a ``constructor''. You can think of them as
unique {\emph{tag}}'s that identify each summand. Each
{\nterm{conId}} is followed by a specification for the fields involved
in that summand ({\ie} the fields are the ``product'' within the
summand). In the first way of specifying a summand, the fields are
just identified by position, hence we only specify the types of the
fields. In the second way of specifying a summand, the fields are
named, hence we specify the field names ({\nterm{fieldId}}'s) and
their types.
The same constructor name may occur in more than one type. The same
field name can occur in more than one type. The same field name can
occur in more than one summand within the same type, but the type of
the field must be the same in each summand.
The optional {\nterm{derive}} clause is used as a shorthand to make
this new type an instance of the {\nterm{classId}}'s, instead of using
a separate, full-blown {\te{instance}} declaration. This can only be
done for certain predefined {\nterm{classId}}'s: {\te{Bits}},
{\te{Eq}}, and {\te{Bounded}}. The compiler automatically derives the
operations corresponding to those classes (such as {\te{pack}} and
{\te{unpack}} for the {\te{Bits}} class). Type classes, instances,
and {\te{deriving}} are described in more detail in sections
{\ref{sec-overloading}}, {\ref{sec-classes}} and
{\ref{sec-instances}}.
To construct a value corresponding to some {\te{data}} definition $T$,
one simply applies the constructor to the appropriate number of
arguments (see section {\ref{sec-exprs-constrs}}); the values of those
arguments become the components/fields of the data structure.
To extract a component/field from such a value, one uses pattern
matching (see section {\ref{sec-patterns}}).
Example:
\begin{verbatim}
data Bool = False | True
\end{verbatim}
This is a ``trivial'' case of a {\te{data}} definition. The type is
not polymorphic (no type parameters); there are two summands with
constructors {\te{False}} and {\te{True}}, and neither constructor has
any fields. It is a 2-way sum of empty products. A value of type
{\te{Bool}} is either the value {\te{False}} or the value {\te{True}}
Definitions like these correspond to an ``enum'' definition in C.
Example:
\begin{verbatim}
data Operand = Register (Bit 5)
| Literal (Bit 22)
| Indexed (Bit 5) (Bit 5)
\end{verbatim}
Here, the first two summands have one field each; the third has two
fields. The fields are positional (no field names). The field of a
{\te{Register}} value must have type {\mbox{Bit 5}}. A value of type
{\te{Operand}} is either a {\te{Register}} containing a 5-bit value,
or a {\te{Literal}} containing a 22-bit value, or an {\te{Indexed}}
containing two 5-bit values.
Example:
\begin{verbatim}
data Maybe a = Nothing | Just a
deriving (Eq, Bits)
\end{verbatim}
\index{Maybe@\te{Maybe} (type)|textbf}
\index{Nothing@\te{Nothing}|see{\te{Maybe}}}
\index{Just@\te{Just}|see{\te{Maybe}}}
This is a very useful and commonly used type. Consider a function
that, given a key, looks up a table and returns some value associated
with that key. Such a function can return either {\te{Nothing}}, if
the table does not contain an entry for the given key, of {\te{Just
$v$}}, if the table contains $v$ associated with the key. The type is
polymorphic (type parameter {\qbs{a}}) because it may be used with
lookup functions for integer tables, string tables, IP address tables,
etc., {\ie} we do not want here to over-specify the type of the value
$v$ at which it may be used.
Example: