src/Doc/Codegen/Adaptation.thy
author haftmann
Sat Jan 25 23:50:49 2014 +0100 (2014-01-25)
changeset 55147 bce3dbc11f95
parent 52742 e7296939fec2
child 59104 a14475f044b2
permissions -rw-r--r--
prefer explicit code symbol type over ad-hoc name mangling
haftmann@31050
     1
theory Adaptation
haftmann@28213
     2
imports Setup
haftmann@28213
     3
begin
haftmann@28213
     4
haftmann@55147
     5
setup %invisible {* Code_Target.extend_target ("\<SML>", ("SML", I))
haftmann@55147
     6
  #> Code_Target.extend_target ("\<SMLdummy>", ("Haskell", I)) *}
haftmann@28561
     7
haftmann@31050
     8
section {* Adaptation to target languages \label{sec:adaptation} *}
haftmann@28419
     9
haftmann@28561
    10
subsection {* Adapting code generation *}
haftmann@28561
    11
haftmann@28561
    12
text {*
haftmann@28561
    13
  The aspects of code generation introduced so far have two aspects
haftmann@28561
    14
  in common:
haftmann@28561
    15
haftmann@28561
    16
  \begin{itemize}
haftmann@38450
    17
haftmann@38450
    18
    \item They act uniformly, without reference to a specific target
haftmann@38450
    19
       language.
haftmann@38450
    20
haftmann@28561
    21
    \item They are \emph{safe} in the sense that as long as you trust
haftmann@28561
    22
       the code generator meta theory and implementation, you cannot
haftmann@38450
    23
       produce programs that yield results which are not derivable in
haftmann@38450
    24
       the logic.
haftmann@38450
    25
haftmann@28561
    26
  \end{itemize}
haftmann@28561
    27
haftmann@38450
    28
  \noindent In this section we will introduce means to \emph{adapt}
haftmann@38450
    29
  the serialiser to a specific target language, i.e.~to print program
haftmann@38450
    30
  fragments in a way which accommodates \qt{already existing}
haftmann@38450
    31
  ingredients of a target language environment, for three reasons:
haftmann@28561
    32
haftmann@28561
    33
  \begin{itemize}
haftmann@28593
    34
    \item improving readability and aesthetics of generated code
haftmann@28561
    35
    \item gaining efficiency
haftmann@28561
    36
    \item interface with language parts which have no direct counterpart
haftmann@28561
    37
      in @{text "HOL"} (say, imperative data structures)
haftmann@28561
    38
  \end{itemize}
haftmann@28561
    39
haftmann@28561
    40
  \noindent Generally, you should avoid using those features yourself
haftmann@28561
    41
  \emph{at any cost}:
haftmann@28561
    42
haftmann@28561
    43
  \begin{itemize}
haftmann@38450
    44
haftmann@38450
    45
    \item The safe configuration methods act uniformly on every target
haftmann@38450
    46
      language, whereas for adaptation you have to treat each target
haftmann@38450
    47
      language separately.
haftmann@38450
    48
haftmann@38450
    49
    \item Application is extremely tedious since there is no
haftmann@38450
    50
      abstraction which would allow for a static check, making it easy
haftmann@38450
    51
      to produce garbage.
haftmann@38450
    52
paulson@34155
    53
    \item Subtle errors can be introduced unconsciously.
haftmann@38450
    54
haftmann@28561
    55
  \end{itemize}
haftmann@28561
    56
haftmann@38450
    57
  \noindent However, even if you ought refrain from setting up
haftmann@51162
    58
  adaptation yourself, already @{text "HOL"} comes with some
haftmann@38450
    59
  reasonable default adaptations (say, using target language list
haftmann@38450
    60
  syntax).  There also some common adaptation cases which you can
haftmann@38450
    61
  setup by importing particular library theories.  In order to
haftmann@38450
    62
  understand these, we provide some clues here; these however are not
haftmann@38450
    63
  supposed to replace a careful study of the sources.
haftmann@28561
    64
*}
haftmann@28561
    65
haftmann@38450
    66
haftmann@31050
    67
subsection {* The adaptation principle *}
haftmann@28561
    68
haftmann@28561
    69
text {*
haftmann@38450
    70
  Figure \ref{fig:adaptation} illustrates what \qt{adaptation} is
haftmann@38450
    71
  conceptually supposed to be:
haftmann@28601
    72
haftmann@28601
    73
  \begin{figure}[here]
wenzelm@52742
    74
    \begin{tikzpicture}[scale = 0.5]
wenzelm@52742
    75
      \tikzstyle water=[color = blue, thick]
wenzelm@52742
    76
      \tikzstyle ice=[color = black, very thick, cap = round, join = round, fill = white]
wenzelm@52742
    77
      \tikzstyle process=[color = green, semithick, ->]
wenzelm@52742
    78
      \tikzstyle adaptation=[color = red, semithick, ->]
wenzelm@52742
    79
      \tikzstyle target=[color = black]
wenzelm@52742
    80
      \foreach \x in {0, ..., 24}
wenzelm@52742
    81
        \draw[style=water] (\x, 0.25) sin + (0.25, 0.25) cos + (0.25, -0.25) sin
wenzelm@52742
    82
          + (0.25, -0.25) cos + (0.25, 0.25);
wenzelm@52742
    83
      \draw[style=ice] (1, 0) --
wenzelm@52742
    84
        (3, 6) node[above, fill=white] {logic} -- (5, 0) -- cycle;
wenzelm@52742
    85
      \draw[style=ice] (9, 0) --
wenzelm@52742
    86
        (11, 6) node[above, fill=white] {intermediate language} -- (13, 0) -- cycle;
wenzelm@52742
    87
      \draw[style=ice] (15, -6) --
wenzelm@52742
    88
        (19, 6) node[above, fill=white] {target language} -- (23, -6) -- cycle;
wenzelm@52742
    89
      \draw[style=process]
wenzelm@52742
    90
        (3.5, 3) .. controls (7, 5) .. node[fill=white] {translation} (10.5, 3);
wenzelm@52742
    91
      \draw[style=process]
wenzelm@52742
    92
        (11.5, 3) .. controls (15, 5) .. node[fill=white] (serialisation) {serialisation} (18.5, 3);
wenzelm@52742
    93
      \node (adaptation) at (11, -2) [style=adaptation] {adaptation};
wenzelm@52742
    94
      \node at (19, 3) [rotate=90] {generated};
wenzelm@52742
    95
      \node at (19.5, -5) {language};
wenzelm@52742
    96
      \node at (19.5, -3) {library};
wenzelm@52742
    97
      \node (includes) at (19.5, -1) {includes};
wenzelm@52742
    98
      \node (reserved) at (16.5, -3) [rotate=72] {reserved}; % proper 71.57
wenzelm@52742
    99
      \draw[style=process]
wenzelm@52742
   100
        (includes) -- (serialisation);
wenzelm@52742
   101
      \draw[style=process]
wenzelm@52742
   102
        (reserved) -- (serialisation);
wenzelm@52742
   103
      \draw[style=adaptation]
wenzelm@52742
   104
        (adaptation) -- (serialisation);
wenzelm@52742
   105
      \draw[style=adaptation]
wenzelm@52742
   106
        (adaptation) -- (includes);
wenzelm@52742
   107
      \draw[style=adaptation]
wenzelm@52742
   108
        (adaptation) -- (reserved);
wenzelm@52742
   109
    \end{tikzpicture}
haftmann@31050
   110
    \caption{The adaptation principle}
haftmann@31050
   111
    \label{fig:adaptation}
haftmann@28601
   112
  \end{figure}
haftmann@28601
   113
haftmann@28601
   114
  \noindent In the tame view, code generation acts as broker between
haftmann@38450
   115
  @{text logic}, @{text "intermediate language"} and @{text "target
haftmann@38450
   116
  language"} by means of @{text translation} and @{text
haftmann@38450
   117
  serialisation}; for the latter, the serialiser has to observe the
haftmann@38450
   118
  structure of the @{text language} itself plus some @{text reserved}
haftmann@38450
   119
  keywords which have to be avoided for generated code.  However, if
haftmann@38450
   120
  you consider @{text adaptation} mechanisms, the code generated by
haftmann@38450
   121
  the serializer is just the tip of the iceberg:
haftmann@28601
   122
haftmann@28601
   123
  \begin{itemize}
haftmann@38450
   124
haftmann@28635
   125
    \item @{text serialisation} can be \emph{parametrised} such that
haftmann@28635
   126
      logical entities are mapped to target-specific ones
haftmann@38450
   127
      (e.g. target-specific list syntax, see also
haftmann@38450
   128
      \secref{sec:adaptation_mechanisms})
haftmann@38450
   129
haftmann@28635
   130
    \item Such parametrisations can involve references to a
haftmann@38450
   131
      target-specific standard @{text library} (e.g. using the @{text
haftmann@38450
   132
      Haskell} @{verbatim Maybe} type instead of the @{text HOL}
haftmann@38450
   133
      @{type "option"} type); if such are used, the corresponding
haftmann@38450
   134
      identifiers (in our example, @{verbatim Maybe}, @{verbatim
haftmann@38450
   135
      Nothing} and @{verbatim Just}) also have to be considered @{text
haftmann@38450
   136
      reserved}.
haftmann@38450
   137
haftmann@28635
   138
    \item Even more, the user can enrich the library of the
haftmann@38450
   139
      target-language by providing code snippets (\qt{@{text
haftmann@38450
   140
      "includes"}}) which are prepended to any generated code (see
haftmann@38450
   141
      \secref{sec:include}); this typically also involves further
haftmann@38450
   142
      @{text reserved} identifiers.
haftmann@38450
   143
haftmann@28601
   144
  \end{itemize}
haftmann@28635
   145
haftmann@38450
   146
  \noindent As figure \ref{fig:adaptation} illustrates, all these
haftmann@38450
   147
  adaptation mechanisms have to act consistently; it is at the
haftmann@38450
   148
  discretion of the user to take care for this.
haftmann@28561
   149
*}
haftmann@28561
   150
haftmann@31050
   151
subsection {* Common adaptation patterns *}
haftmann@28419
   152
haftmann@28419
   153
text {*
haftmann@28428
   154
  The @{theory HOL} @{theory Main} theory already provides a code
haftmann@38450
   155
  generator setup which should be suitable for most applications.
haftmann@38450
   156
  Common extensions and modifications are available by certain
wenzelm@52665
   157
  theories in @{file "~~/src/HOL/Library"}; beside being useful in
haftmann@38450
   158
  applications, they may serve as a tutorial for customising the code
haftmann@38450
   159
  generator setup (see below \secref{sec:adaptation_mechanisms}).
haftmann@28419
   160
haftmann@28419
   161
  \begin{description}
haftmann@28419
   162
haftmann@51143
   163
    \item[@{theory "Code_Numeral"}] provides additional numeric
haftmann@51143
   164
       types @{typ integer} and @{typ natural} isomorphic to types
haftmann@51143
   165
       @{typ int} and @{typ nat} respectively.  Type @{typ integer}
haftmann@51143
   166
       is mapped to target-language built-in integers; @{typ natural}
haftmann@51143
   167
       is implemented as abstract type over @{typ integer}.
haftmann@51143
   168
       Useful for code setups which involve e.g.~indexing
haftmann@51143
   169
       of target-language arrays.  Part of @{text "HOL-Main"}.
haftmann@51143
   170
haftmann@51143
   171
    \item[@{text "Code_Target_Int"}] implements type @{typ int}
haftmann@51143
   172
       by @{typ integer} and thus by target-language built-in integers.
haftmann@38450
   173
haftmann@51171
   174
    \item[@{text "Code_Binary_Nat"}] implements type
haftmann@51143
   175
       @{typ nat} using a binary rather than a linear representation,
haftmann@51143
   176
       which yields a considerable speedup for computations.
haftmann@51143
   177
       Pattern matching with @{term "0\<Colon>nat"} / @{const "Suc"} is eliminated
haftmann@51171
   178
       by a preprocessor.\label{abstract_nat}
haftmann@51143
   179
haftmann@51171
   180
    \item[@{text "Code_Target_Nat"}] implements type @{typ nat}
haftmann@51171
   181
       by @{typ integer} and thus by target-language built-in integers.
haftmann@51171
   182
       Pattern matching with @{term "0\<Colon>nat"} / @{const "Suc"} is eliminated
haftmann@51171
   183
       by a preprocessor.
haftmann@51143
   184
haftmann@51162
   185
    \item[@{text "Code_Target_Numeral"}] is a convenience theory
haftmann@51143
   186
       containing both @{text "Code_Target_Nat"} and
haftmann@51143
   187
       @{text "Code_Target_Int"}.
haftmann@38450
   188
haftmann@51143
   189
    \item[@{text "Code_Char"}] represents @{text HOL} characters by
haftmann@51143
   190
       character literals in target languages.
haftmann@38450
   191
haftmann@38450
   192
    \item[@{theory "String"}] provides an additional datatype @{typ
haftmann@38450
   193
       String.literal} which is isomorphic to strings; @{typ
haftmann@38450
   194
       String.literal}s are mapped to target-language strings.  Useful
haftmann@38450
   195
       for code setups which involve e.g.~printing (error) messages.
haftmann@46519
   196
       Part of @{text "HOL-Main"}.
haftmann@28419
   197
haftmann@51162
   198
    \item[@{theory "IArray"}] provides a type @{typ "'a iarray"}
haftmann@51162
   199
       isomorphic to lists but implemented by (effectively immutable)
haftmann@51162
   200
       arrays \emph{in SML only}.
haftmann@28419
   201
haftmann@51162
   202
  \end{description}
haftmann@28419
   203
*}
haftmann@28419
   204
haftmann@28419
   205
haftmann@31050
   206
subsection {* Parametrising serialisation \label{sec:adaptation_mechanisms} *}
haftmann@28419
   207
haftmann@28419
   208
text {*
haftmann@38450
   209
  Consider the following function and its corresponding SML code:
haftmann@28419
   210
*}
haftmann@28419
   211
haftmann@28564
   212
primrec %quote in_interval :: "nat \<times> nat \<Rightarrow> nat \<Rightarrow> bool" where
haftmann@28419
   213
  "in_interval (k, l) n \<longleftrightarrow> k \<le> n \<and> n \<le> l"
haftmann@28447
   214
(*<*)
haftmann@52378
   215
code_printing %invisible
haftmann@52378
   216
  type_constructor bool \<rightharpoonup> (SML)
haftmann@52378
   217
| constant True \<rightharpoonup> (SML)
haftmann@52378
   218
| constant False \<rightharpoonup> (SML)
haftmann@52378
   219
| constant HOL.conj \<rightharpoonup> (SML)
haftmann@52378
   220
| constant Not \<rightharpoonup> (SML)
haftmann@28447
   221
(*>*)
haftmann@39745
   222
text %quotetypewriter {*
haftmann@39683
   223
  @{code_stmts in_interval (SML)}
haftmann@39664
   224
*}
haftmann@28419
   225
haftmann@28419
   226
text {*
haftmann@38450
   227
  \noindent Though this is correct code, it is a little bit
haftmann@38450
   228
  unsatisfactory: boolean values and operators are materialised as
haftmann@38450
   229
  distinguished entities with have nothing to do with the SML-built-in
haftmann@38450
   230
  notion of \qt{bool}.  This results in less readable code;
haftmann@38450
   231
  additionally, eager evaluation may cause programs to loop or break
haftmann@38450
   232
  which would perfectly terminate when the existing SML @{verbatim
haftmann@38450
   233
  "bool"} would be used.  To map the HOL @{typ bool} on SML @{verbatim
haftmann@38450
   234
  "bool"}, we may use \qn{custom serialisations}:
haftmann@28419
   235
*}
haftmann@28419
   236
haftmann@52378
   237
code_printing %quotett
haftmann@52378
   238
  type_constructor bool \<rightharpoonup> (SML) "bool"
haftmann@52378
   239
| constant True \<rightharpoonup> (SML) "true"
haftmann@52378
   240
| constant False \<rightharpoonup> (SML) "false"
haftmann@52378
   241
| constant HOL.conj \<rightharpoonup> (SML) "_ andalso _"
haftmann@28213
   242
haftmann@28419
   243
text {*
haftmann@52378
   244
  \noindent The @{command_def code_printing} command takes a series
haftmann@52378
   245
  of symbols (contants, type constructor, \ldots)
haftmann@52378
   246
  together with target-specific custom serialisations.  Each
haftmann@38450
   247
  custom serialisation starts with a target language identifier
haftmann@38450
   248
  followed by an expression, which during code serialisation is
haftmann@52378
   249
  inserted whenever the type constructor would occur.  Each
haftmann@38450
   250
  ``@{verbatim "_"}'' in a serialisation expression is treated as a
haftmann@52378
   251
  placeholder for the constant's or the type constructor's arguments.
haftmann@28419
   252
*}
haftmann@28419
   253
haftmann@39745
   254
text %quotetypewriter {*
haftmann@39683
   255
  @{code_stmts in_interval (SML)}
haftmann@39664
   256
*}
haftmann@28419
   257
haftmann@28419
   258
text {*
haftmann@38450
   259
  \noindent This still is not perfect: the parentheses around the
haftmann@38450
   260
  \qt{andalso} expression are superfluous.  Though the serialiser by
haftmann@38450
   261
  no means attempts to imitate the rich Isabelle syntax framework, it
haftmann@38450
   262
  provides some common idioms, notably associative infixes with
haftmann@38450
   263
  precedences which may be used here:
haftmann@28419
   264
*}
haftmann@28419
   265
haftmann@52378
   266
code_printing %quotett
haftmann@52378
   267
  constant HOL.conj \<rightharpoonup> (SML) infixl 1 "andalso"
haftmann@28419
   268
haftmann@39745
   269
text %quotetypewriter {*
haftmann@39683
   270
  @{code_stmts in_interval (SML)}
haftmann@39664
   271
*}
haftmann@28419
   272
haftmann@28419
   273
text {*
haftmann@38450
   274
  \noindent The attentive reader may ask how we assert that no
haftmann@38450
   275
  generated code will accidentally overwrite.  For this reason the
haftmann@38450
   276
  serialiser has an internal table of identifiers which have to be
haftmann@38450
   277
  avoided to be used for new declarations.  Initially, this table
haftmann@38450
   278
  typically contains the keywords of the target language.  It can be
haftmann@38450
   279
  extended manually, thus avoiding accidental overwrites, using the
haftmann@38505
   280
  @{command_def "code_reserved"} command:
haftmann@28561
   281
*}
haftmann@28561
   282
haftmann@40351
   283
code_reserved %quote "\<SMLdummy>" bool true false andalso
haftmann@28561
   284
haftmann@28561
   285
text {*
haftmann@28447
   286
  \noindent Next, we try to map HOL pairs to SML pairs, using the
haftmann@28419
   287
  infix ``@{verbatim "*"}'' type constructor and parentheses:
haftmann@28419
   288
*}
haftmann@28447
   289
(*<*)
haftmann@52378
   290
code_printing %invisible
haftmann@52378
   291
  type_constructor prod \<rightharpoonup> (SML)
haftmann@52378
   292
| constant Pair \<rightharpoonup> (SML)
haftmann@28447
   293
(*>*)
haftmann@52378
   294
code_printing %quotett
haftmann@52378
   295
  type_constructor prod \<rightharpoonup> (SML) infix 2 "*"
haftmann@52378
   296
| constant Pair \<rightharpoonup> (SML) "!((_),/ (_))"
haftmann@28419
   297
haftmann@28419
   298
text {*
haftmann@28593
   299
  \noindent The initial bang ``@{verbatim "!"}'' tells the serialiser
haftmann@38450
   300
  never to put parentheses around the whole expression (they are
haftmann@38450
   301
  already present), while the parentheses around argument place
haftmann@38450
   302
  holders tell not to put parentheses around the arguments.  The slash
haftmann@38450
   303
  ``@{verbatim "/"}'' (followed by arbitrary white space) inserts a
haftmann@38450
   304
  space which may be used as a break if necessary during pretty
haftmann@38450
   305
  printing.
haftmann@28419
   306
haftmann@38450
   307
  These examples give a glimpse what mechanisms custom serialisations
haftmann@38450
   308
  provide; however their usage requires careful thinking in order not
haftmann@38450
   309
  to introduce inconsistencies -- or, in other words: custom
haftmann@38450
   310
  serialisations are completely axiomatic.
haftmann@28419
   311
haftmann@39643
   312
  A further noteworthy detail is that any special character in a
haftmann@38450
   313
  custom serialisation may be quoted using ``@{verbatim "'"}''; thus,
haftmann@38450
   314
  in ``@{verbatim "fn '_ => _"}'' the first ``@{verbatim "_"}'' is a
haftmann@38450
   315
  proper underscore while the second ``@{verbatim "_"}'' is a
haftmann@38450
   316
  placeholder.
haftmann@28419
   317
*}
haftmann@28419
   318
haftmann@28419
   319
haftmann@28419
   320
subsection {* @{text Haskell} serialisation *}
haftmann@28419
   321
haftmann@28419
   322
text {*
haftmann@38450
   323
  For convenience, the default @{text HOL} setup for @{text Haskell}
haftmann@39063
   324
  maps the @{class equal} class to its counterpart in @{text Haskell},
haftmann@52378
   325
  giving custom serialisations for the class @{class equal}
haftmann@52378
   326
  and its operation @{const [source] HOL.equal}.
haftmann@28419
   327
*}
haftmann@28419
   328
haftmann@52378
   329
code_printing %quotett
haftmann@52378
   330
  type_class equal \<rightharpoonup> (Haskell) "Eq"
haftmann@52378
   331
| constant HOL.equal \<rightharpoonup> (Haskell) infixl 4 "=="
haftmann@28419
   332
haftmann@28419
   333
text {*
haftmann@38450
   334
  \noindent A problem now occurs whenever a type which is an instance
haftmann@39063
   335
  of @{class equal} in @{text HOL} is mapped on a @{text
haftmann@38450
   336
  Haskell}-built-in type which is also an instance of @{text Haskell}
haftmann@38450
   337
  @{text Eq}:
haftmann@28419
   338
*}
haftmann@28419
   339
haftmann@28564
   340
typedecl %quote bar
haftmann@28419
   341
haftmann@39063
   342
instantiation %quote bar :: equal
haftmann@28419
   343
begin
haftmann@28419
   344
haftmann@39063
   345
definition %quote "HOL.equal (x\<Colon>bar) y \<longleftrightarrow> x = y"
haftmann@28419
   346
haftmann@39063
   347
instance %quote by default (simp add: equal_bar_def)
haftmann@28213
   348
haftmann@30880
   349
end %quote (*<*)
haftmann@30880
   350
haftmann@52378
   351
(*>*) code_printing %quotett
haftmann@52378
   352
  type_constructor bar \<rightharpoonup> (Haskell) "Integer"
haftmann@28419
   353
haftmann@28419
   354
text {*
haftmann@38450
   355
  \noindent The code generator would produce an additional instance,
haftmann@38450
   356
  which of course is rejected by the @{text Haskell} compiler.  To
haftmann@52378
   357
  suppress this additional instance:
haftmann@28419
   358
*}
haftmann@28419
   359
haftmann@52378
   360
code_printing %quotett
haftmann@52378
   361
  class_instance bar :: "HOL.equal" \<rightharpoonup> (Haskell) -
haftmann@28419
   362
haftmann@28561
   363
haftmann@28635
   364
subsection {* Enhancing the target language context \label{sec:include} *}
haftmann@28561
   365
haftmann@28561
   366
text {*
haftmann@28593
   367
  In rare cases it is necessary to \emph{enrich} the context of a
haftmann@52378
   368
  target language; this can also be accomplished using the @{command
haftmann@52378
   369
  "code_printing"} command:
haftmann@28561
   370
*}
haftmann@28561
   371
haftmann@52378
   372
code_printing %quotett
haftmann@52378
   373
  code_module "Errno" \<rightharpoonup> (Haskell) {*errno i = error ("Error number: " ++ show i)*}
haftmann@28561
   374
haftmann@39745
   375
code_reserved %quotett Haskell Errno
haftmann@28561
   376
haftmann@28561
   377
text {*
haftmann@52378
   378
  \noindent Such named modules are then prepended to every
haftmann@38450
   379
  generated code.  Inspect such code in order to find out how
haftmann@52378
   380
  this behaves with respect to a particular
haftmann@38450
   381
  target language.
haftmann@28561
   382
*}
haftmann@28561
   383
haftmann@28419
   384
end
haftmann@46519
   385