1 \documentclass[10pt]{article}
8 \setlength{\parskip}{0.5\baselineskip plus 0.2\baselineskip minus 0.1\baselineskip}
9 \setlength{\parsep}{\parskip}
10 \setlength{\topsep}{0cm}
11 \setlength{\parindent}{0cm}
12 %\oddsidemargin -0.5 in
13 %\evensidemargin -0.5 in
16 \newcommand{\derives}{\mbox{$\rightarrow$}}
17 \newcommand{\orderives}{\mbox{$\mid$}}
18 \newcommand{\many}[1]{\{ {#1} \}}
19 \newcommand{\oneormore}[1]{\{ {#1} \}$^{+}$}
20 \newcommand{\optional}[1]{[ {#1} ]}
22 \newcommand{\at}{\texttt{@}}
24 \newcommand{\lam}{\texttt{\char`\\}}
26 \newcommand{\workingnote}[1]%
28 \framebox{\parbox{.8 \linewidth}
29 {\textbf{\textsl{Working note:}} \textsl{#1}}}
32 %% Can't have more than one paragraph in one of these boxes? WTF
35 \framebox{\parbox{.8 \linewidth}
36 {\textbf{\textsl{tjc:}} \textsl{#1}}}
41 \title{An External Representation for the GHC Core Language\\ (For GHC 6.10)}
42 \author{Andrew Tolmach, Tim Chevalier ({\tt \{apt,tjc\}@cs.pdx.edu})\\and The GHC Team}
48 This document provides a precise definition for the GHC Core language,
49 so that it can be used to communicate between GHC and new stand-alone
50 compilation tools such as back-ends or optimizers.\footnote{This is a draft document, which attempts to describe GHC's current
51 behavior as precisely as possible. Working notes scattered throughout indicate
52 areas where further work is needed. Constructive comments are very welcome,
53 both on the presentation, and on ways in which GHC could be improved in order
54 to simplify the Core story.
56 Support for generating external Core (post-optimization) was originally introduced in
57 GHC 5.02. The definition of external Core in this document reflects the version of
58 external Core generated by the HEAD (unstable) branch of GHC as of May 3, 2008 (version 6.9), , using the compiler flag
59 @-fext-core@. We expect that GHC 6.10 will be consistent with this definition.} The definition includes a formal grammar and an informal semantics.
60 An executable typechecker and interpreter (in Haskell),
61 which formally embody the static and dynamic semantics,
62 are available separately.
65 \section{Introduction}
67 The Glasgow Haskell Compiler (GHC) uses an intermediate language, called
68 ``Core,'' as its internal program representation within the compiler's simplification phase.
69 Core resembles a subset of Haskell, but with explicit type annotations
70 in the style of the polymorphic lambda calculus (F$_\omega$).
72 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
75 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)
76 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}.
79 Researchers interested in writing just {\it part} of a Haskell compiler,
80 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
81 might like to use GHC's front-end to parse, desugar, and type-check source Haskell,
82 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
83 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.
85 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.
87 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:
90 \item precisely specifying the external format of Core;
92 \item modifying GHC to generate external Core files (post-simplification; as always, users can control the exact transformations GHC does with command-line flags);
94 \item modifying GHC to accept external Core files in place of Haskell
95 source files (users will also be able to control what GHC does to those files with command-line flags).
99 The first two facilities will let developers couple GHC's front-end (parser,
100 type-checker, desugarer), and optionally its optimizer, with new back-end tools.
101 The last facility will let developers write new Core-to-Core
102 transformations as an external tool and integrate them into GHC. It will also
103 allow new front-ends to generate Core that can be fed into GHC's optimizer or
106 However, because there are many (undocumented)
107 idiosyncracies in the way GHC produces Core from source Haskell, it will be hard
108 for an external tool to produce Core that can be integrated with GHC-produced Core
109 (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.
111 This document addresses the first requirement, a formal Core definition,
112 by proposing a formal grammar for an external representation of Core
113 (Section~\ref{sec:external}), and
114 an informal semantics (Section~\ref{sec:informal}).
116 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.
118 Formal static and dynamic semantics in the form of an executable typechecker and interpreter
119 are available separately in the GHC source tree\footnote{\url{http://darcs.haskell.org/ghc}} under @utils/ext-core@.
121 \section{External Grammar of Core}
124 In designing the external grammar, we have tried to strike a balance among
125 a number of competing goals, including easy parseability by machines,
126 easy readability by humans, and adequate structural simplicity to
127 allow straightforward presentations of the semantics. Thus, we had to make some compromises. Specifically:
130 \item In order to avoid explosion of parentheses, we support standard precedences
131 and short-cuts for expressions, types, and kinds. Thus we had to introduce
132 multiple non-terminals for each of these syntactic categories, and as a result,
133 the concrete grammar is longer and more complex than the underlying abstract syntax.
135 \item On the other hand, we have kept the grammar simpler by avoiding special syntax for
136 tuple types and terms. Tuples (both boxed and unboxed) are treated
137 as ordinary constructors.
139 \item All type abstractions and applications are given in full, even though
140 some of them (e.g., for tuples) could be reconstructed; this means a parser for Core does not have to
141 reconstruct types.\footnote{These choices are certainly debatable. In particular, keeping
142 type applications on tuples and case arms considerably increases the size of Core files and
143 makes them less human-readable, though it allows a Core parser to be simpler.}
145 \item The syntax of identifiers is heavily restricted (to just
146 alphanumerics and underscores); this again makes Core easier to parse but harder to read.
150 We use the following notational conventions for syntax:
153 {\it [ pat ]} & optional \\
154 {\it \{ pat \}} & zero or more repetitions \\
155 {\it \{ pat \}$^{+}$} & one or more repetitions \\
156 {\it pat$_1$ \orderives\ pat$_2$} & choice \\
157 @fibonacci@ & terminal syntax in typewriter font \\
163 \begin{tabular}{lrclr}
164 {\rm Module} & module & \derives &
165 \multicolumn{2}{l}{@\%module@ mident \many{tdef @;@} \many{vdefg @;@}} \\
167 {\rm Type defn.} & tdef & \derives & @%data@ qtycon \many{tbind} @=@ @{@ \optional{cdef \many{@;@ cdef}} @}@ & {\rm algebraic type}\\
168 & & \orderives & @%newtype@ qtycon qtycon \many{tbind} @=@ ty & {\rm newtype} \\
170 {\rm Constr. defn.} & cdef & \derives & qdcon \many{@\at@ tbind} \oneormore{aty} \\
172 {\rm Value defn.} & vdefg & \derives & @%rec@ @{@ vdef \many{@;@ vdef} @}@ & {\rm recursive} \\
173 & & \orderives & vdef & {\rm non-recursive} \\
174 & vdef & \derives & qvar @::@ ty @=@ exp & \\
176 {\rm Atomic expr.} & aexp & \derives & qvar & {\rm variable} \\
177 & & \orderives & qdcon & {\rm data constructor}\\
178 & & \orderives & lit & {\rm literal} \\
179 & & \orderives & @(@ exp @)@ & {\rm nested expr.}\\
181 {\rm Expression} & exp & \derives & aexp & {\rm atomic expresion}\\
182 & & \orderives & aexp \oneormore{arg} & {\rm application}\\
183 & & \orderives & @\@ \oneormore{binder} @->@ exp & {\rm abstraction}\\
184 & & \orderives & @%let@ vdefg @%in@ exp & {\rm local definition}\\
185 & & \orderives & @%case@ @(@aty@)@ exp @%of@ vbind @{@ alt \many{@;@ alt} @}@ & {\rm case expression}\\
186 & & \orderives & @%cast@ exp aty & {\rm type coercion}\\
187 & & \orderives & @%note@ @"@ \many{char} @"@ exp & {\rm expression note}\\
188 & & \orderives & @%external ccall@ @"@ \many{char} @"@ aty & {\rm external reference}\\
189 & & \orderives & @%dynexternal ccall@ aty & {\rm external reference (dynamic)}\\
190 & & \orderives & @%label@ @"@ \many{char} @"@ & {\rm external label}
193 {\rm Argument} & arg & \derives & \at\ aty & {\rm type argument}\\
194 & & \orderives & aexp & {\rm value argument} \\
196 {\rm Case alt.} & alt & \derives & qdcon \many {@\at@ tbind} \many{vbind} @->@ exp &{\rm constructor alternative}\\
197 & & \orderives & lit @->@ exp & {\rm literal alternative} \\
198 & & \orderives & @%_@ @->@ exp & {\rm default alternative} \\
200 {\rm Binder} & binder & \derives & \at\ tbind & {\rm type binder}\\
201 & & \orderives & vbind & {\rm value binder}\\
203 {\rm Type binder} & tbind & \derives & tyvar & {\rm implicitly of kind @*@} \\
204 & & \orderives & @(@ tyvar @::@ kind @)@ & {\rm explicitly kinded} \\
206 {\rm Value binder} & vbind & \derives & @(@ var @::@ ty @)@ \\
208 {\rm Literal} & lit & \derives & @(@ [@-@] \oneormore{digit} @::@ ty @)@ & {\rm integer} \\
209 & & \orderives & @(@ [@-@] \oneormore{digit} @%@ \oneormore{digit} @::@ ty @)@ & {\rm rational} \\
210 & & \orderives & @(@ $'$ char $'$ @::@ ty @)@ & {\rm character} \\
211 & & \orderives & @(@ @"@ \many{char} @"@ @::@ ty @)@ & {\rm string} \\
213 {\rm Character} & char & \derives & \multicolumn{2}{l}{any ASCII character in range 0x20-0x7E except 0x22,0x27,0x5c}\\
214 & & \orderives & @\x@ hex hex & {\rm ASCII code escape sequence} \\
215 & hex & \derives & @0@ \orderives \ldots \orderives @9@ \orderives @a@ \orderives \ldots \orderives @f@ \\
218 \begin{tabular}{lrclr}
219 {\rm Atomic type} & aty & \derives & tyvar & {\rm type variable} \\
220 & & \orderives & qtycon & {\rm type constructor}\\
221 & & \orderives & @(@ ty @)@ & {\rm nested type}\\
223 {\rm Basic type} & bty & \derives & aty & {\rm atomic type}\\
224 & & \orderives & bty aty & {\rm type application}\\
225 & & \orderives & @%trans@ aty aty & {\rm transitive coercion} \\
226 & & \orderives & @%sym@ aty & {\rm symmetric coercion} \\
227 & & \orderives & @%unsafe@ aty aty & {\rm unsafe coercion} \\
228 & & \orderives & @%left@ aty & {\rm left coercion} \\
229 & & \orderives & @%right@ aty & {\rm right coercion} \\
230 & & \orderives & @%inst@ aty aty & {\rm instantiation coercion} \\
232 {\rm Type} & ty & \derives & bty & {\rm basic type}\\
233 & & \orderives & @%forall@ \oneormore{tbind} @.@ ty & {\rm type abstraction}\\
234 & & \orderives & bty @->@ ty & {\rm arrow type construction} \\
237 {\rm Atomic kind} & akind & \derives & @*@ & {\rm lifted kind}\\
238 & & \orderives & @#@ & {\rm unlifted kind}\\
239 & & \orderives & @?@ & {\rm open kind}\\
240 & & \orderives & bty @:=:@ bty & {\rm equality kind} \\
241 & & \orderives & @(@ kind @)@& {\rm nested kind}\\
243 {\rm Kind} & kind & \derives & akind & {\rm atomic kind}\\
244 & & \orderives & akind @->@ kind & {\rm arrow kind} \\
246 {\rm Identifier} & mident & \derives & pname @:@ uname & {\rm module} \\
247 & tycon & \derives & uname & {\rm type constr.} \\
248 & qtycon & \derives & mident @.@ tycon & {\rm qualified type constr.} \\
249 & tyvar & \derives & lname & {\rm type variable} \\
250 & dcon & \derives & uname & {\rm data constr.} \\
251 & qdcon & \derives & mident @.@ dcon & {\rm qualified data constr.} \\
252 & var & \derives & lname & {\rm variable} \\
253 & qvar & \derives & [ mident @.@ ] var & {\rm optionally qualified variable} \\
255 {\rm Name} & lname & \derives & lower \many{namechar} \\
256 & uname & \derives & upper \many{namechar} & \\
257 & pname & \derives & \oneormore{namechar} & \\
258 & namechar & \derives & lower \orderives\ upper \orderives\ digit \\
259 & lower & \derives & @a@ \orderives\ @b@ \orderives\ \ldots \orderives\ @z@ \orderives\ @_@ \\
260 & upper & \derives & @A@ \orderives\ @B@ \orderives\ \ldots \orderives\ @Z@ \\
261 & digit & \derives & @0@ \orderives\ @1@ \orderives\ \ldots \orderives\ @9@ \\
265 \section{Informal Semantics}
268 At the term level, Core resembles a explicitly-typed polymorphic lambda calculus (F$_\omega$), with the addition
269 of local @let@ bindings, algebraic type definitions, constructors, and @case@ expressions,
270 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}
272 In this section we concentrate on the less obvious points about Core.
274 \subsection{Program Organization and Modules}
277 Core programs are organized into {\em modules}, corresponding directly to source-level Haskell modules.
278 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.}
280 Each module may contain the following kinds of top-level declarations:
282 \item Algebraic data type declarations, each defining a type constructor and one or more data constructors;
283 \item Newtype declarations, corresponding to Haskell @newtype@ declarations, each defining a type constructor and a coercion name; and
284 \item Value declarations, defining the types and values of top-level variables.
287 No type constructor, data constructor, or top-level value may be declared more than once within a given module.
288 All the type declarations are (potentially) mutually recursive. Value declarations must be
289 in dependency order, with explicit grouping of potentially mutually recursive declarations.
292 Identifiers defined in top-level declarations may be {\it external} or {\it internal}.
293 External identifiers can be referenced from any other module in
294 the program, using conventional dot notation (e.g., @base:GHC.Base.Bool@, @base:GHC.Base.True@).
295 Internal identifiers are visible only within the defining module.
296 All type and data constructors are external, and are always defined and referenced using
297 fully qualified names (with dots).
299 A top-level value is external if it is defined and referenced
300 using a fully qualified name with a dot (e.g., @main:MyModule.foo = ...@); otherwise, it is internal
302 Note that Core's notion of an external identifier does not necessarily coincide with that of ``exported''
303 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.
305 Core modules have no explicit import or export lists.
306 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.
308 There is also an implicitly-defined module @ghc-prim:GHC.Prim@, which exports the ``built-in'' types and values
309 that must be provided by any implementation of Core (including GHC). Details of this
310 module are in Section~\ref{sec:prims}.
312 A Core {\em program} is a collection of distinctly-named modules that includes a module
313 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@.)
315 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
316 the standard library modules.
318 \subsection{Namespaces}
319 \label{sec:namespaces}
321 There are five distinct namespaces:
323 \item module identifiers (@mident@),
324 \item type constructors (@tycon@),
325 \item type variables (@tyvar@),
326 \item data constructors (@dcon@),
327 \item term variables (@var@).
330 Spaces (1), (2+3), and (4+5) can be distinguished from each other by context.
331 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.
333 Primitive types and operators are not syntactically distinguished.
335 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.
337 A given variable (type or term) may have multiple definitions within a module.
338 However, definitions of term variables never ``shadow'' one another: the scope of the definition
339 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
340 to this rule is that (necessarily closed) types labelling @%external@ expressions may contain
341 @tyvar@ bindings that shadow outer bindings.
343 Core generated by GHC makes heavy use of encoded names, in which the characters @Z@ and @z@ are
344 used to introduce escape sequences for non-alphabetic characters such as dollar sign @$@ (@zd@),
345 hash @#@ (@zh@), plus @+@ (@zp@), etc. This is the same encoding used in @.hi@ files and in the
346 back-end of GHC itself, except that we sometimes change an initial @z@ to @Z@, or vice-versa,
347 in order to maintain case distinctions.
349 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.
350 \subsection{Types and Kinds}
351 \label{sec:typesandkinds}
353 In Core, all type abstractions and applications are explicit. This make it easy to
354 typecheck any (closed) fragment of Core code. An full executable typechecker is available separately.
356 \subsubsection{Types}
357 Types are described by type expressions, which
358 are built from named type constructors and type variables
359 using type application and universal quantification.
360 Each type constructor has a fixed arity $\geq 0$.
361 Because it is so widely used, there is
362 special infix syntax for the fully-applied function type constructor (@->@).
363 (The prefix identifier for this constructor is @ghc-prim:GHC.Prim.ZLzmzgZR@; this should
364 only appear in unapplied or partially applied form.)
366 There are also a number of other primitive type constructors (e.g., @Intzh@) that
367 are predefined in the @GHC.Prim@ module, but have no special syntax.
368 @%data@ and @%newtype@ declarations introduce additional type constructors, as described below.
369 Type constructors are distinguished solely by name.
371 \subsubsection{Coercions}
373 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.
375 \subsubsection{Kinds}
376 As described in the Haskell definition, it is necessary to distinguish
377 well-formed type-expressions by classifying them into different {\it kinds}~\citep[p. 41]{haskell98}.
378 In particular, Core explicitly records the kind of every bound type variable.
380 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.
381 \subsubsection{Lifted and Unlifted Types}
382 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.
384 Currently, all the primitive types are unlifted
385 (including a few boxed primitive types such as @ByteArrayzh@).
386 Peyton Jones and Launchbury~[\citeyear{pj:unboxed}] described the ideas behind unboxed and unlifted types.
388 \subsubsection{Type Constructors; Base Kinds and Higher Kinds}
389 Every type constructor has a kind, depending on its arity and whether it or its arguments are lifted.
391 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:
392 @*@ 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
393 appears in Core type declarations generated from user code; the other two are needed to describe
394 certain types in primitive (or otherwise specially-generated) code (which, after optimization, could potentially appear anywhere).
396 In particular, no top-level identifier (except in @ghc-prim:GHC.Prim@) has a type of kind @#@ or @?@.
398 Nullary type constructors have base kinds: for example, the type @Int@ has kind @*@, and @Int#@ has kind @#@.
400 Non-nullary type constructors have higher kinds: kinds that have the form $k_1 @->@ k_2$,
401 where $k_1$ and $k_2$ are kinds. For example, the function type constructor
402 @->@ has kind @* -> (* -> *)@. Since Haskell allows abstracting over type
403 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.
405 \subsubsection{Type Synonyms and Type Equivalence}
406 There is no mechanism for defining type synonyms (corresponding to
407 Haskell @type@ declarations).
409 Type equivalence is just syntactic equivalence on type expressions
410 (of base kinds) modulo:
413 \item alpha-renaming of variables bound in @%forall@ types;
414 \item the identity $a$ @->@ $b$ $\equiv$ @ghc-prim:GHC.Prim.ZLzmzgZR@ $a$ $b$
417 \subsection{Algebraic data types}
419 Each @data@ declaration introduces a new type constructor and a set of one or
420 more data constructors, normally corresponding directly to a source Haskell @data@ declaration.
421 For example, the source declaration
424 Fork (Bintree a) (Bintree a)
427 might induce the following Core declaration
430 Fork (Bintree a) (Bintree a);
433 which introduces the unary type constructor @Bintree@ of kind @*->*@ and two data constructors with types
435 Fork :: %forall a . Bintree a -> Bintree a -> Bintree a
436 Leaf :: %forall a . a -> Bintree a
438 We define the {\it arity} of each data constructor to be the number of value arguments it takes;
439 e.g. @Fork@ has arity 2 and @Leaf@ has arity 1.
441 For a less conventional example illustrating the possibility of higher-order kinds, the Haskell source declaration
443 data A f a = MkA (f a)
445 might induce the Core declaration
447 %data A (f::*->*) a = { MkA (f a) }
449 which introduces the constructor
451 MkA :: %forall (f::*->*) a . (f a) -> (A f) a
454 GHC (like some other Haskell implementations) supports an extension to Haskell98
455 for existential types such as
457 data T = forall a . MkT a (a -> Bool)
459 This is represented by the Core declaration
461 %data T = {MkT @a a (a -> Bool)}
463 which introduces the nullary type constructor @T@ and the data constructor
465 MkT :: %forall a . a -> (a -> Bool) -> T
467 In general, existentially quantified variables appear as extra univerally
468 quantified variables in the data contructor types.
469 An example of how to construct and deconstruct values of type @T@ is shown in
470 Section~\ref{sec:exprs}.
472 \subsection{Newtypes}
475 Each Core @%newtype@ declaration introduces a new type constructor and an associated
476 representation type, corresponding to a source Haskell @newtype@
477 declaration. However, unlike in source Haskell, a @%newtype@ declaration does not introduce any data constructors.
479 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.
481 For example, the Haskell fragment
488 might induce the Core fragment
490 %newtype U ZCCoU = Bool;
491 u :: U = %cast (True)
493 v :: Bool = not (%cast (u) ZCCoU);
496 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}.
498 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.
500 Also notice that unlike in a previous draft version of External Core, there is no need to handle recursive newtypes specially.
501 \subsection{Expression Forms}
504 Variables and data constructors are straightforward.
506 Literal ({\it lit}) expressions consist of a literal value, in one of four different formats,
507 and a (primitive) type annotation. Only certain combinations of format and type
508 are permitted; see Section~\ref{sec:prims}. The character and string formats can describe only
509 8-bit ASCII characters.
511 Moreover, because the operational semantics for Core interprets strings as C-style null-terminated
512 strings, strings should not contain embedded nulls.
514 In Core, value applications, type applications, value abstractions, and type abstractions are all explicit. To tell them apart, type arguments in applications
515 and formal type arguments in abstractions are preceded by an \at\ symbol. (In abstractions,
516 the \at\ plays essentially the same role as the more usual $\Lambda$ symbol.)
517 For example, the Haskell source declaration
521 might induce the Core declaration
523 f :: %forall a . a -> BinTree (BinTree a) =
524 \ @a (x::a) -> Leaf @(Bintree a) (Leaf @a x)
527 Value applications may be of user-defined functions, data constructors, or primitives.
528 None of these sorts of applications are necessarily saturated.
530 Note that the arguments of type applications are not always of kind @*@. For example,
531 given our previous definition of type @A@:
533 data A f a = MkA (f a)
541 (MkA @Bintree @Bool) (Leaf @Bool True)
544 Local bindings, of a single variable or of a set of mutually recursive variables,
545 are represented by @%let@ expressions in the usual way.
547 By far the most complicated expression form is @%case@.
548 @%case@ expressions are permitted over values of any type, although they will normally
549 be algebraic or primitive types (with literal values).
550 Evaluating a @%case@ forces the evaluation of the expression being
551 tested (the ``scrutinee''). The value of the scrutinee is bound to the variable
552 following the @%of@ keyword, which is in scope in all alternatives;
553 this is useful when the scrutinee is a non-atomic
554 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).
556 In an algebraic @%case@, all the case alternatives must be
557 labeled with distinct data constructors from the algebraic type, followed by
558 any existential type variable bindings (see below), and
559 typed term variable bindings corresponding to the data constructor's
560 arguments. The number of variables must match the data constructor's arity.
562 For example, the following Haskell source expression
566 t@(Leaf v) -> Fork t t
568 might induce the Core expression
570 %case ((Bintree a)) g x %of (t::Bintree a)
571 Fork (l::Bintree a) (r::Bintree a) ->
577 When performing a @%case@ over a value of an existentially-quantified algebraic
578 type, the alternative must include extra local type bindings
579 for the existentially-quantified variables. For example, given
581 data T = forall a . MkT a (a -> Bool)
591 MkT @b (w::b) (g::b->Bool) -> g w
594 In a @%case@ over literal alternatives,
595 all the case alternatives must be distinct literals of the same primitive type.
597 The list of alternatives may begin with a
598 default alternative labeled with an underscore (@%_@), whose right-hand side will be evaluated if
599 none of the other alternatives match. The default is optional except for in a case
600 over a primitive type, or when there are no other alternatives.
601 If the case is over neither an
602 algebraic type nor a primitive type, then the list of alternatives must contain a default alternative and nothing else.
603 For algebraic cases, the set of alternatives
604 need not be exhaustive, even if no default is given; if alternatives are missing,
605 this implies that GHC has deduced that they cannot occur.
607 @%cast@ is used to manipulate newtypes, as described in Section~\ref{sec:newtypes}. The @%cast@ expression takes an expression and a coercion:
608 syntactically, the coercion is an arbitrary type, but it must have an
609 equality kind. In an expression @(cast e co)@, if @e :: T@ and @co@
610 has kind @T :=: U@, then the overall expression has type
611 @U@~\citep{ghc-fc-commentary}. Here, @co@ must be a coercion whose left-hand side is @T@.
614 that unlike the @%coerce@ expression that existed in previous versions
615 of Core, this means that @%cast@ is (almost) type-safe: the coercion
616 argument provides evidence that can be verified by a
617 typechecker. There are still unsafe @%cast@s, corresponding to the
618 unsafe @%coerce@ construct that existed in old versions of Core,
619 because there is a primitive unsafe coercion type that
620 can be used to cast arbitrary types to each other. GHC uses this for
621 such purposes as coercing the return type of a function (such as
622 error) which is guaranteed to never return:
630 %cast (error @ Bool (ZMZN @ Char))
631 (%unsafe Bool Integer);
633 @%cast@ has no operational meaning and is only used in typechecking.
637 A @%note@ expression carries arbitrary internal information that GHC finds interesting. The information is encoded as a string. Expression notes currently generated by GHC
638 include the inlining pragma (@InlineMe@) and cost-center labels for profiling.
640 A @%external@ expression denotes an external identifier, which has
641 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.
643 The present syntax for externals is sufficient for describing C functions and labels.
644 Interfacing to other languages may require additional information or a different interpretation
648 \subsection{Expression Evaluation}
649 \label{sec:evaluation}
651 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
652 the resulting type-free program are just the conventional ones for a call-by-name
653 language, in which expressions are only evaluated on demand.
654 But Core is intended to be a call-by-{\it{need}} language, in which
655 expressions are only evaluated {\it once}. To express the sharing behavior
656 of call-by-need, we give an operational model in the style of Launchbury~\citep{launchbury93natural}.
658 This section describes the model informally; a more formal semantics is
659 separately available as an executable interpreter.
661 To simplify the semantics, we consider only ``well-behaved'' Core programs in which
662 constructor and primitive applications are fully saturated, and in which
663 non-trivial expresssions of unlifted kind (@#@) appear only as scrutinees
664 in @%case@ expressions. Any program can easily be put into this form;
665 a separately available preprocessor illustrates how.
666 In the remainder of this section, we use ``Core'' to mean ``well-behaved'' Core.
668 Evaluating a Core expression means reducing it to {\it weak-head normal form (WHNF)},
669 i.e., a primitive value, lambda abstraction, or fully-applied data constructor. Evaluating a program means evaluating the expression @main:ZCMain.main@.
671 To make sure that expression evaluation is shared, we
672 make use of a {\it heap}, which contains {\it heap entries}. A heap entry can be:
674 \item A {\em thunk}, representing an unevaluated expression, also known as a {\em suspension}.
676 \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.
679 {\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.
681 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:
683 \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)).
685 \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.
687 \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.
690 As computation proceeds, copies of the heap pointer for a given thunk propagate through the executing program.
691 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
692 only in the context of
694 \item evaluating the operator expression of an application;
696 \item evaluating the scrutinee of a @case@ expression; or
698 \item evaluating an argument to a primitive or external function application
701 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.
703 With the exception of functions, arrays, and mutable variables, we intend that values of all primitive types
704 should be held {\it unboxed}: they should not be heap-allocated. This does not violate call-by-need semantics: all
705 primitive types are {\it unlifted}, which means that values of those types must be evaluated strictly. Unboxed tuple types are not heap-allocated either.
707 Certain primitives and @%external@ functions cause side-effects to state threads or to the real world.
708 Where the ordering of these side-effects matters, Core already forces this order with data dependencies on the pseudo-values representing the threads.
710 An implementation must specially support the @raisezh@ and @handlezh@ primitives: for example, by using a handler stack.
711 Again, real-world threading guarantees that they will execute in the correct order.
713 \section{Primitive Module}
716 The semantics of External Core rely on the contents and informal semantics of the primitive module @ghc-prim:GHC.Prim@.
717 Nearly all the primitives are required in order to cover GHC's implementation of the Haskell98
718 standard prelude; the only operators that can be completely omitted are those supporting the byte-code interpreter,
719 parallelism, and foreign objects. Some of the concurrency primitives are needed, but can be
720 given degenerate implementations if it desired to target a purely sequential backend (see Section~\ref{sec:sequential}).
722 In addition to these primitives, a large number of C library functions are required to implement
723 the full standard Prelude, particularly to handle I/O and arithmetic on less usual types.
725 For a full listing of the names and types of the primitive operators, see the GHC library documentation~\citep{ghcprim}.
728 \subsection{Non-concurrent Back End}
729 \label{sec:sequential}
731 The Haskell98 standard prelude doesn't include any concurrency support, but GHC's
732 implementation of it relies on the existence of some concurrency primitives. However,
733 it never actually forks multiple threads. Hence, the concurrency primitives can
734 be given degenerate implementations that will work in a non-concurrent setting,
737 \item @ThreadIdzh@ can be represented
738 by a singleton type, whose (unique) value is returned by @myThreadIdzh@.
740 \item @forkzh@ can just die with an ``unimplemented'' message.
742 \item @killThreadzh@ and @yieldzh@ can also just die ``unimplemented'' since
743 in a one-thread world, the only thread a thread can kill is itself, and
744 if a thread yields the program hangs.
746 \item @MVarzh a@ can be represented by @MutVarzh (Maybe a)@;
747 where a concurrent implementation would block, the sequential implementation can
748 just die with a suitable message (since no other thread exists to unblock it).
750 \item @waitReadzh@ and @waitWritezh@ can be implemented using a @select@ with no timeout.
753 \subsection{Literals}
755 Only the following combination of literal forms and types are permitted:
757 \begin{tabular}{|l|l|l|}
759 Literal form & Type & Description \\
761 integer & @Intzh@ & Int \\
762 % & @Int32zh@ & Int32 \\
763 % & @Int64zh@ & Int64 \\
765 % & @Word32zh@ & Word32 \\
766 % & @Word64zh@ & Word64 \\
767 & @Addrzh@ & Address \\
768 & @Charzh@ & Unicode character code \\
769 rational & @Floatzh@ & Float \\
770 & @Doublezh@ & Double \\
771 character & @Charzh@ & Unicode character specified by ASCII character\\
772 string & @Addrzh@ & Address of specified C-format string \\
777 \bibliographystyle{abbrvnat}