ocaml.xml 32.5 KB
Newer Older
1
2
3
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<page name="ocaml">

4
<title>OCamlDuce</title>
5
6
7

<left>
<local-links href="index,documentation"/>
8
9
<p>On this page:</p>
<boxes-toc/>
10
11
12
13
14
</left>

<box>

<p>
15
16
17
18
19
OCamlDuce is a merger between <a
href="http://caml.inria.fr/">OCaml</a> and 
<local href="index">CDuce</local>. It comes as a modified
version of OCaml which integrates CDuce features: expressions, types,
patterns.
20
21
</p>

22
23
24
25
26
27
28
29
<p>
OCamlDuce is distributed under the same licenses as Objective Caml:
the Q Public License version 1.0 for the Compiler, and the LGPL
version 2 for the Library. The extension has been written by Alain
Frisch. Parts of the CDuce implementation, by the same author, have
been reused.
</p>

30
31
32
33
</box>

<box title="Download and installation" link="install">

34
<p>
35
36
37
38
39
The build procedure for OCamlDuce is exactly the same as for OCaml:
<tt>configure, make world, make install</tt>. The names of the tools
are unchanged: <tt>ocaml,ocamlc,ocamlopt</tt>. Currently, OCamlDuce
is based on CVS snapshots of OCaml (between 3.08.3 and the current
<tt>release308</tt> branch) and CDuce (between 0.3.91 and the head).
40
41
42
43
</p>

<ul>
<li><a
44
45
href="http://pauillac.inria.fr/~frisch/ocamlcduce/download/cduce-ocaml-0.0.5.tar.gz">Compiler,
version 0.0.5</a></li>
46
<!--<li><a
47
href="http://pauillac.inria.fr/~frisch/ocamlcduce/download/xml-support-0.0.4.tar.gz">Support
48
library, version 0.0.4</a></li>-->
49
50
51
52
53
54
55
56
57
58
59
</ul>

<p>
GODI users can upgrade an existing installation by adding this
line to their <tt>etc/godi.conf</tt> file:
</p>
<sample>
GODI_BUILD_SITES += http://pauillac.inria.fr/~frisch/ocamlcduce/godi
</sample>
<p>
and by forcing a recompilation of the <tt>godi-ocaml-src</tt>
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
and <tt>godi-ocaml</tt> packages. <!--They should also build
the <tt>godi-xml-support</tt> library.-->
</p>

<!--
<p>
Some simple examples can be found <a -->
<!--href="http://pauillac.inria.fr/~frisch/ocamlcduce/tests/">here</a>.</p>
-->

</box>

<box title="Overview" link="overview">

<p>
75
76
77
In a nutshell, OCamlDuce extends OCaml with a new kind of values
(<em>x-values</em>) to represent XML documents, fragments, tags, Unicode
strings. In order to describe these values, it also extends the type algebra
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
with so-called <em>x-types</em>. The philosophy behind these types is that they
represent <em>set of x-values</em>. They can be very precise: indeed,
each value can be seen as a singleton type (a set with a single
value), and it is possible to form Boolean combinations of x-types
(intersection, union, difference).
</p>

<p>
OCamlDuce's type system can be understood as a refinement of OCaml.
For each sub-expression which is inferred to be of the x-kind (using
OCaml unification based type-system), OCamlDuce will try to infer to
best possible sound x-type. Here, best means smallest for the natural
subtyping relation (set inclusion). The inference algorithm is
actually a data-flow analysis: the x-type will collect all the values
that can be produced by the expression, considering all the possible
data-flow in the program. It it sometimes necessary to provide
explicit type annotations to help the type checker infer this type, in
particular when you define recursive functions or when you use
iterators.
</p>

<p>
Subtyping is implicit for x-types: if an expression is inferred to be
of x-type <code>t</code>, which is a subtype of <code>s</code>, then
it is possible to use this expression in any context which expects a
value of type <code>s</code>.
</p>

</box>

<box title="Getting started" link="start">

<p>
Most of the new language features are enclosed within double curly braces
<code>{{ON}}{{...}}</code>. For instance, the following code sample
defines a value <code>x</code> as an XML element (with tag
<code>a</code>, an attribute <code>href</code>, and a simple
string as content):
</p>

<sample><![CDATA[{{ON}}
# let x = {{ <a href="http://www.cduce.org">['CDuce'] }};;
val x : {{<a href=[ 'http://www.cduce.org' ]>[ 'CDuce' ]}} =
  {{<a href="http://www.cduce.org">[ 'CDuce' ]}}
]]></sample>

<p>
What appears between the curly braces is called an x-expression.
Similarly, there are x-types (as seen above), and also x-patterns.
The delimiters <code>{{ON}}{{...}}</code> are only used
for syntactical reasons, to avoid clashed between OCaml and CDuce
syntaxes and lexical conventions. As a matter of fact,
an OCaml expression need not be a syntactical x-expression
(delimited by double curly braces) to evaluate to an x-value.
For instance, once <code>x</code> has been declared as above,
the expression <code>x</code> evaluates to an x-value.
</p>


<p>
It is possible to use an arbitrary
OCaml expression as part of an x-expression: it must simply be
protected by a new pair of double curly braces. For instance, there is
no <code>if-then-else</code> construction for x-expressions, but you
can write:
</p>

<sample><![CDATA[{{ON}}
# {{ <a href={{if true then {{"a"}} else {{"z"}}}}>[] }};;
- : {{<a href=[ 'a' | 'z' ]>[  ]}} = {{<a href="a">[ ]}}
]]></sample>

<p>
Only the highlighted parts are parsed as x-expressions. The
<code>if-then-else</code> sub-expression is parsed as an OCaml
expression, but its type is an x-type (namely <code>{{ON}}{{[ 'a' |
'z' ]}}</code>).
</p>

</box>

<box title="X-values" link="values">

<p>
X-values are intended to represent XML documents and fragments
thereof: elements, tags, text, sequences. In this section, we
present the x-value algebra, the syntax of the corresponding
x-expression constructors and the associated x-types.
</p>

<p>
There are three kinds of atomic kind of x-values:
</p>
<ul>
<li>Unicode characters;</li>
<li>qualified names;</li>
<li>arbitrarily large integers.</li>
</ul>

<section title="Characters">

<p>
X-characters are different from OCaml characters. They can represent
the range of Unicode codepoints defined in the XML specification.
Character literals are delimited by single quotes. The escape
sequences \n, \r, \t, \b, \', \&quot;, \\ are recognized as usual.  The
numerical escape sequence are written <code>\n;</code> where n is an integer
literal (note the extra semi-colon). The source code is interpreted as
being encoded in iso-8859-1. As a consequence, Unicode characters which are not
part of the Latin1 character set must be introduced with this
numerical escape mechanism. The x-types for x-characters are:
</p>
<ul>
<li>singletons;</li>
<li>intervals, written <code>c -- d</code>, where <code>c</code> and 
<code>d</code> are literals (example: <code>{{ON}}type t = {{ 'a'--'z'
}}</code>);</li>
<li>the type of all x-characters, written <code>Char</code>;</li>
<li>the type of all Latin1 characters, written <code>Latin1Char</code>
(defined as <code>\0; -- \255;</code>).</li>
</ul>

</section>

<section title="Integers">

<p>
X-integers are arbitrarily large. Literals must be written in decimal.
Negative literals must be in parenthesis. E.g.: <code>(-3)</code>.
The x-types for x-integers are:
</p>
<ul>
<li>singletons;</li>
<li>intervals, written <code>i -- j</code>, where <code>i</code> and 
<code>j</code> are literals (example: <code>{{ON}}type t = {{ 10--20
}}</code>); it is possible to replace <code>i</code> or <code>j</code>
with <code>**</code> to define open-ended intervals, e.g.
<code>{{ON}}type pos = {{ 1 -- ** }}</code>;
</li>
<li>the type of all x-integers, written <code>Int</code>;</li>
<li>the type of all the integers which can be represented by a
signed 32 (resp. 64) bit machine word, written <code>Int32</code> (resp.
<code>Int64</code>).</li>
</ul>

</section>

<section title="Qualified names">

<p>
Qualified names are intended to represent XML tag names. Conceptually,
they are made of a namespace URI and a local name. Since URIs tends
to be long, literals are of the form <code>`prefix:local</code>
where <code>local</code> is the local name and <code>prefix</code>
is an <em>namespace prefix</em> bound to some URI (in the scope of the
literal). The local name follows the definitions from
the XML Namespaces specification; a dot character must be protected
by a backslash and non-Latin1 characters are written as character
literals <code>\n;</code>. <a href="#ns">See below</a> for a
explanation on how to bind prefixes to URIs. To refer
to the default namespace (or the absence of namespace if not default
has been defined), the syntax is simply <code>`local</code>.
The x-types for qualified names are:
</p>
<ul>
<li>singletons;</li>
<li>the type of all qualified names, written <code>Atom</code>;</li>
<li>the type of all qualified names from a specified namespace,
written <code>`ns:*</code>.</li>
</ul>
</section>

<section title="Records">

<p>
X-records are mainly used to represent the set of attributes of an XML
element. An x-record is a binding from a finite set of <em>labels</em>
to x-values. Labels follows the same syntax as for qualified names
without the leading backquote. However, if the namespace prefix is not
given, the default namespace does not apply (the namespace URI is
empty). The syntax for record x-expressions is <code> { l1=e1
... ln=en }</code> where the <code>li</code> are labels and the
<code>ei</code> are x-expressions. Fields can also be separated with a
semi-colon. It is legal to omit the expression for a field; the label is then
taken as the content of the field (a value with this name must be
defined in the current scope), e.g.: <code>{{ON}}let x = ... and y = ...
in {{ {x y z=3} }}</code> is equivalent to <code>{{ON}}let x = ... and
y = ... in {{ {x=x y=y z=3} }}</code>. The types for x-records specify
which labels are authorized/mandatory, and what the types of the
corresponding fields are. There are two kind of record x-types:
</p>

<ul>
<li>
Closed record types, which only allow a finite number of fields:
<code>{ l1=t1 ... ln=tn }</code>;
</li>
<li>
Open record types, which allow additional fields (with arbitrary
type):
<code>{ l1=t1 ... ln=tn .. }</code> (the final two colons are
in the syntax).
</li>
</ul>

<p>
In both cases, it is possible to make one of
the fields optional by changing = to =?.
</p>

<p>
The x-type of all x-record is thus <code>{ .. }</code>,
and the x-type of x-records with maybe a field <code>l</code>
of type <code>Int</code> and maybe arbitrary other fields is 
<code>{ l=?Int .. }</code>.
293
294
</p>

295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
</section>

<section title="Sequences">

<p>
X-sequences are finite and ordered collections of x-values.
The syntax for a sequence x-expression in 
<code>[ e1 ... en ]</code> (note that elements are <em>not</em> separated
by semi-colons as in OCaml list). Each item <code>ei</code> 
can either be:
</p>
<ul>
<li>an x-expression;</li>
<li><code>!e</code> where <code>e</code> is an x-expression which
evaluates to a sequence (whose content is inserted in the sequence
which is currently defined); e.g. 
<code>let x = [ 2 3 ] in [ 1 !x 4 ]</code> is equivalent to
<code>[ 1 2 3 4 ]</code>;</li>
<li>a string literal delimited by simple quotes; e.g.
<code>[ 'abc' ]</code> is equivalent to <code>[ 'a' 'b' 'c' ]</code>.</li>
</ul>

<p>
X-types for sequences are of the form <code>[R]</code>
where <code>R</code> is a regular expression over x-types which
describe the possible contents of the sequences. The possible
forms of regular expressions are:
</p>

<ul>
<li><code>t</code> (one single element of x-type <code>t</code>)</li>
<li><code>R*</code> (zero or more repetitions)</li>
<li><code>R+</code> (one or more repetitions)</li>
<li><code>R?</code> (zero or one repetition)</li>
<li><code>R1 R2</code> (sequence)</li>
<li><code>R1|R2</code> (alternation)</li>
<li><code>(R)</code></li>
<li><code>/t</code> (guard: the tail of the sequence must comply with
<code>t</code>).</li>
<li><code>PCDATA</code> (equivalent to Char*).</li>
</ul>

<note>sequence are actually encoded with embedded pairs and a
terminator, and sequences types are encoded with product types and
recursive types. The encoding is available to the programmer
but not described in this manual.
</note>

</section>

<section title="Strings">

<p>
Strings are nothing but sequences of characters. There are two
predefined types <code>String</code> and <code>Latin1</code>
(defined as <code>[ Char* ]</code> and <code>[ Latin1Char* ]</code>).
</p>

<p>
A string literal <code>[ '...' ]</code> can also be written
<code>"..." </code> (without the square brackets). Note that simple
(resp. double) quotes need to be escaped only when the string is
delimited with double (resp. simple) quotes.
</p>

</section>

<section title="XML elements">

<p>
An XML element is a triple of x-values. The syntax for 
the corresponding x-expression constructor is
<code><![CDATA[<(e1) (e2)>e3]]></code>. When <code>e1</code> is a
qualified name literal, it is possible to omit the leading
backquote and the surrounding parentheses. Similarly,
when <code>e2</code> is an x-record literal, it is possible
to omit the curly braces and the parentheses. For instance,
one can simply write <code><![CDATA[<a href="abc">['def']]]></code>
instead of <code><![CDATA[<(`a) ({href="abc"})>['def']]]></code>.
</p>

<p>
XML element x-type are written <code><![CDATA[<(t1) (t2)>t3]]></code>,
and the same simplifications applies. For instance, if
the namespace prefix <code>ns</code> has been defined,
the following is a legal x-type <code><![CDATA[<ns:* ..>[]]]></code>;
it describes XML elements whose tag is in the namespace bound to
<code>ns</code>, with an empty content, and with an arbitrary set of
attributes. An underscore in place of <code>(t1)</code> is
equivalent to <code>(Atom)</code> (any tag).
</p>

</section>

</box>

<box title="X-expressions" link="expr">

<p>
In the previous section, we have seen the syntax for x-values
constructors (constant literals, sequence, record, element constructors).
In this section, we describe the other kinds of x-expressions.
</p>

<section title="Binary infix operators">

401
<p>
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
The arithmetic operators on integers follow the usual precedence.
They are written <code>+,*,-,div,mod</code> (they are all infix).
</p>

<p>
Record concatenation: <code>e1 ++ e2</code>. The x-expressions
<code>e1</code> and <code>e2</code> must evaluate to x-records.
The result is obtained by concatening them. If a field with the same
label is present in both records, the right-most one is selected.
</p>

<p>
Sequence concatenation: <code>e1 @ e2</code>, equivalent
to <code>[!e1 !e2]</code>.
</p>

</section>

<section title="Projections, filtering">

<p>
If the x-expression <code>e</code> evaluates to a record or an XML
element, the construction <code>e.l</code> will extract the value of
field or attribute <code>l</code>. Similarly, the construction
<code>e.?l</code> will extract the value of field or attribute
<code>l</code> if present, and return the empty sequence
<code>[]</code> otherwise.
</p>

<p>
If the x-expression <code>e</code> evaluates to a record,
the construction <code>e -. l</code> will produce a new record
where the field <code>l</code> has been removed (if present).
</p>

<p>
If the  x-expression <code>e</code> evaluates to an x-sequence,
the construction <code>e/</code> will result in a new x-sequence
obtained by taking in order all the children of the XML elements
from the sequence <code>e</code>. For instance, the x-expression
<code><![CDATA[[<a>[ 1 2 3 ] 4 5 <b>[ 6 7 8 ] ]/]]></code>
evaluates to the x-value <code>[ 1 2 3 6 7 8 ]</code>.
</p>

<p>
If the  x-expression <code>e</code> evaluates to an x-sequence,
the construction <code>e.(t)</code> (where <code>t</code> is an
x-type) will result in a new x-sequence
obtained by filtering <code>e</code> to keep only the elements
of type <code>t</code>. For instance, the x-expression
<code><![CDATA[[<a>[ 1 2 3 ] 4 5 <b>[ 6 7 8 ] ].(Int)]]></code>
evaluates to the x-value <code>[ 4 5 ]</code>.
</p>
</section>

<section title="Dynamic type checking">

<p>
If <code>e</code> is an x-expression and <code>t</code> is an x-type,
the construction <code>(e :? t)</code> returns the same
result as <code>e</code> if it has type <code>t</code>, and otherwise
raises a <code>Failure</code> exception whose argument explains
why this is not the case.
</p>

<sample><![CDATA[{{ON}}
# let f (x : {{ Any }}) = {{ (x :? <a>[ Int* ] ) }} in
  f {{ <a>[ 1 2 '3' ] }};;
Exception:
Failure
 "Value <a>[ 1 2 '3' ] does not match type <a>[ Int* ]\nValue '3' does not match type Int\n".
]]></sample>
</section>

<section title="Pattern matching">

<p>
OCamlDuce comes with a powerful pattern matching operation.
X-patterns are described <a href="#patterns">below</a>.
The syntax for the pattern matching operation is:
<code>match e with p1 -> e1 | ... | pn -> en</code>.
The type-system ensures exhaustivivity for the pattern matching
and infers precise types for the capture variables.
It is also possile to use x-pattern matching as a regular
OCaml expression; x-patterns must be surrounded by {{..}}, e.g.:
   match e with {{p1}} -> e1 | ... | {{pn}} -> en
   function {{p1}} -> e1 | ... | {{pn}} -> en
</p>

<note>
currently it is impossible to mix normal OCaml patterns and x-patterns
in a single pattern matching.
</note>

</section>

<section title="Local binding">

<p>
The x-expression <code>let p=e1 in e2</code> is equivalent to 
<code>match e1 with p -> e2</code>. There is also an local binding
with an x-pattern in OCaml expressions: <code>let {{p}}=e1 in
e2</code>.
</p>

</section>


<section title="Iterators">

<p>
OCamlDuce comes with a sequence iterator 
<code>map e with p1 -> e1 | ... | pn -> en</code> and
a tree iterator
<code>map* e with p1 -> e1 | ... | pn -> en</code>.
</p>

<p>
For both constructions, the argument must evaluate to a sequence.
The <code>map</code> iterator applies the patterns to each element
of this sequence in turns and produces a new sequence by concatenating
all the results (all the right-hand sides must thus produce a
sequence). The set of patterns must be exhaustive for all the possible
elements of the input sequence.
</p>

<p>
The tree iterator is similar except that the patterns need not be
exhaustive. If some element of the input sequence is not matched,
it is simply copied into the result unless it is an XML element. In
this case, the transformation is applied recursively to its content.
</p>

</section>

<section title="OCaml constructions">

<p>
As a convenience, some of the OCaml expression constructors
are allowed as x-expressions (without a need to go back to OCaml
with double curly braces): (unqualified) value identifiers and
function calls.
</p>

</section>

</box>

<box title="More on x-types" link="types">

<p>
We have seen how to write simple x-types. We can then combine
them with Boolean connectives:
</p>

<ul>
<li><code>t1 &amp; t2</code>: intersection;</li>
<li><code>t1 | t2</code>: union;</li>
<li><code>t1 - t2</code>: difference.</li>
</ul>

<p>
The empty x-type is written <code>Empty</code> (it contains no value),
and the universal x-type is written <code>Any</code> (it contains
all the x-values) or <code>_</code>.
</p>

<p>
When an x-type has been bound to some OCaml identifier 
(<code>{{ON}}type t = {{...}}</code>), it is possible to use
this identifier in another x-type. Recursive definitions
are allowed:
</p>

<sample><![CDATA[{{ON}}
type t1 = {{ <a>[ t2* ] }}
and  t2 = {{ <b>[ t1* ] }}
]]></sample>

<p>
Note that x-values are always finite and acyclic. The type checker
detects type definition which would yield empty types:
</p>

<sample><![CDATA[{{ON}}
# type t = {{ <a>[ t+ ] }};;
This definition yields an empty type
]]></sample>

<p>
If <code>t1</code> and <code>t2</code> are record x-types,
we can combine them with the infix <code>++</code> operator, which
mimics the corresponding operator on expressions (record
concatenation). Similarly, we can use the infix <code>@</code>
concatenation operator on sequence x-types.
</p>

</box>

<box title="X-patterns" link="patterns">

<p>
X-patterns follow the same syntax as X-types. In particular,
any X-type is a valid X-pattern. In addition to X-types constructors, 
X-patterns can have:
</p>

<ul>
<li>capture variables (lowercase OCaml identifiers);</li>
<li>constant bindings <code>(x := c)</code> where x is a capture 
  variable and c is 
  a literal x-constant (this pattern always succeeds and returns the 
  binding x->c).</li>
</ul>

<p>
In record x-patterns, it is possible to omit the <code>=p</code> part of a field.
The content is then replaced with the label name considered as
a capture variable. E.g.  <code>{ x y=p }</code> is equivalent to 
<code>{ x=x y=p }</code>.</p>

<p>It is also possible to add an "else" clause:
<code>{ x = (a,_)|(a:=3) }</code>
will accept any record with atmost the field <code>x</code>. If the content
is a pair, the capture variable a will be bound to its component;
otherwise, it is set to <code>3</code>.</p>

<p>
In regular expressions, it is possible to extract whole subsequences
with the notation <code>x::R</code>, e.g.:  <code>[ _* x::Int+ _* ]</code>
</p>

<p>
If the same sequence capture variable appears several times (or below a
repetition) in a regexp, it is bound to the concatenation of all
matched subsequences. E.g.: <code>[ (x::Int | _)* ]</code> will
collect in <code>x</code> all the elements of type <code>Int</code> from
a sequence.</p>

<p>
642
643
The regexp operators <code>+,*,?</code> are greedy by default (they match as long
as possible).  They admit non-greedy variants <code>+?,*?,??</code>.
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
</p>
</box>

<box title="Namespace bindings" link="ns">

<p>
The binding of namespace prefixes to URIs
can be done either by toplevel phrases (structure items) or 
by local declarations:
</p>

<sample>{{ON}}
# {{ namespace ns = "http://..." }};;
# let x = {{ `ns: x }};;
val x : {{`ns:x}} = {{`ns:x}}
# let x = {{ let namespace ns = "http://..." in `ns:x }};;
val x : {{`ns:x}} = {{`ns:x}}
</sample>

<p>The toplevel definitions can also appear in module interfaces
(signatures). A toplevel prefix binding is not exported by a module: its scope
is limited to the current structure or signature. It is possible
to specify a default namespace, and to reset it:
</p>

<sample>{{ON}}
# {{ namespace "http://..." }};;
# {{ `x }};;
- : {{`ns1:x}} = {{`ns1:x}}
# {{ namespace "" }};;
# {{ `x }};;
- : {{`x}} = {{`x}}
</sample>

<p>
Note that the value pretty-printer invented some prefix
for the namespace URI. The default prefix declaration also have a
local form <code> let namespace "..." in ... </code>.
</p>

</box>

686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
<box title="More on type-checking" link="typecheck">

<section title="Type inference">

<p>
As we said above, the programmer is sometimes required to provide type
annotations. To know where to put these annotation, it is necessary to
get a basic understanding of how type-checking works.
</p>

<p>
The OCaml type-checker is run first to detect which sub-expressions
are of the x-kind. A second ML type-checking pass is then done to
introduce subsumption (implicit subtyping) steps where allowed. After
these two passes, the OCamlDuce type checker obtains a data-flow summary of
x-values in the whole compilation unit. This is a directed graph,
whose edges represent either simple data-flow or complex operation
on x-values. The nodes of the graph can be thought as x-type
variables. A data-flow edge corresponds to a subtyping constraints,
and an operation edge corresponds to a symbolic constraints which
mimics the corresponding operation on values.
</p>

<p>
Some of the nodes are given an explicit type by the programmer,
through type annotations (on expressions or function arguments)
or the other usual mechanism in ML (data type declarations,
signatures, ...).
</p>

<p>
Also, if there is a loop with only subtyping edges in the graph,
all the nodes on the loop are merged together.
</p>

<p>
After this operation, the graph is required to be acyclic (assuming
that the nodes with an explicit type are removed from the graph). It
is the responsibility of the programmer to provide enough type
annotation to achieve this property. Otherwise, a type error
is issued.
</p>

<sample><![CDATA[{{ON}}
# let rec f x = match x with 0 -> {{ [] }} | n -> {{ f {{n-1}} @ ['.'] }};;
Cycle detected: cannot type-check
# let rec f x : {{ String }} = match x with 0 -> {{ [] }} | n -> {{ f {{n-1}} @ ['.'] }};;
val f : int -> {{String}} = <fun>]]>
</sample>

<p>
In the example above, there is a cycle between the result type for
<code>f</code> and the type for the sub-expression <code>{{ON}}f
{{n-1}}</code>. It is here broken with a type annotation on the result; it could
have been broken by a type annotation on the expression  <code>{{ON}}f
{{n-1}}</code>, or on the function <code>f</code> itself, or by a
module signature.
</p>

<p>
Let us study another simple example:
</p>

<sample>{{ON}}
# let f x = {{ x + 1 }} in f {{ 2 }}, f {{ 3 }};;
- : {{3--4}} * {{3--4}} = ({{3}}, {{4}})
</sample>

<p>
The type-checkers detects that the two x-values <code>2</code> and
<code>3</code> can flow to the argument of <code>f</code>. Its body
is thus type-checked with the assumption that <code>x</code> has type
<code>2--3</code>. The computed result type is then <code>3--4</code>.
</p>


<p>
The type-inference process described above is global by nature. The
acyclicity condition is only imposed after a whole compilation unit
has been type-checked by OCaml (and the information from the module
interface as been integrated). When a type variable is inferred to
be of the x-kind, it is never generalized. As a consequence, there
is no parametric polymorphism on x-types.
</p>

<p>
In the toplevel, type-checking is done after each phrase. Consider
the following session:
</p>

<sample><![CDATA[{{ON}}
# let f x = {{ x + 1 }};;
val f : {{Empty}} -> {{Empty}} = <fun>
# let a = f {{ 2 }};;
Subtyping failed 2 <= Empty
Sample:
2
]]></sample>

<p>
The function <code>f</code> is inferred to have type
<code>{{ON}}{{Empty}} -> {{Empty}}</code> because when the first
phrase is type-checked, the data-flow graph says that no value
can flow to <code>x</code>, and thus the input type is empty
(and similarly for the result type). If the two phrases
were type-checked together (which would be the case it they had
been compiled by the compiler, not in the toplevel), the type checker
would have correctly inferred that the input type for <code>f</code>
must contain <code>2</code>.
</p>

</section>

<section title="Implicit subtyping">

<p>
Coercion from an x-type to a super type is automatic in OCamlDuce.
However, this automatic subsumption does not carry over to OCaml
type constructor, even if there are covariant. Consider:
</p>

<sample><![CDATA[{{ON}}
# let f (x : {{ Int }} * {{ Int }}) = 1;;
val f : {{Int}} * {{Int}} -> int = <fun>
# let g (x : {{ 0 }} * {{ 0 }}) = f x;;
This expression has type {{0}} * {{0}} but is here used with type
  {{Int}} * {{Int}}
# let g (x : {{ 0 }} * {{ 0 }}) = let a,b = x in f (a,b);;
val g : {{0}} * {{0}} -> int = <fun>
# let g (x : {{ 0 }} * {{ 0 }}) = f (x :> {{ Int }} * {{ Int }});;
val g : {{0}} * {{0}} -> int = <fun>
]]></sample>

<p>
The first attempt to define <code>g</code> fails because the type for
<code>x</code> is not an x-type and thus subsumption does not
apply. In the second attempt, we extract the two components of the
pair; since they are inferred to be x-values, subtyping applies to
both of them. Thus, when the pair <code>(a,b)</code> is reconstructed,
it is legal to unify its type with the input type of <code>f</code>.
The third definition for <code>g</code> gives an alternative solution:
using explicit OCaml type coercions.
</p>

</section>

</box>

<box title="Exchanging values" link="transl">

<p>
OCamlDuce strongly seperates regular OCaml values from the new
x-values. They have different syntax, expressions, types, patterns,
and even type-checking algorithms. This strong segregation is key point
which allowed a simple integration between very different type
systems.
</p>

<p>
At some point, it is still necessary to cross the frontier and
translate OCaml values to x-values or the opposite.
</p>

<p>
Fortunately, OCamlDuce provides automatic translations in both
directions. Instead of double curly braces, you can
enclose x-expressions in curly brace+colon <code>{: ... :}</code>
(here, the <code>...</code> is an x-expression).
The effect is to translate the result of the x-expression
(which must be an x-value) to an OCaml value. Similarly,
in an x-expression, you can obtain the x-translation of
an OCaml value with the same syntax <code>{: ... :}</code>
(here, the <code>...</code> is an OCaml expression).
</p>

<p>
Here is how the translation works. To each OCaml type <code>t</code>,
we associate an x-type <code>T(t)</code> and a pair of translation
function between <code>t</code> and <code>T(t)</code>.
Actually, not all the features are supported. For instance,
free type variables, abstract types, object types, non-regular
recursive types cannot be translated. In particular, since
type variables are not allowed, the OCaml type must be fully known.
</p>

<p>
872
873
The translation for an OCaml type <code>t</code> is defined by structural
induction on <code>t</code>. Sum types are
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
translated to union types: a constant constructor <code>A</code> is
translated to the qualified name <code>`A</code>; a non-constant
constructor <code>A of t1 * ... * tn</code> is translated to
<code>&lt;A>[ T(t1) ... T(tn) ]</code>. Closed polymorphic variants
have the same translation. Record types are translated to closed
record x-types. Some other translations:
</p>

<table border="1">
<tr><th>Caml type t</th> <th>X-type T(t)</th></tr>
<tr><td><code>int</code></td> <td><code>Int</code></td></tr>
<tr><td><code>int32</code></td> <td><code>Int32</code></td></tr>
<tr><td><code>int64</code></td> <td><code>Int64</code></td></tr>
<tr><td><code>string</code></td> <td><code>Latin1</code></td></tr>
<tr><td><code>t list</code></td> <td><code>[T(t)*]</code></td></tr>
<tr><td><code>t array</code></td> <td><code>[T(t)*]</code></td></tr>
<tr><td><code>unit</code></td> <td><code>[]</code></td></tr>
<tr><td><code>char</code></td> <td><code>Latin1Char</code></td></tr>
<tr><td><code>{{t}}</code></td> <td><code>t</code></td></tr>
</table>

<p>
Here is an example:
</p>

<sample>{{ON}}
# let f (x : {{ Int }}) = {{ x + 1 }} in List.map f {: [ 1 2 3 ] :};;
- : {{Int}} list = [{{2}}; {{3}}; {{4}}]
</sample>
903
904

<p>
905
906
907
908
In this example, the result type of the translation is inferred
to be <code>{{ON}}{{ Int }} list</code> (because the type for
<code>f</code> is given). The corresponding x-type
is <code>{{ON}}{{ [Int*] }}</code>.
909
</p>
910
911
912

</box>

913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
<box title="The standard library" link="stdlib">

<p>
In OCamlDuce, the Num library from OCaml is included in the standard
library. In addition, there are two new module called
<code>Ocamlduce</code> and <code>Cduce_types</code> in the standard library.
</p>

<p>
The module <code>Cduce_types</code> gives access to the internal
representation of x-values. It is currently undocumented.
</p>

<p>
The module <code>Ocamlduce</code> provides several useful
functionality x-values. See the <a href="http://yquem.inria.fr/~frisch/ocamlcduce/doc/ocamlduce/Ocamlduce.html">ocamldoc</a> generated
documentation for a description of its interface.
</p>

</box>

<box title="Code samples" link="code">


<section title="Parsing XML files">

<p>
OCamlDuce does not come with any built-in XML parser. However,
the <a href="http://yquem.inria.fr/~frisch/ocamlcduce/doc/ocamlduce/Ocamlduce.Load.html"><code>Ocamlduce.Load</code></a> module in the standard library
makes it easy to plug existing XML parsers. Here is some
code which demonstrate how to do that with three of
the most popular OCaml XML parser libraries:
</p>

<ul>
<li><a
href="http://yquem.inria.fr/~frisch/ocamlcduce/samples/pxp/">PXP</a></li>
<li><a
href="http://yquem.inria.fr/~frisch/ocamlcduce/samples/expat/">Expat</a></li>
<li><a href="http://yquem.inria.fr/~frisch/ocamlcduce/samples/xmllight/">Xml-light</a></li>
</ul>

</section>

<section title="Converting DTD to OCamlDuce types">

<p>
This <a href="http://yquem.inria.fr/~frisch/ocamlcduce/samples/dtd2types/">tool</a> produces a set of OCamlDuce type declarations
from a DTD. It requires PXP.
</p>

<note>This application does not use any of the new features, but it
can be useful in the development of OCamlDuce applications.
</note>

</section>

<section title="Parsing XML Schema, producing valid XHTML output">

<p>
This <a
href="http://yquem.inria.fr/~frisch/ocamlcduce/samples/schema/">application</a>
parses XML Schema Definitions (.xsd files), and produces summaries
(toplevel declaration names) in XHTML. OCamlDuce type system ensures
that the parser is coherent with the input XML type (any valid XML
Schema is accepted) and that the printer is coherent with the output
XML type (it is necessarily a valid XHTML document).
</p>

<p>
Of course, for such a simple transformation, parsing the XML document
into an internal representation is not necessary. A direct XML-to-XML
transformation would be easy to write. We wanted to illustrate
a complex parsing of XML.
</p>

<p>
It it interesting to introduce errors in the parser
<code>schema_loader.ml</code> or the printer
<code>dump_schema.ml</code> and see how the type system catch them.
</p>

<note>
The application uses XML Light to parse XML document.
</note>

<note>
Some features of XML Schema are not parsed, such as
<code>redefine</code> elements or substitution groups.
</note>

</section>

</box>

1008
</page>