Some External Core doc fixes
[ghc-hetmet.git] / docs / ext-core / core.tex
1 \documentclass[10pt]{article}
2 \usepackage{a4wide}
3 \usepackage{code}
4 \usepackage{natbib}
5
6 \sloppy
7 \setlength{\parskip}{0.5\baselineskip plus 0.2\baselineskip minus 0.1\baselineskip}
8 \setlength{\parsep}{\parskip}
9 \setlength{\topsep}{0cm}
10 \setlength{\parindent}{0cm}
11 %\oddsidemargin -0.5 in
12 %\evensidemargin -0.5 in
13 %\textwidth 7.375 in
14
15 \newcommand{\derives}{\mbox{$\rightarrow$}}
16 \newcommand{\orderives}{\mbox{$\mid$}}
17 \newcommand{\many}[1]{\{ {#1} \}}
18 \newcommand{\oneormore}[1]{\{ {#1} \}$^{+}$}
19 \newcommand{\optional}[1]{[ {#1} ]}
20
21 \newcommand{\at}{\texttt{@}}
22 \newcommand{\att}{@}
23 \newcommand{\lam}{\texttt{\char`\\}}
24
25 \newcommand{\workingnote}[1]%
26         {\begin{quote}
27           \framebox{\parbox{.8 \linewidth}
28                            {\textbf{\textsl{Working note:}} \textsl{#1}}}
29           \end{quote}}
30
31 %% Can't have more than one paragraph in one of these boxes? WTF
32 \newcommand{\tjc}[1]%
33         {\begin{quote}
34           \framebox{\parbox{.8 \linewidth}
35                            {\textbf{\textsl{tjc:}} \textsl{#1}}}
36           \end{quote}}
37
38 \begin{document}
39
40 \title{An External Representation for the GHC Core Language\\ (For GHC 6.10)}
41 \author{Andrew Tolmach, Tim Chevalier ({\tt \{apt,tjc\}@cs.pdx.edu})\\and The GHC Team}
42
43 \maketitle
44 \makeatactive
45
46 \abstract{
47 This document provides a precise definition for the GHC Core language,
48 so that it can be used to communicate between GHC and new stand-alone
49 compilation tools such as back-ends or optimizers.\footnote{This is a draft document, which attempts to describe GHC's current
50 behavior as precisely as possible.  Working notes scattered throughout indicate
51 areas where further work is needed.  Constructive comments are very welcome, 
52 both on  the presentation, and on ways in which GHC could be improved in order
53 to simplify the Core story.
54
55 Support for generating external Core (post-optimization) was originally introduced in
56 GHC 5.02.  The definition of external Core in this document reflects the version of
57 external Core generated by the HEAD (unstable) branch of GHC as of May 3, 2008 (version 6.9), , using the compiler flag
58 @-fext-core@. We expect that GHC 6.10 will be consistent with this definition.}} The definition includes a formal grammar and an informal semantics.
59 An executable typechecker and interpreter (in Haskell), 
60 which formally embody the static and dynamic semantics,
61 are available separately.
62 }
63
64 \section{Introduction}
65
66 The Glasgow Haskell Compiler (GHC) uses an intermediate language, called
67 ``Core,''  as its internal program representation within the compiler's simplification phase.
68 Core resembles a subset of Haskell, but with explicit type annotations
69 in the style of the polymorphic lambda calculus (F$_\omega$).
70
71 GHC's front-end translates full Haskell 98 (plus some extensions) into Core. The GHC optimizer then repeatedly transforms Core programs while preserving their meaning. A ``Core Lint'' pass in GHC typechecks Core in between transformation passes (at least when the user enables linting by setting a compiler flag), verifying that transformations preserve type-correctness. Finally, GHC's back-end translates Core into STG-machine code~\citep{stg-machine} and then into
72 C or native code. 
73
74 Two existing papers discuss the original rationale for the design and use of Core~\citep{ghc-inliner,comp-by-trans-scp}, although the (two different)
75 idealized versions of Core described therein differ in significant ways from the actual Core language in current GHC. In particular, with the advent of GHC support for generalized algebraic datatypes (GADTs)~\citep{gadts} Core was extended beyond its previous F$_\omega$-style incarnation to support type equality constraints and safe coercions, and is now based on a system known as F$_C$~\citep{system-fc}.
76
77
78 Researchers interested in writing just {\it part} of a Haskell compiler,
79 such as a new back-end or a new optimizer pass, might like to use GHC to provide the other parts of the compiler.  For example, they
80 might like to use GHC's front-end to parse, desugar, and type-check source Haskell,
81 then feeding the resulting code to their own back-end tool. As another example, they might like to use Core as the target language for a front-end compiler of their own design, feeding externally synthesized Core into GHC in order to take advantage of GHC's optimizer, code generator, and run-time system. Without external Core, there are two ways for compiler writers to do this: they can link their code into the
82 GHC executable, which is an arduous process, or they can use the GHC API~\citep{ghc-api} to do the same task more cleanly. Both ways require new code to be written in Haskell.
83
84 We present a precisely specified external format for Core files. The external format is text-based and human-readable, to promote interoperability and ease of use. We hope this format will make it easier for external developers to use GHC in a modular way.
85
86 It has long been true that GHC prints an ad-hoc textual representation of Core if you set certain compiler flags. But this representation is intended to be read by people who are debugging the compiler, not by other programs. Making Core into a machine-readable, bi-directional communication format requires:
87
88 \begin{enumerate}
89 \item precisely specifying the external format of Core;
90
91 \item modifying GHC to generate external Core files (post-simplification; as always, users can control the exact transformations GHC does with command-line flags);
92
93 \item modifying GHC to accept external Core files in place of Haskell 
94 source files (users will also be able to control what GHC does to those files with command-line flags).
95
96 \end{enumerate}
97
98 The first two facilities will let developers couple GHC's front-end (parser,
99 type-checker, desugarer), and optionally its optimizer, with new back-end tools.
100 The last facility will let developers write new Core-to-Core 
101 transformations as an external tool and integrate them into GHC. It will also
102 allow new front-ends to generate Core that can be fed into GHC's optimizer or 
103 back-end.
104
105 However, because there are many (undocumented)
106 idiosyncracies in the way GHC produces Core from source Haskell, it will be hard
107 for an external tool to produce Core that can be integrated with GHC-produced Core 
108 (e.g., for the Prelude), and we don't aim to support this. Indeed, for the time being, we aim to support only the first two facilities and not the third: we define and implement Core as an external format that GHC can use to communicate with external back-end tools, and defer the larger task of extending GHC to support reading this external format back in.
109
110 This document addresses the first requirement, a formal Core definition,
111 by proposing  a formal grammar for an external representation of Core
112 (Section~\ref{sec:external}), and 
113 an informal semantics (Section~\ref{sec:informal}).
114
115 GHC supports many type system extensions; the External Core printer built into GHC only supports some of them. However, External Core should be capable of representing any Haskell 98 program, and may be able to represent programs that require certain type system extensions as well. If a program uses unsupported features, GHC may fail to compile it to Core when the @-fext-core@ flag is set, or GHC may successfully compile it to Core, but the external tools will not be able to typecheck or interpret it.
116  
117 Formal static and dynamic semantics in the form of an executable typechecker and interpreter
118 are available separately in the GHC source tree\footnote{\url{http://darcs.haskell.org/ghc}} under @utils/ext-core@.
119
120 \section{External Grammar of Core}
121 \label{sec:external}
122
123 In designing the external grammar, we have tried to strike a balance among
124 a number of competing goals, including easy parseability by machines,
125 easy readability by humans, and adequate structural simplicity to 
126 allow straightforward presentations of the semantics. Thus, we had to make some compromises. Specifically:
127
128 \begin{itemize}
129 \item In order to avoid explosion of parentheses, we support standard precedences
130 and short-cuts for expressions, types, and kinds. Thus we had to introduce
131 multiple non-terminals for each of these syntactic categories, and as a result,
132 the concrete grammar is longer and more complex than the underlying abstract syntax.
133
134 \item On the other hand, we have kept the grammar simpler by avoiding special syntax for 
135 tuple types and terms. Tuples (both boxed and unboxed) are treated 
136 as ordinary constructors. 
137
138 \item All type abstractions and applications are given in full, even though
139 some of them (e.g., for tuples) could be reconstructed; this means a parser for Core does not have to
140 reconstruct types.\footnote{These choices are certainly debatable.  In particular, keeping 
141 type applications on tuples and case arms considerably increases the size of Core files and
142 makes them less human-readable, though it allows a Core parser to be simpler.}
143
144 \item The syntax of identifiers is heavily restricted (to just
145 alphanumerics and underscores); this again makes Core easier to parse but harder to read.
146
147 \end{itemize}
148
149 We use the following notational conventions for syntax:
150
151 \begin{tabular}{ll}
152 {\it [ pat ]} & optional \\
153 {\it \{ pat \}} & zero or more repetitions \\
154 {\it \{ pat \}$^{+}$} & one or more repetitions \\
155 {\it pat$_1$ \orderives\ pat$_2$} & choice \\
156 @fibonacci@ & terminal syntax in typewriter font \\
157 \end{tabular}
158
159 \newpage
160
161 {\it
162 \begin{tabular}{lrclr}
163 {\rm Module} &   module &        \derives &      
164         \multicolumn{2}{l}{@\%module@ mident \many{tdef @;@} \many{vdefg @;@}} \\
165 \\
166 {\rm Type defn.} &       tdef &  \derives &     @%data@ qtycon \many{tbind} @=@ @{@ \optional{cdef \many{@;@ cdef}} @}@ & {\rm algebraic type}\\
167                  &       &       \orderives &    @%newtype@ qtycon qtycon \many{tbind} @=@ ty &  {\rm newtype} \\
168 \\
169 {\rm Constr. defn.} &   cdef &   \derives &      qdcon \many{@\at@ tbind} \oneormore{aty} \\
170 \\
171 {\rm Value defn.}  &    vdefg &  \derives &      @%rec@ @{@ vdef \many{@;@ vdef} @}@ &                   {\rm recursive} \\
172                    &    &        \orderives &    vdef &                                                  {\rm non-recursive} \\
173                    &    vdef  &  \derives & qvar @::@ ty @=@ exp & \\
174 \\
175 {\rm Atomic expr.} &     aexp &  \derives &      qvar &                                                 {\rm variable} \\
176                  &      &        \orderives &    qdcon &                                                {\rm data constructor}\\ 
177                  &      &        \orderives &    lit &                                                  {\rm literal} \\
178                  &      &        \orderives &    @(@ exp @)@ &                                          {\rm nested expr.}\\
179 \\
180 {\rm Expression} &      exp   &  \derives    &   aexp &                                                 {\rm atomic expresion}\\
181                  &      &       \orderives  &    aexp \oneormore{arg} &                                 {\rm application}\\
182                  &      &        \orderives &    @\@ \oneormore{binder} @->@ exp &                      {\rm abstraction}\\
183                  &      &        \orderives &    @%let@ vdefg @%in@ exp &                               {\rm local definition}\\
184                  &      &        \orderives &    @%case@ @(@aty@)@ exp @%of@ vbind @{@ alt \many{@;@ alt} @}@ & {\rm case expression}\\
185                  &      &        \orderives &    @%cast@ exp aty &                                      {\rm type coercion}\\
186                  &      &        \orderives &    @%note@  @"@ \many{char} @"@ exp &                     {\rm expression note}\\
187                  &      &        \orderives &    @%external ccall@ @"@ \many{char} @"@ aty &                    {\rm external reference}\\
188                  &      &        \orderives &    @%dynexternal ccall@ aty &                     {\rm external reference (dynamic)}\\
189                  &      &        \orderives &    @%label@ @"@ \many{char} @"@       &               {\rm external label}
190 \\
191 \\
192 {\rm Argument}   &      arg &   \derives &       \at\ aty &                                             {\rm type argument}\\
193                  &      &        \orderives &    aexp &                                                 {\rm value argument} \\
194 \\
195 {\rm Case alt.} &       alt &    \derives &     qdcon \many {@\at@ tbind} \many{vbind} @->@ exp &{\rm constructor alternative}\\
196                 &       &        \orderives &    lit @->@ exp &                         {\rm literal alternative} \\
197                 &       &        \orderives &    @%_@ @->@ exp &                                {\rm default alternative} \\
198 \\
199 {\rm Binder}     &      binder & \derives & \at\ tbind  &                                       {\rm type binder}\\
200                  &              & \orderives &  vbind   &                                               {\rm value binder}\\
201 \\
202 {\rm Type binder} &     tbind & \derives   & tyvar & {\rm implicitly of  kind @*@} \\
203                   &           & \orderives & @(@ tyvar @::@ kind @)@ & {\rm explicitly kinded} \\
204 \\
205 {\rm Value binder} &    vbind & \derives &   @(@ var @::@ ty @)@ \\
206 \\
207 {\rm Literal} &  lit &   \derives &      @(@ [@-@] \oneormore{digit} @::@ ty @)@ & {\rm integer} \\
208             &   &        \orderives &    @(@ [@-@] \oneormore{digit} @%@ \oneormore{digit} @::@ ty @)@ & {\rm rational} \\
209             &   &        \orderives &    @(@ $'$ char $'$ @::@ ty @)@ & {\rm character} \\
210             &   &        \orderives &    @(@ @"@ \many{char} @"@ @::@ ty @)@ & {\rm string} \\
211 \\
212 {\rm Character}  & char & \derives & \multicolumn{2}{l}{any ASCII character in range 0x20-0x7E except 0x22,0x27,0x5c}\\
213                 &       & \orderives & @\x@ hex hex  & {\rm ASCII code escape sequence} \\
214                 &  hex   & \derives & @0@ \orderives  \ldots \orderives  @9@ \orderives  @a@ \orderives  \ldots \orderives  @f@ \\
215 \end{tabular}
216
217 \begin{tabular}{lrclr}
218 {\rm Atomic type} & aty & \derives &     tyvar &                                        {\rm type variable} \\
219           &     &        \orderives &    qtycon &                                       {\rm type constructor}\\
220           &     &        \orderives &    @(@ ty @)@ &                                   {\rm nested type}\\
221 \\
222 {\rm Basic type} & bty  & \derives &    aty  &                                          {\rm atomic type}\\
223                   &      & \orderives & bty aty &                                       {\rm type application}\\
224         &     &        \orderives &   @%trans@ aty aty &           {\rm transitive coercion} \\
225         &     &        \orderives &   @%sym@ aty &                   {\rm symmetric coercion} \\
226         &     &        \orderives &   @%unsafe@ aty aty &          {\rm unsafe coercion} \\
227         &     &        \orderives &   @%left@ aty &                  {\rm left coercion} \\
228         &     &        \orderives &   @%right@ aty &                 {\rm right coercion} \\
229         &     &        \orderives &   @%inst@ aty aty &             {\rm instantiation coercion} \\
230 \\
231 {\rm Type} &     ty &    \derives   &   bty &                                           {\rm basic type}\\
232           &     &        \orderives &   @%forall@ \oneormore{tbind} @.@ ty  &           {\rm type abstraction}\\
233           &     &        \orderives &   bty @->@ ty  &                                  {\rm arrow type construction} \\
234   \\
235
236 {\rm Atomic kind} & akind & \derives &   @*@ &                          {\rm lifted kind}\\
237                 &       & \orderives &   @#@ &                          {\rm unlifted kind}\\
238                 &       & \orderives &   @?@ &                          {\rm open kind}\\
239                 &    &        \orderives &    bty @:=:@ bty      &      {\rm equality kind} \\
240                 &       & \orderives &   @(@ kind @)@&                  {\rm nested kind}\\
241 \\
242 {\rm Kind} &    kind &   \derives &      akind &                        {\rm atomic kind}\\
243            &    &        \orderives &    akind @->@ kind         &      {\rm arrow kind} \\
244 \\
245 {\rm Identifier}        &       mident & \derives & pname @:@ uname &   {\rm module} \\
246         &       tycon &  \derives &      uname &                {\rm type constr.}  \\
247         &       qtycon & \derives &      mident @.@  tycon &    {\rm qualified type constr.} \\
248         &       tyvar &  \derives &      lname &                {\rm type variable} \\
249         &       dcon &   \derives &      uname &                {\rm data constr.} \\
250         &       qdcon &  \derives &      mident @.@  dcon &     {\rm qualified data constr.} \\
251         &       var &    \derives &      lname &                {\rm variable} \\
252         &       qvar &   \derives &      [ mident @.@ ] var &   {\rm optionally qualified variable} \\
253 \\
254 {\rm Name}      &       lname  &  \derives &     lower \many{namechar} \\
255         &       uname &  \derives &      upper \many{namechar} & \\
256         &       pname &  \derives &      \oneormore{namechar} & \\
257         &       namechar & \derives &    lower \orderives\  upper \orderives\  digit \\
258         &       lower &  \derives &      @a@ \orderives\  @b@ \orderives\  \ldots \orderives\  @z@ \orderives\  @_@ \\
259         &       upper &  \derives &      @A@ \orderives\  @B@ \orderives\  \ldots \orderives\  @Z@ \\
260         &       digit &  \derives &      @0@ \orderives\  @1@ \orderives\  \ldots \orderives\  @9@ \\
261 \\
262 \end{tabular}
263 }
264 \section{Informal Semantics}
265 \label{sec:informal}
266
267 At the term level, Core resembles a explicitly-typed polymorphic lambda calculus (F$_\omega$), with the addition
268 of local @let@ bindings, algebraic type definitions, constructors, and @case@ expressions,
269 and primitive types, literals and operators. Its type system is richer than that of System F, supporting explicit type equality coercions and type functions.~\citep{system-fc}
270
271 In this section we concentrate on the less obvious points about Core.
272
273 \subsection{Program Organization and Modules}
274 \label{sec:modules}
275
276 Core programs are organized into {\em modules}, corresponding directly to source-level Haskell modules.
277 Each module has a identifying name {\it mident}. A module identifier consists of a {\it package name} followed by a module name, which may be hierarchical: for example, @base:GHC.Base@ is the module identifier for GHC's Base module. Its name is @Base@, and it lives in the @GHC@ hierarchy within the @base@ package. Section 5.8 of the GHC users' guide explains package names~\citep{ghc-user-guide}. In particular, note that a Core program may contain multiple modules with the same (possibly hierarchical) module name that differ in their package names. In some of the code examples that follow, we will omit package names and possibly full hierarchical module names from identifiers for brevity, but be aware that they are always required.\footnote{A possible improvement to the Core syntax would be to add explicit import lists to Core modules, which could be used to specify abbrevations for long qualified names. This would make the code more human-readable.}
278
279 Each module may contain the following kinds of top-level declarations:
280 \begin{itemize}
281 \item Algebraic data type declarations, each defining a type constructor and one or more data constructors;
282 \item Newtype declarations,  corresponding to Haskell @newtype@ declarations, each defining a type constructor and a coercion name; and
283 \item Value declarations, defining the types and values of top-level variables.
284 \end{itemize}
285
286 No type constructor, data constructor, or top-level value may be declared more than once within a given module.
287 All the type declarations are (potentially) mutually recursive. Value declarations must be
288 in dependency order, with explicit grouping of potentially mutually recursive declarations.
289
290
291 Identifiers defined in top-level declarations may be {\it external} or {\it internal}.
292 External identifiers can be referenced from any other module in
293 the program, using conventional dot notation (e.g., @base:GHC.Base.Bool@, @base:GHC.Base.True@).  
294 Internal identifiers are visible only within the defining module.
295 All type and data constructors are external, and are always defined and referenced using
296 fully qualified names (with dots).  
297
298 A top-level value is external if it is defined and referenced 
299 using a fully qualified name with a dot (e.g., @main:MyModule.foo = ...@); otherwise, it is internal
300 (e.g., @bar = ...@).  
301 Note that Core's notion of an external identifier does not necessarily coincide with that of ``exported''
302 identifier in a Haskell source module. An identifier can be an external identifier in Core, but not be exported by the original Haskell source module.\footnote{Two examples of such identifiers are: data constructors, and values that potentially appear in an unfolding. For an example of the latter, consider @Main.foo = ... Main.bar ...@, where @Main.foo@ is inlineable. Since @bar@ appears in @foo@'s unfolding, it is defined and referenced with an external name, even if @bar@ was not exported by the original source module.} However, if an identifier was exported by the Haskell source module, it will appear as an external name in Core.
303
304 Core modules have no explicit import or export lists. 
305 Modules may be mutually recursive. Note that because of the latter fact, GHC currently prints out the top-level bindings for every module as a single recursive group, in order to avoid keeping track of dependencies between top-level values within a module. An external Core tool could reconstruct dependencies later, of course.
306
307 There is also an implicitly-defined module @ghc-prim:GHC.Prim@, which exports the ``built-in'' types and values
308 that must be provided by any implementation of Core (including GHC).   Details of this
309 module are in Section~\ref{sec:prims}.
310
311 A Core {\em program} is a collection of distinctly-named modules that includes a module
312 called @main:Main@ having an exported value called @main:ZCMain.main@ of type @base:GHC.IOBase.IO a@ (for some type @a@). (Note that the strangely named wrapper for @main@ is the one exception to the rule that qualified names defined within a module @m@ must have module name @m@.)
313
314 Many Core programs will contain library modules, such as @base:GHC.Base@, which implement parts of the Haskell standard library.  In principle, these modules are ordinary Haskell modules, with no special status.  In practice, the requirement on the type of @main:Main.main@ implies that every program will contain a large subset of
315 the standard library modules.
316
317 \subsection{Namespaces}
318 \label{sec:namespaces}
319
320 There are five distinct namespaces: 
321 \begin{enumerate}
322 \item module identifiers (@mident@),
323 \item type constructors (@tycon@),
324 \item type variables (@tyvar@),
325 \item data constructors (@dcon@),
326 \item term variables (@var@).
327 \end{enumerate}  
328
329 Spaces (1), (2+3), and (4+5) can be distinguished from each other by context.
330 To distinguish (2) from (3) and (4) from (5), we require that data and type constructors begin with an upper-case character, and that term and type variables begin with a lower-case character.
331
332 Primitive types and operators are not syntactically distinguished.
333
334 Primitive {\it coercion} operators, of which there are six, {\it are} syntactically distinguished in the grammar. This is because these coercions must be fully applied, and because distinguishing their applications in the syntax makes typechecking easier.
335
336 A given variable (type or term) may have multiple definitions within a module.
337 However, definitions of term variables never ``shadow'' one another: the scope of the definition
338 of a given variable never contains a redefinition of the same variable. Type variables may be shadowed. Thus, if a term variable has multiple definitions within a module, all those definitions must be local (let-bound). The only exception
339 to this rule is that (necessarily closed) types labelling @%external@ expressions may contain 
340 @tyvar@ bindings that shadow outer bindings.
341
342 Core generated by GHC makes heavy use of encoded names, in which the characters @Z@ and @z@ are
343 used to introduce escape sequences for non-alphabetic characters such as dollar sign @$@ (@zd@),
344 hash @#@ (@zh@), plus @+@ (@zp@), etc.  This is the same encoding used in @.hi@ files and in the
345 back-end of GHC itself, except that we sometimes change an initial @z@ to @Z@, or vice-versa, 
346 in order to maintain case distinctions.
347
348 Finally, note that hierarchical module names are z-encoded in Core: for example, @base:GHC.Base.foo@ is rendered as @base:GHCziBase.foo@. A parser may reconstruct the module hierarchy, or regard @GHCziBase@ as a flat name.
349 \subsection{Types and Kinds}
350 \label{sec:typesandkinds}
351
352 In Core, all type abstractions and applications are explicit.  This make it easy to 
353 typecheck any (closed) fragment of Core code.  An full executable typechecker is available separately.
354
355 \subsubsection{Types}
356 Types are described by type expressions, which 
357 are built from named type constructors and type variables
358 using type application and universal quantification.  
359 Each type constructor has a fixed arity $\geq 0$.  
360 Because it is so widely used, there is
361 special infix syntax for the fully-applied function type constructor (@->@).
362 (The prefix identifier for this constructor is @ghc-prim:GHC.Prim.ZLzmzgZR@; this should
363 only appear in unapplied or partially applied form.)
364
365 There are also a number of other primitive type constructors (e.g., @Intzh@) that
366 are predefined in the @GHC.Prim@ module, but have no special syntax.
367 @%data@ and @%newtype@ declarations introduce additional type constructors, as described below.
368 Type constructors are distinguished solely by name.
369
370 \subsubsection{Coercions}
371
372 A type may also be built using one of the primitive coercion operators, as described in Section~\ref{sec:namespaces}. For details on the meanings of these operators, see the System FC paper~\citep{system-fc}. Also see Section~\ref{sec:newtypes} for examples of how GHC uses coercions in Core code.
373
374 \subsubsection{Kinds}
375 As described in the Haskell definition, it is necessary to distinguish 
376 well-formed type-expressions by classifying them into different {\it kinds}~\citep[p. 41]{haskell98}.
377 In particular, Core explicitly records the kind of every bound type variable. 
378
379 In addition, Core's kind system includes equality kinds, as in System FC~\citep{system-fc}. An application of a built-in coercion, or of a user-defined coercion as introduced by a newtype declaration, has an equality kind.
380 \subsubsection{Lifted and Unlifted Types}
381 Semantically, a type is {\it lifted} if and only if it has bottom as an element. We need to distinguish them because operationally, terms with lifted types may be represented by closures; terms with unlifted types must not be represented by closures, which implies that any unboxed value is necessarily unlifted. We distinguish between lifted and unlifted types by ascribing them different kinds.
382
383 Currently, all the primitive types are unlifted 
384 (including a few boxed primitive types such as @ByteArrayzh@).
385 Peyton Jones and Launchbury~[\citeyear{pj:unboxed}] described the ideas behind unboxed and unlifted types.
386
387 \subsubsection{Type Constructors; Base Kinds and Higher Kinds}
388 Every type constructor has a kind, depending on its arity and whether it or its arguments are lifted.
389
390 Term variables can only be assigned types that have base kinds: the base kinds are @*@,@#@, and @?@. The three base kinds distinguish the liftedness of the types they classify:
391 @*@ represents lifted types; @#@ represents unlifted types; and @?@ is the ``open'' kind, representing a type that may be either lifted or unlifted. Of these, only @*@ ever
392 appears in Core type declarations generated from user code; the other two are needed to describe
393 certain types in primitive (or otherwise specially-generated) code (which, after optimization, could potentially appear anywhere).
394
395 In particular, no top-level identifier (except in @ghc-prim:GHC.Prim@) has a type of kind @#@ or @?@.
396
397 Nullary type constructors have base kinds: for example, the type @Int@ has kind @*@, and @Int#@ has kind @#@.
398
399 Non-nullary type constructors have higher kinds: kinds that have the form $k_1 @->@ k_2$,
400 where $k_1$ and $k_2$ are kinds.   For example, the function type constructor
401 @->@ has kind @* -> (* -> *)@.  Since Haskell allows abstracting over type
402 constructors, type variables may have higher kinds; however, much more commonly they have kind @*@, so that is the default if a type binder omits a kind.
403
404 \subsubsection{Type Synonyms and Type Equivalence}
405 There is no mechanism for defining type synonyms (corresponding to
406 Haskell @type@ declarations).
407
408 Type equivalence is just syntactic equivalence on type expressions
409 (of base kinds) modulo:
410
411 \begin{itemize} 
412 \item alpha-renaming of variables bound in @%forall@ types;
413 \item the identity $a$ @->@ $b$ $\equiv$ @ghc-prim:GHC.Prim.ZLzmzgZR@ $a$ $b$
414 \end{itemize}
415
416 \subsection{Algebraic data types}
417
418 Each @data@ declaration introduces a new type constructor and a set of one or
419 more data constructors, normally corresponding directly to a source Haskell @data@ declaration.
420 For example, the source declaration
421 \begin{code}
422 data Bintree a =
423    Fork (Bintree a) (Bintree a)
424 |  Leaf a
425 \end{code}
426 might induce the following Core declaration
427 \begin{code}
428 %data Bintree a = {
429    Fork (Bintree a) (Bintree a);
430    Leaf a)}
431 \end{code}
432 which introduces the unary type constructor @Bintree@ of kind @*->*@  and two data constructors with types
433 \begin{code}
434 Fork :: %forall a . Bintree a -> Bintree a -> Bintree a
435 Leaf :: %forall a . a -> Bintree a
436 \end{code}
437 We define the {\it arity} of each data constructor to be the number of value arguments it takes;
438 e.g. @Fork@ has arity 2 and @Leaf@ has arity 1.
439
440 For a less conventional example illustrating the possibility of higher-order kinds, the Haskell source declaration
441 \begin{code}
442 data A f a = MkA (f a)
443 \end{code}
444 might induce the Core declaration
445 \begin{code}
446 %data A (f::*->*) a = { MkA (f a) }
447 \end{code}
448 which introduces the constructor
449 \begin{code}
450 MkA :: %forall (f::*->*) a . (f a) -> (A f) a
451 \end{code}
452
453 GHC (like some other Haskell implementations) supports an extension to Haskell98 
454 for existential types such as 
455 \begin{code}
456 data T = forall a . MkT a (a -> Bool)
457 \end{code}
458 This is represented by the Core declaration
459 \begin{code}
460 %data T = {MkT @a a (a -> Bool)}
461 \end{code}
462 which introduces the nullary type constructor @T@ and the data constructor
463 \begin{code}
464 MkT :: %forall a . a -> (a -> Bool) -> T
465 \end{code}
466 In general, existentially quantified variables appear as extra univerally
467 quantified variables in the data contructor types.
468 An example of how to construct and deconstruct values of type @T@ is shown in 
469 Section~\ref{sec:exprs}.
470
471 \subsection{Newtypes}
472 \label{sec:newtypes}
473
474 Each Core @%newtype@ declaration introduces a new type constructor and an associated
475 representation type, corresponding to a source Haskell @newtype@
476 declaration. However, unlike in source Haskell, a @%newtype@ declaration does not introduce any data constructors.
477
478 Each @%newtype@ declaration also introduces a new coercion (syntactically, just another type constructor) that implies an axiom equating the type constructor, applied to any type variables bound by the @%newtype@, to the representation type.
479
480 For example, the Haskell fragment
481 \begin{code}
482 newtype U = MkU Bool
483 u = MkU True
484 v = case u of
485   MkU b -> not b
486 \end{code}
487 might induce the Core fragment
488 \begin{code}
489 %newtype U ZCCoU = Bool;
490 u :: U = %cast (True)
491            ((%sym ZCCoU));
492 v :: Bool = not (%cast (u) ZCCoU);
493 \end{code}
494
495 The newtype declaration implies that the types {\tt U} and {\tt Bool} have equivalent representations, and the coercion axiom {\tt ZCCoU} provides evidence that {\tt U} is equivalent to {\tt Bool}. Notice that in the body of {\tt u}, the boolean value {\tt True} is cast to type {\tt U} using the primitive symmetry rule applied to {\tt ZCCoU}: that is, using a coercion of kind {\tt Bool :=: U}. And in the body of {\tt v}, {\tt u} is cast back to type {\tt Bool} using the axiom {\tt ZCCoU}.
496
497 Notice that the {\tt case} in the Haskell source code above translates to a {\tt cast} in the corresponding Core code. That is because operationally, a {\tt case} on a value whose type is declared by a {\tt newtype} declaration is a no-op. Unlike a {\tt case} on any other value, such a {\tt case} does no evaluation: its only function is to coerce its scrutinee's type.
498
499 Also notice that unlike in a previous draft version of External Core, there is no need to handle recursive newtypes specially.
500 \subsection{Expression Forms}
501 \label{sec:exprs}
502
503 Variables and data constructors are straightforward.
504
505 Literal ({\it lit}) expressions consist of a literal value, in one of four different formats,
506 and a (primitive) type annotation.   Only certain combinations of format and type
507 are permitted; see Section~\ref{sec:prims}.  The character and string formats can describe only
508 8-bit ASCII characters.  
509
510 Moreover, because the operational semantics for Core interprets strings as C-style null-terminated
511 strings, strings should not contain embedded nulls.
512
513 In Core, value applications, type applications, value abstractions, and type abstractions are all explicit. To tell them apart, type arguments in applications
514 and formal type arguments in abstractions are preceded by an \at\ symbol. (In abstractions,
515 the \at\ plays essentially the same role as the more usual $\Lambda$ symbol.)
516 For example, the Haskell source declaration
517 \begin{code}
518 f x = Leaf (Leaf x)
519 \end{code}
520 might induce the Core declaration
521 \begin{code}
522 f :: %forall a . a -> BinTree (BinTree a) =
523   \ @a (x::a) -> Leaf @(Bintree a) (Leaf @a x)
524 \end{code}
525
526 Value applications may be of user-defined functions, data constructors, or primitives.
527 None of these sorts of applications are necessarily saturated.
528
529 Note that the arguments of type applications are not always of kind @*@.  For example,
530 given our previous definition of type @A@:
531 \begin{code}
532 data A f a = MkA (f a)
533 \end{code}
534 the source code
535 \begin{code}
536 MkA (Leaf True)
537 \end{code}
538 becomes
539 \begin{code}
540 (MkA @Bintree @Bool) (Leaf @Bool True)
541 \end{code}
542
543 Local bindings, of a single variable or of a set of mutually recursive variables,
544 are represented by @%let@ expressions in the usual way.
545
546 By far the most complicated expression form is @%case@.
547 @%case@ expressions are permitted over values of any type, although they will normally
548 be algebraic or primitive types (with literal values).
549 Evaluating a @%case@ forces the evaluation of the expression being
550 tested (the ``scrutinee''). The value of the scrutinee is bound to the variable
551 following the @%of@ keyword, which is in scope in all alternatives; 
552 this is useful when the scrutinee is a non-atomic
553 expression (see next example). The scrutinee is preceded by the type of the entire @%case@ expression: that is, the result type that all of the @%case@ alternatives have (this is intended to make type reconstruction easier in the presence of type equality coercions).
554
555 In an algebraic @%case@, all the case alternatives must be
556 labeled with distinct data constructors from the algebraic type, followed by
557 any existential type variable bindings (see below), and 
558 typed term variable bindings corresponding to the data constructor's
559 arguments. The number of variables must match the data constructor's arity.
560
561 For example, the following Haskell source expression
562 \begin{code}
563 case g x of
564   Fork l r -> Fork r l
565   t@(Leaf v) -> Fork t t
566 \end{code}
567 might induce the Core expression
568 \begin{code}
569 %case ((Bintree a)) g x %of (t::Bintree a)
570    Fork (l::Bintree a) (r::Bintree a) ->
571       Fork @a r l
572    Leaf (v::a) ->
573       Fork @a t t
574 \end{code}
575
576 When performing a @%case@ over a value of an existentially-quantified algebraic
577 type, the alternative must include extra local type bindings 
578 for the existentially-quantified variables.  For example, given 
579 \begin{code}
580 data T = forall a . MkT a (a -> Bool)
581 \end{code}
582 the source
583 \begin{code}
584 case x of
585   MkT w g -> g w
586 \end{code}
587 becomes
588 \begin{code}
589 %case x %of (x'::T) 
590   MkT @b (w::b) (g::b->Bool) -> g w
591 \end{code}
592
593 In a @%case@ over literal alternatives,
594 all the case alternatives must be distinct literals of the same primitive type.
595
596 The list of alternatives may begin with a 
597 default alternative labeled with an underscore (@%_@), whose right-hand side will be evaluated if
598 none of the other alternatives match.  The default is optional except for in a case
599 over a primitive type, or when there are no other alternatives.
600 If the case is over neither an
601 algebraic type nor a primitive type, then the list of alternatives must contain a default alternative and nothing else.
602 For algebraic cases, the set of alternatives
603 need not be exhaustive, even if no default is given; if alternatives are missing,
604 this implies that GHC has deduced that they cannot occur. 
605
606 @%cast@ is used to manipulate newtypes, as described in Section~\ref{sec:newtypes}. The @%cast@ expression takes an expression and a coercion:
607 syntactically, the coercion is an arbitrary type, but it must have an
608 equality kind. In an expression @(cast e co)@, if @e :: T@ and @co@
609 has kind @T :=: U@, then the overall expression has type
610 @U@~\citep{ghc-fc-commentary}. Here, @co@ must be a coercion whose left-hand side is @T@.
611
612 Note
613 that unlike the @%coerce@ expression that existed in previous versions
614 of Core, this means that @%cast@ is (almost) type-safe: the coercion
615 argument provides evidence that can be verified by a
616 typechecker. There are still unsafe @%cast@s, corresponding to the
617 unsafe @%coerce@ construct that existed in old versions of Core,
618 because there is a primitive unsafe coercion type that
619 can be used to cast arbitrary types to each other. GHC uses this for
620 such purposes as coercing the return type of a function (such as
621 error) which is guaranteed to never return:
622 \begin{code}
623 case (error "") of
624   True -> 1
625   False ->  2
626 \end{code}
627 becomes:
628 \begin{code}
629     %cast (error @ Bool (ZMZN @ Char))
630     (%unsafe Bool Integer);
631 \end{code}
632 @%cast@ has no operational meaning and is only used in typechecking.
633
634
635  
636 A @%note@ expression carries arbitrary internal information that GHC finds interesting. The information is encoded as a string.  Expression notes currently generated by GHC
637 include the inlining pragma (@InlineMe@) and cost-center labels for profiling.
638
639 A @%external@ expression denotes an external identifier, which has
640 the indicated type (always expressed in terms of Haskell primitive types). External Core supports two kinds of external calls: @%external@ and @%dynexternal@. Only the former is supported by the current set of stand-alone Core tools. In addition, there is a @%label@ construct which GHC may generate but which the Core tools do not support.
641
642 The present syntax for externals is sufficient for describing C functions and labels.
643 Interfacing to other languages may require additional information or a different interpretation
644 of the name string.
645
646
647 \subsection{Expression Evaluation}  
648 \label{sec:evaluation}
649
650 The dynamic semantics of Core are defined on the type-erasure of the program: for example, we ignore all type abstractions and applications.  The denotational semantics of
651 the resulting type-free program are just the conventional ones for a call-by-name
652 language, in which expressions are only evaluated on demand.
653 But Core is intended to be a call-by-{\it{need}} language, in which
654 expressions are only evaluated {\it once}.  To express the sharing behavior
655 of call-by-need, we give an operational model in the style of Launchbury~\citep{launchbury93natural}.
656
657 This section describes the model informally; a more formal semantics is
658 separately available as an executable interpreter.
659
660 To simplify the semantics, we consider only ``well-behaved'' Core programs in which
661 constructor and primitive applications are fully saturated, and in which
662 non-trivial expresssions of unlifted kind (@#@) appear only as scrutinees
663 in @%case@ expressions.  Any program can easily be put into this form;
664 a separately available preprocessor illustrates how.
665 In the remainder of this section, we use ``Core'' to mean ``well-behaved'' Core.
666
667 Evaluating a Core expression means reducing it to {\it weak-head normal form (WHNF)},
668 i.e., a primitive value, lambda abstraction, or fully-applied data constructor. Evaluating a program means evaluating the expression @main:ZCMain.main@.
669
670 To make sure that expression evaluation is shared, we
671 make use of a {\it heap}, which contains {\it heap entries}. A heap entry can be:
672 \begin{itemize}
673 \item A {\em thunk}, representing an unevaluated expression, also known as a {\em suspension}.
674
675 \item A {\em WHNF}, representing an evaluated expression. The result of evaluating a thunk is a WHNF. A WHNF is always a closure (corresponding to a lambda abstraction in the source program) or a data constructor application: computations over primitive types are never suspended.
676 \end{itemize}
677
678 {\it Heap pointers} point to heap entries: at different times, the same heap pointer can point to either a thunk or a WHNF, because the run-time system overwrites thunks with WHNFs as computation proceeds.
679
680 The suspended computation that a thunk represents might represent evaluating one of three different kinds of expression. The run-time system allocates a different kind of thunk depending on what kind of expression it is:
681 \begin{itemize}
682 \item A thunk for a value definition has a group of suspended defining expressions, along with a list of bindings between defined names and heap pointers to those suspensions. (A value definition may be a recursive group of definitions or a single non-recursive definition, and it may be top-level (global) or @let@-bound (local)).
683
684 \item A thunk for a function application (where the function is user-defined) has a suspended actual argument expression, and a binding between the formal argument and a heap pointer to that suspension.
685
686 \item A thunk for a constructor application has a suspended actual argument expression; the entire constructed value has a heap pointer to that suspension embedded in it.
687 \end{itemize}
688
689 As computation proceeds, copies of the heap pointer for a given thunk propagate through the executing program. 
690 When another computation demands the result of that thunk, the thunk is {\it forced}: the run-time system computes the thunk's result, yielding a WHNF, and overwrites the heap entry for the thunk with the WHNF. Now, all copies of the heap pointer point to the new heap entry: a WHNF. Forcing occurs
691 only in the context of
692 \begin{itemize}
693 \item evaluating the operator expression of an application; 
694
695 \item evaluating the scrutinee of a @case@ expression; or 
696
697 \item evaluating an argument to a primitive or external function application
698 \end{itemize}
699
700 When no pointers to a heap entry (whether it is a thunk or WHNF) remain, the garbage collector can reclaim the space it uses. We assume this happens implicitly.
701
702 With the exception of functions, arrays, and mutable variables, we intend that values of all primitive types
703 should be held {\it unboxed}: they should not be heap-allocated. This does not violate call-by-need semantics: all
704 primitive types are {\it unlifted}, which means that values of those types must be evaluated strictly.  Unboxed tuple types are not heap-allocated either.
705
706 Certain primitives and @%external@ functions cause side-effects to state threads or to the real world.
707 Where the ordering of these side-effects matters, Core already forces this order with data dependencies on the pseudo-values representing the threads.
708
709 An implementation must specially support the @raisezh@ and @handlezh@ primitives: for example, by using a handler stack.  
710 Again, real-world threading guarantees that they will execute in the correct order.
711
712 \section{Primitive Module}
713 \label{sec:prims}
714
715 The semantics of External Core rely on the contents and informal semantics of the primitive module @ghc-prim:GHC.Prim@.
716 Nearly all the primitives are required in order to cover GHC's implementation of the Haskell98
717 standard prelude; the only operators that can be completely omitted are those supporting the byte-code interpreter, 
718 parallelism, and foreign objects.  Some of the concurrency primitives are needed, but can be
719 given degenerate implementations if it desired to target a purely sequential backend (see Section~\ref{sec:sequential}).
720
721 In addition to these primitives, a large number of C library functions are required to implement
722 the full standard Prelude, particularly to handle I/O and arithmetic on less usual types.
723
724 For a full listing of the names and types of the primitive operators, see the GHC library documentation~\citep{ghcprim}.
725
726
727 \subsection{Non-concurrent Back End}
728 \label{sec:sequential}
729
730 The Haskell98 standard prelude doesn't include any concurrency support, but GHC's
731 implementation of it relies on the existence of some concurrency primitives.  However,
732 it never actually forks multiple threads.  Hence, the concurrency primitives can
733 be given degenerate implementations that will work in a non-concurrent setting,
734 as follows:
735 \begin{itemize}
736 \item  @ThreadIdzh@ can be represented
737 by a singleton type, whose (unique) value is returned by @myThreadIdzh@.
738
739 \item @forkzh@ can just die with an ``unimplemented'' message.
740
741 \item @killThreadzh@ and @yieldzh@ can also just die ``unimplemented'' since
742 in a one-thread world, the only thread a thread can kill is itself, and
743 if a thread yields the program hangs.
744
745 \item @MVarzh a@ can be represented by @MutVarzh (Maybe a)@;
746 where a concurrent implementation would block, the sequential implementation can
747 just die with a suitable message (since no other thread exists to unblock it).
748
749 \item @waitReadzh@ and @waitWritezh@ can be implemented using a @select@ with no timeout. 
750 \end{itemize}
751
752 \subsection{Literals}
753
754 Only the following combination of literal forms and types are permitted:
755
756 \begin{tabular}{|l|l|l|}
757 \hline
758 Literal form & Type & Description \\
759 \hline 
760 integer &  @Intzh@ & Int \\
761 %       &  @Int32zh@ & Int32 \\
762 %       &  @Int64zh@ & Int64 \\
763         &  @Wordzh@ & Word \\
764 %       &  @Word32zh@ & Word32 \\
765 %       &  @Word64zh@ & Word64 \\
766         &  @Addrzh@ & Address \\
767         &  @Charzh@ & Unicode character code \\
768 rational & @Floatzh@ & Float \\
769          & @Doublezh@ & Double \\
770 character & @Charzh@ & Unicode character specified by ASCII character\\
771 string &  @Addrzh@  & Address of specified C-format string \\
772 \hline
773 \end{tabular}
774
775 \bibliography{core}
776 \bibliographystyle{abbrvnat}
777
778 \end{document}